about 5 years ago

Androidで非同期処理はThreadやAsycTask、Serviceでできる。Serviceはアプリケーションがフォアグラウンドでなくても処理が中断されないことが保証されている点が他の非同期処理と異なる。IntentSerivceはSerivceのサブクラスでServiceと同じように使えるが、Serviceより扱いが簡単で、明示的に終了させなくてもタスクがなくなり次第自動的に終了してくれる。

package com.example.servicedemo;

import java.util.HashMap;

import com.example.servicedemo.APIServiceTask.APICallbackInterface;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class ResultReceiverDemoActivity extends Activity implements APICallbackInterface{

    TextView txtview;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        txtview = (TextView) findViewById(R.id.txtview);
        HashMap<String, String> params = new HashMap<String, String>();
        params.put("param1", "hello1");
        params.put("param2", "hello2");
        params.put("param3", "hello3");
        params.put("param4", "hello4");
        params.put("param5", "hello5");
        params.put("param6", "hello6");
        params.put("param7", "hello7");
        new APIServiceTask().request(this, "dummy", this, params);
    }

    @Override
    public void onAPIResult(String result) {
        txtview.setText(result);
    }
}
package com.example.servicedemo;

import java.util.HashMap;
import java.util.Map.Entry;
import java.util.Set;

import android.app.IntentService;
import android.content.Intent;
import android.os.Bundle;
import android.os.ResultReceiver;

public class APIService extends IntentService {
    
    ResultReceiver resultReceiver;
    Intent intent;
    
    public APIService() {
        super("APIService");
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        resultReceiver = intent.getParcelableExtra(APIServiceTask.RECEIVER);
        HashMap<String, String> params = (HashMap<String, String>) intent.getSerializableExtra(APIServiceTask.PARAMS);
        Set<Entry<String, String>> entries = params.entrySet();
        String result = "";
        for (Entry<String, String> entry : entries) {
            result += entry.getKey() + " : " + entry.getValue() + "\n";
        }
        Bundle bundle = new Bundle();
        bundle.putString(APIServiceTask.RESULT, result);
        resultReceiver.send(100, bundle);       
    }
}
package com.example.servicedemo;

import java.util.HashMap;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.ResultReceiver;

public class APIServiceTask {
    public final static String RESULT = "result";
    public final static String RECEIVER = "receiver";
    public final static String PARAMS = "params";

    private Intent mIntent;
    private APIServiceTaskReceiver mResultReceiver;
    private APICallbackInterface mCallbackInterface;
    
    interface APICallbackInterface {
        void onAPIResult(String result);
    }
    
    public void request(Context context, String APIname, APICallbackInterface callbackInterface, HashMap<String, String> params){
        mResultReceiver = new APIServiceTaskReceiver(null);
        mCallbackInterface = callbackInterface;
        mIntent = new Intent(context, APIService.class);
        mIntent.putExtra(RECEIVER, mResultReceiver);
        mIntent.putExtra(PARAMS, params);
        context.startService(mIntent);
    }
    
    class APIServiceTaskReceiver extends ResultReceiver {
        public APIServiceTaskReceiver(Handler handler) {
            super(handler);
        }

        @Override
        protected void onReceiveResult(int resultCode, Bundle resultData) {
            String result = resultData.getString(RESULT);
            mCallbackInterface.onAPIResult(result);
        }
    }
}
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.servicedemo"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.servicedemo.ResultReceiverDemoActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <service android:name=".APIService" />
    </application>

</manifest>
← libGDX - パーティクル libGDX - scene2dui →