はじめに、下手な英語でお詫び申し上げます。
私の問題があります:
アクティビティが実行されているときにバックグラウンドで実行される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 は呼び出されません。しかし、アクティビティの onDestroy メソッドが呼び出されると (ユーザーがボタンを押して戻る)、サービスが正常に停止し、CService の onDestroy が呼び出されます。
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();
}
}
アクティビティがクラッシュしたら、バックグラウンド サービスを停止する必要があります。Android がアクティビティを閉じて、スタック (ログイン画面) で前のアクティビティを開始すると、ユーザーがログに記録されなくなります。
提案をありがとう。