У меня есть служба, которую я хочу связать и запустить в режиме переднего плана.Он включает в себя следующее:
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()
никогда не печатается.
И позже, когда я пытаюсь привязать действие к Сервису, я всегда получаю ссылку null
для Сервиса.Похоже, что onServiceConnected()
не вызывается, поскольку оператор журнала не печатает:
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()" );
}
Когда я пытаюсь использовать thermoServiceRef
в действии onResume()
, я получаю NullPointerException
.
В основном весь этот код адаптирован прямо из примеров для Android, и я не могу понять, в чем дело.Я использовал подобный код в других приложениях, которые работали, хотя я впервые пытался использовать режим Foreground для Службы.
Теперь мне приходит в голову, что это может быть связано с другой проблемой, которую я заметил: когда я пытаюсь отменить привязку Сервиса в onDestroy()
Действия, я получаю сообщение, что это не таксвязано.
Обновление: вот декларация сервиса в манифесте:
<service
android:name=".ThermocoupleService"
android:enabled="true"
android:exported="false"
android:description="@string/service_description" >
</service>