Service からの sendBroadcast

ええと、@IT の記事のサンプルですが、sendBroadcast からデータが送付できるかを確認。
基本的に Intent 渡してるはずなんで可能と見てちょっと手を入れてみました。

元は

以下なカンジになっております。まず sendBroadcast する側が以下。

        TimerTask timerTask = new TimerTask() {

            public void run() {
     	        sendBroadcast(new Intent(ACTION));
            }

        };
 	timer.schedule(timerTask, delay);

時間が来たら云々。あと、受け取り側の Activity で以下。

public class Main extends Activity {

    private class KitchenTimerReceiver extends BroadcastReceiver {

        @Override
	public void onReceive(Context context, Intent intent) {
	    Toast toast = Toast.makeText(getApplicationContext(), "Time over!", Toast.LENGTH_LONG);
	    toast.show();
	    MediaPlayer mp = MediaPlayer.create(Main.this, R.raw.alarm);
	    try {
	        mp.start();
            } catch (Exception e) {
	        // 例外は発生しない
            }
        }
    }
	
    private KitchenTimerService kitchenTimerService;
    private final KitchenTimerReceiver receiver = new KitchenTimerReceiver();

sendBroadcast に Intent を渡して、onReceive で Intent が渡されてくるので Service 側で以下かな。

            public void run() {
	        Intent i = new Intent(ACTION);
		i.putExtra("message", "Time over!");
		sendBroadcast(i);
            }

で、以下のように取り出してみる。

            Toast toast = Toast.makeText(getApplicationContext(), 
                                         intent.getStringExtra("message"), 
                                      	 Toast.LENGTH_LONG);

無事、取り出す事ができる事を確認しております。何が確認したかったかとゆーと、処理完了を bind している Activity 側に通知できてかつ、データが渡せます、という事が確認したかった訳なんですが、putExtra な限界をあまり考慮できてないかもorz

よく考えたら Service と Activity の i/f はあるので、処理終了が通知できれば良いのでした。わははは。