Aは、現在のスレッドでデフォルト( egのHandler
ないコンストラクター)ごとにコードを実行/メッセージを処理します。ほとんどの場合、これがメインスレッドです。別のスレッドで実行する場合は、使用するスレッドを指定する必要があります。Looper
new Handler()
Looper
Androidには、を使用HandlerThread
してを作成するThread
というユーティリティクラスがありますLooper
。
簡単な例:
public class MyActivity extends Activity {
private Handler mHandler;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
HandlerThread handlerThread = new HandlerThread("background-handler");
handlerThread.start();
Looper looper = handlerThread.getLooper();
mHandler = new Handler(looper);
mHandler.post(new Runnable() {
public void run() {
// code executed in handlerThread
}
});
}
@Override
protected void onDestroy() {
super.onDestroy();
// stops the HandlerThread
mHandler.getLooper().quit();
}
}
タスクに必要な情報が一部であり、報告する必要がない場合は、を使用しIntentService
ます。アクティビティライフサイクルでアクティビティが再作成されても、それらは怒りません。
Service
独自のファイルに小さなファイルを作成します
public class SaveService extends IntentService {
public SaveService() {
super("SaveService");
}
@Override
protected void onHandleIntent(Intent intent) {
if ("com.example.action.SAVE".equals(intent.getAction())) {
String player = intent.getStringExtra("com.example.player");
int score = intent.getIntExtra("com.example.score", -1);
magicHttpSave(player, score); // assuming there is an implementation here
}
}
}
に追加しますAndroidManifest.xml
<application ....
<service android:name=".SaveService" />
</application>
そしてあなたのコードでそれを始めてください
Intent intent = new Intent(this /* context */, SaveService.class);
intent.setAction("com.example.action.SAVE");
intent.putExtra("com.example.player", "John123");
intent.putExtra("com.example.score", 5123);
startService(intent);
IntentService#onHandleIntent()
すでにバックグラウンドスレッドで実行されているので、気にする必要はありません。