ぽんこつ備忘録

自分用のWatsonやらAndroidやらやったことの備忘録 さぼりがち

AsyncTaskのあれこれ

Javaに対しての勉強不足が相まって依頼されたアプリ作成が滞ってしまったため簡単に備忘録

public class UploadTask extends AsyncTask<String, Void, Response> {
    private Context context;
   
    public UploadTask(Context context) {
        super();
        this.context = context;
    }

    // 非同期処理
    @Override
    protected Response doInBackground(String... params) {

        // パラメータで送った値を受け取る
        String lat = params[0];
        String lng = params[1];
       
        // 処理を記述 

        // 結果を下に送る
        return response;
    }

    // 非同期処理終了後、結果をメインスレッドに返す
    @Override
    protected void onPostExecute(Response response) {
        super.onPostExecute(response);

        if (response != null) {

            // 完了したら画面遷移する
            Intent intent = new Intent(context, hogehogeActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            context.startActivity(intent);
        } else {
            Toast.makeText(context, R.string.post_failed, Toast.LENGTH_SHORT).show();
            Log.w(TAG + "POST:", "error: " + "responseがNULL");
        }
    }
}

んで使うときは

 UploadTask task = new UploadTask(context);
        task.execute(
                String.valueOf(lat), // lat
                String.valueOf(lng), // lng
        );

って書いてやればいい