開始時,我想爲壞的英語道歉。活動崩潰後的Android停止後臺服務
有我的問題:
我有一個Android的服務,這是活動運行時,在後臺運行。 (此服務以指定的時間間隔與服務器同步用戶數據)。
public class CService extends Service
{
private Boolean isDestroyed;
@Override
public int onStartCommand (Intent intent, int flags, int startId)
{
if (intent != null)
{
new Thread(new Runnable()
{
//run new thread to disable flush memory for android and destroy this service
@Override
public void run()
{
this.isDestroyed = Boolean.FALSE
while(!this.isDestroyed)
{
//loop until service isn't destroyed
}
}
}).start();
}
return Service.START_NOT_STICKY;
}
@Override
public void onDestroy()
{
//THIS ISNT CALLED FROM uncaughtException IN ACTIVITY BUT from onDestroy method is this called.
//when is service destroyed then onDestroy is called and loop finish
this.isDestroyed = Boolean.TRUE;
}
}
並從onCreateMethod中的活動開始。此活動實現Thread.UncaughtExceptionHandler並在onCreate方法中註冊以捕獲活動中的所有意外異常。當活動中的某些事件拋出異常方法uncaughtException被調用時,服務應該停止在stopService(serviceIntent);但onDestoy服務不叫。但是當activity中的onDestroy方法被調用時(用戶按下然後返回按鈕)服務被成功停止並且在CService中調用onDestoroy。
public class CActivity extends Activity implements Thread.UncaughtExceptionHandler
{
private Thread.UncaughtExceptionHandler defaultUEH;
@Override
protected void onCreate (Bundle savedInstanceState)
{
this.defaultUEH = Thread.getDefaultUncaughtExceptionHandler();
// create intent for service
Intent serviceIntent = new Intent(this, CService.class);
// run service
startService(serviceIntent);
//set default handler when application crash
Thread.setDefaultUncaughtExceptionHandler(this);
super.onCreate(savedInstanceState);
}
@Override
public void uncaughtException (Thread thread, Throwable ex)
{
//THIS DOESN'T WORK
//when global exception in activity is throws then this method is called.
Intent serviceIntent = new Intent(this, CService.class);
//method to service stop is called. BUT THIS METHOD DON'T CALL onDestroy in CService
stopService(serviceIntent);
defaultUEH.uncaughtException(thread, ex);
}
@Override
public void onDestroy()
{
//this work fine
Intent serviceIntent = new Intent(this, CService.class);
stopService(serviceIntent);
super.onDestroy();
}
}
當活動崩潰時,我需要停止後臺服務。當機器人關閉活動並在堆棧中啓動以前的活動(即登錄屏幕)時,Bacause現在不記錄用戶。
感謝您的建議。
是您從另一個進程運行的服務嗎? –
服務運行並停止在onCreate方法中運行的相同活動,並在uncaughtException方法中彎腰。 – Kamikazee