@blog.justoneplanet.info

日々勉強

Google Developer Day 2011のAndroid問題を解いてみる

src/com/google/android/apps/gddquiz/IQuizService.aidlを配置したら、後はサービスを扱う感じ。

package info.justoneplanet.android.gdd2011;

import com.google.android.apps.gddquiz.IQuizService;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;

public class MainActivity extends Activity {
    private IQuizService mService;
    
    /**
     * ServiceConnection
     * サービスへの接続
     */
    private ServiceConnection gddServiceConn = new ServiceConnection(){
        /**
         * onServiceConnected
         * サービスに接続時
         */
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            // mService経由でやりとりする
            mService = IQuizService.Stub.asInterface(service);
            Log.e("onServiceConnected", "onServiceConnected");
            try {
                Log.e("code", mService.getCode());
            }
            catch (RemoteException e) {
                e.printStackTrace();
            }
        }

        /**
         * onServiceDisconnected
         * サービスから切断時
         */
        @Override
        public void onServiceDisconnected(ComponentName name) {
            Log.e("onServiceDisconnected", "onServiceDisconnected");
            mService = null;
        }
    };
    
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        // IQuizServiceにbindする
        Intent intent = new Intent(IQuizService.class.getName());
        if(bindService(
                intent,
                gddServiceConn,
                BIND_AUTO_CREATE
        )){
            Log.e("bindService", "connected");
        }
        else{
            Log.e("bindService", "connect - error");
        }
    }
    
    @Override
    public void onDestroy()
    {
        super.onDestroy();
        unbindService(gddServiceConn);
    }
}

コメントはまだありません»

No comments yet.

RSS feed for comments on this post.TrackBack URL

Leave a comment