September 13, 2011

Google Developer Day 2011:DevQuiz解答晒し大会(4)

分野別問題(3) Android

AIDLファイルを使ってアプリケーションを作ればいいことはわかったが、bindServiceを呼び出してから実際にサービスに接続するまでに時間がかかることを知らずにNullPointerExceptionではまること多数。

アプリケーション

package com.example.devquizanswer;

import android.app.Activity;
import android.content.ServiceConnection;
import android.content.Context;
import android.content.ComponentName;
import android.content.Intent;
import android.os.IBinder;
import android.os.Bundle;
import android.os.RemoteException;
import android.widget.TextView;
import com.google.android.apps.gddquiz.IQuizService;

public class DevQuizAnswer extends Activity {
	
	public IQuizService quiz;
	public TextView tv;
	    
    private ServiceConnection serviceConnection = new ServiceConnection() {
    	public void onServiceConnected(ComponentName name, IBinder service) {
    		quiz = IQuizService.Stub.asInterface(service);
    		try {
    			String code = quiz.getCode();
    			tv.setText(code);
    		} catch (RemoteException e) {
    			// do nothing
    		}
    	}
    	
    	public void onServiceDisconnected(ComponentName name) {
    		quiz = null;
    	}
    };
    
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        tv = (TextView)findViewById(R.id.code);
        Intent intent = new Intent(IQuizService.class.getName());
        bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE);
    }
    
    @Override
    protected void onDestroy() {
    	super.onDestroy();
    	unbindService(serviceConnection);
    }
    
}

レイアウト

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
     android:orientation="vertical"
     android:layout_width="fill_parent"
     android:layout_height="fill_parent"
     >
<TextView android:text="TextView" android:id="@+id/code" android:layout_width="wrap_content" android:layout_height="wrap_content"></TextView>
</LinearLayout>