Android Studio(メモリストのアプリ10_終了時の処理について)

■OnStop, OnPause, OnDestroyとかの処理
メモリストのアプリを終了させるときに、そのときのリストをSQLiteに書き込みたい。そのため、終了する際の処理について調べた。Androidのアプリのライフサイクルとしては、OnPause, OnStop, OnDestroyの順番に呼び出されるよう。ただ、OnDestroyは必ず呼び出されるわけでもないようなので、ここにSQLiteへの書き込み処理を入れてもうまくいかなかった。

一方で、OnPauseやOnStopのメソッドは、スマホの「□」を押すと実行されるよう。下のように、ログ表示とスレッドスリープで、1秒ごとにログが出るようなコードをOnPauseなどで実行させると、下の画面のようにログが表示される。

    @Override
    protected void onPause() {
        super.onPause();
        Log.i("pause1", "中断");
        for (int i = 0; i < 10; i++) {
            try {
                Log.i("bb", Integer.valueOf(i).toString() + "aaa");
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
        Log.i("pause2", "中断2");
    }

そのため、この状態でSQLiteへ書き込めるようにすれば問題ないかもしれない。

他の方法としてバックグラウンドで処理を行うサービスというものがあった。簡単なサンプルとして、下のようなものを試してみた。

AndroidManifest.xmlにserviceを追加。ここの名前は、下で作成するクラス。

…
        </activity>
        <service android:name=".HelloIntentService" />
    </application>
…

IntentService(Serviceのサブクラス)のサブクラスとしてHelloIntentServiceを作成。

package com.example.sampleproject010_ondestroy;


import android.app.IntentService;
import android.content.Intent;
import android.util.Log;

public class HelloIntentService extends IntentService {

    public HelloIntentService() {
        super("HelloIntentService");
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        try {
            for (int i = 0; i < 10; i++) {
                Log.i("dd", Integer.valueOf(i).toString() + "service");
                Thread.sleep(1000);
            }
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }

        Log.i("Service", "サービス");
        this.stopSelf();

    }
}

下のコードをどこか(ここではOnStop)に入れて、サービスを実行。

        Intent intent = new Intent(this, HelloIntentService.class);
        startService(intent);

結果が下のもの。
OnStopの始めの方に入れていても、OnStop内の処理が終わった後に実行されるよう。また、サービス実行時にアプリを終了させるとOnDestroyが呼び出された(長い処理にすると途中で止まってしまうけど)。

この辺りのどこかに処理を追加すれば、アプリ終了時の処理として使えそう。