自動終了してくれる非同期サービス
- Android
 - 
                        
2011-11-07                                                                                                 - 更新:2013-01-09                                             
この記事は最終更新日から1年以上経過しています。
                    
                    時間のかかる処理を非同期で実行するためのクラスIntentServiceを利用します。
メインスレッドとは別のプロセスで処理が実行されます。
これはメインのActivityに依存せず処理をするので、Activityが終了しても処理が
終了するまで続きます。
クラスの定義
import android.app.IntentService;
import android.content.Intent;
import android.util.Log;
public class MyIntentService extends IntentService {
    final static String TAG = "MyIntentService";
    
    public MyIntentService(){
        super("MyIntentService");
    }
    
    @Override
    protected void onHandleIntent(Intent intent) {
        try{
            Log.d(TAG, "onHandleIntent");
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    
    @Override
    public void onDestroy(){
        super.onDestroy();
        Log.d(TAG, "onDestroy");
    }
}
Activityからの呼び出し
Intent intent = new Intent(Intent.ACTION_SYNC, null, this, MyIntentService.class); // または // Intent intent = new Intent(this, MyIntentService.class); this.startService(intent);
AndroidManifest.xml
applicationタグ内に以下を記述
<service android:name="MyIntentService"></service>
IntentServiceに引数を渡すにはstartServiceの前に以下を記述
intent.putExtra("IntentService_Extra", "ExtraText"); 
IntentService側で引数を取得
intent.getStringExtra("IntentService_Extra");
非同期処理の中でToastを表示したいとき、通常の実行では表示されないので以下のようにします。
必要なimport
import android.os.Handler; import android.widget.Toast;
クラス内に以下を定義
private Handler mHandler;
コンストラクタに以下を記述
mHandler = new Handler();
使用例
mHandler.post(new DisplayToast("文字列"));
以下のメソッドを用意しておく
private class DisplayToast implements Runnable{
    String mText;
    public DisplayToast(String text){
        mText = text;
        }
    public void run(){
        Toast.makeText(getApplicationContext(), mText, Toast.LENGTH_SHORT).show();
        }
}
                    
                    
                    
                
                        この記事がお役に立ちましたらシェアお願いします
                    
                    
                
                        4,098 views 
                                                                    
                    
                



