我正在开发一个使用服务的简单计时器应用程序(这是为了让计时器保持运行,即使应用程序已经关闭)。
计时器逻辑由服务处理,我的Fragment只是绑定到服务以获取数据。我的问题是,当我启动计时器并关闭应用程序时。当我再次打开它时,计时器会绑定到一个新的服务实例,因此它认为它没有运行。
这只发生在我测试的一个设备中(在模拟器和其他4个设备中工作正常)。怎么会发生什么?
以下是一些代码:
片段onStart
:
public void onStart() {
super.onStart();
Intent intent = createServiceIntent();
getActivity().startService(intent);
getActivity()
.bindService(
intent,
mServiceConnection,
Context.BIND_ABOVE_CLIENT
);
}
服务构造函数,onCreate
,onStart
,onBind
和onUnbind
public ChronometerService() {
Log.d(Config.APP_TAG, "CREATING CHRONOMETER SERVICE INSTANCE");
}
@Override
public void onCreate()
{
super.onCreate();
this.mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
this.mBinder = new ChronometerBinder();
this.mPauses = new LinkedList<>();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId){
return START_STICKY;
}
@Override
public IBinder onBind(Intent intent) {
Log.d(Config.APP_TAG, "SERVICE BIND. AND WAS" + (mRunning ? "" : "N'T") + " RUNNING");
if( ! mRunning ) {
this.mPauseLength = 0;
this.mStoppedAt = 0;
this.mBase = 0;
}
return mBinder;
}
@Override
public boolean onUnbind(Intent intent) {
if( ! mRunning) {
stopForeground(true);
stopSelf();
}
return true;
}
在片段中点击开始按钮时,将调用服务中的以下方法:
public void start() {
if(this.mBase == 0) {
reset();
this.mBase = now();
}else{
mPauseLength += now() - mStoppedAt;
}
Intent i = new Intent(this, MainActivity.class);
i.putExtra(MainActivity.CURRENT_FRAGMENT, MainActivity.CHRONOMETER_TAG);
PendingIntent intent = PendingIntent.getActivity(this, SERVICE_ID, i, PendingIntent.FLAG_UPDATE_CURRENT);
mNotificationBuilder = new NotificationCompat.Builder(this);
mNotificationBuilder.setContentTitle(getResources().getString(R.string.chronometer_title))
.setSmallIcon(R.drawable.ic_timer_white_48dp)
.setContentIntent(intent);
Notification n = mNotificationBuilder.build();
startForeground(SERVICE_ID, n);
mRunning = true;
update();
}
在应用程序运行正常的设备中,在日志中我得到:
CREATING CHRONOMETER SERVICE INSTANCE
SERVICE BIND. AND WASN'T RUNNING
(Closing the app)
SERVICE BIND. AND WAS RUNNING
在设备中它没有工作我得到:
CREATING CHRONOMETER SERVICE INSTANCE
SERVICE BIND. AND WASN'T RUNNING
(Closing the app)
CREATING CHRONOMETER SERVICE INSTANCE
SERVICE BIND. AND WASN'T RUNNING
希望你能帮助我。