2016-05-15 30 views
0

我正在開發一個使用服務的簡單計時器應用程序(即使應用程序已關閉,此功能也會保持計時器運行)。某些設備中的Android複製服務

計時器的邏輯是由服務處理,我的Fragment只是綁定到服務來獲取數據。我的問題是,當我啓動計時器並關閉應用程序時。當我再次打開時,計時器綁定到服務的一個新實例,所以它認爲它沒有運行。

這隻發生在我測試過的一個設備中(在仿真器和其他4個設備上工作正常)。怎麼會發生?

下面是一些代碼:

片段onStart

public void onStart() { 
    super.onStart(); 
    Intent intent = createServiceIntent(); 
    getActivity().startService(intent); 
    getActivity() 
     .bindService(
      intent, 
      mServiceConnection, 
      Context.BIND_ABOVE_CLIENT 
     ); 

} 

服務構造,onCreateonStartonBindonUnbind

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 

希望能幫到你我。

+0

我認爲你需要堅持'mRunning'的價值。 – muratgu

回答

0

解決:

問題不是我的代碼畢竟。問題是Purify

這是殺了我的服務。將我的應用程序添加到白名單後,問題就解決了。

相關問題