java My Service表示它正在运行,但其状态尚不清楚,似乎没有绑定
我有一个服务,我想在前台模式下绑定和启动。它包括:
public int onStartCommand( Intent intent, int flags, int startId ) {
super.onStartCommand( intent, flags, startId );
if( DEBUG ) Log.d( TAG, "onStartCommand() entered"); // never prints
runningNotification = new NotificationCompat.Builder( getApplicationContext(), "Channel 1" )
.setContentTitle( "PID Service Running" )
.setCategory( CATEGORY_SERVICE )
.setOngoing( true )
.build();
startForeground( SERVICE_NOTIFICATION_ID, runningNotification );
我在我的活动中开始(已经尝试了onCreate()
和onStart()
):
bindThermoServiceIntent = new Intent( getApplicationContext(), ThermocoupleService.class );
serviceComponentName = getApplicationContext().startService( bindThermoServiceIntent ); // bind to it AND start it
if( DEBUG ) { // seems to never fail to start
if( serviceComponentName != null ) Log.d( TAG, "Service running with ComponentName " + serviceComponentName.toShortString() ); // looks OK
else throw new NullPointerException( "Attempt to start Service failed" );
}
if( !( serviceBound = bindService( bindThermoServiceIntent, /*ServiceConnection*/ this, Context.BIND_AUTO_CREATE ) ) )
throw new RuntimeException( TAG + ": bindService() call in onCreate() failed" ); // no exception
它总是用右边的ComponentName
记录“服务正在运行”,但onStartCommand()
中的log语句永远不会打印
后来,当我尝试将活动绑定到服务时,我总是会得到服务的null
引用。似乎没有调用onServiceConnected()
,因为log语句没有打印:
public void onServiceConnected( ComponentName className, IBinder service ) {
Log.d( TAG, "Entering onServiceConnected()" );
// We've bound to Service, cast the IBinder and get Service instance
thermoBinder = (ThermocoupleService.LocalBinder) service;
thermoServiceRef = thermoBinder.getService();
if( thermoServiceRef == null ) throw new RuntimeException( TAG
+ ": onServiceConnected returned null from getService()" );
Log.d( TAG, "Finished onServiceConnected()" );
}
当我试图在活动的onResume()
中使用thermoServiceRef
时,我得到一个NullPointerException
基本上,所有这些代码都是直接从Android示例中改编的,我不知道哪里出了问题。我在其他应用程序中也使用过类似的代码,不过这是我第一次尝试使用前台模式进行服务
现在我突然想到,这可能与我注意到的另一个问题有关:当我试图在活动的onDestroy()
中解除服务绑定时,我收到一条消息,它没有连接
更新:以下是清单中的服务声明:
<service
安卓:name=".ThermocoupleService"
安卓:enabled="true"
安卓:exported="false"
安卓:description="@string/service_description" >
</service>
# 1 楼答案
在查看了你在GitHub上的整个项目之后,我想我可以指出哪里出了问题
您错误地假设
startService()
/bindService()
同步创建Service
。如果尚未填充Service
引用,则应用程序将在onResume()
中崩溃。对于Android来说,创建Service
的时间还不够。如果它没有崩溃,Service.onCreated()
将在onResume()
返回后不久被调用TL;DR:期望异步
Service
创建。(“Asynchronous”这个词在这里不太合适,b/c它确实发生在UI线程上。也许“Delayed”更好)