次のエントリ: AlarmManagerで単純にブロードキャストを投げるだけ [Android]
レシーバおぼえがき(BroadcastReceiver)
2011-02-06-1 / カテゴリ: [Java][Android] / [permlink]
そのActivityがtopにいる場合にブロードキャストを受けるには。
(rergisterReceive()を複数叩いて複数のレシーバを受ける場合は必要)
おまけ
↑のInternalは別クラス(ブロードキャスト元)
投げる部分はこんな感じ。(適当)
public class FooBar extends Activity {
:
:
// スレッドの通知を受けるためのレシーバ
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Log.d(TAG, " onReceive(" + context + ", " + intent + ")");
if (intent.getAction().equals(Internal.INTENT_ACTION)) {
Log.d(TAG, "intent val: " + intent.getIntExtra(Internal.INTENT_VAL, 0));
}
}
};
@Override
public void onResume() {
super.onResume();
Log.d(TAG, "onResume()");
// レシーバの登録
registerReceiver(mReceiver, new IntentFilter(Internal.INTENT_ACTION));
}
@Override
public void onPause() {
super.onPause();
Log.d(TAG, "onPause()");
// レシーバの解除
unregisterReceiver(mReceiver);
}
:
registerReceiver()第2引数でフィルタを設定しているので、onReceive()内でgetAction()でAction名をチェックしてるのはこの例では冗長。(rergisterReceive()を複数叩いて複数のレシーバを受ける場合は必要)
おまけ
↑のInternalは別クラス(ブロードキャスト元)
投げる部分はこんな感じ。(適当)
public class Internal extends Activity {
public final static String INTENT_ACTION = "internal_thread_broadcast";
public final static String INTENT_VAL = "internal_thread_val";
private int mCount = 0;
// 中略
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
// TODO 自動生成されたメソッド・スタブ
try {
for (;;) {
Thread.sleep(1000);
mCount ++;
Log.d(TAG, "running count("+ mCount + ")");
Intent intent = new Intent(INTENT_ACTION);
intent.putExtra(INTENT_VAL, mCount);
sendBroadcast(intent);
}
} catch (InterruptedException e) {
// TODO 自動生成された catch ブロック
e.printStackTrace();
}
}
});
thread.start();
// 後略
Referrer (Inside):
[2011-02-06-2]
[
コメント ]
次のエントリ: AlarmManagerで単純にブロードキャストを投げるだけ [Android]
2013 : 01 02 03 04 05 06 07 08 09 10 11 12
2012 : 01 02 03 04 05 06 07 08 09 10 11 12
2011 : 01 02 03 04 05 06 07 08 09 10 11 12
2010 : 01 02 03 04 05 06 07 08 09 10 11 12
2009 : 01 02 03 04 05 06 07 08 09 10 11 12
2008 : 01 02 03 04 05 06 07 08 09 10 11 12
2007 : 01 02 03 04 05 06 07 08 09 10 11 12
2006 : 01 02 03 04 05 06 07 08 09 10 11 12
2005 : 01 02 03 04 05 06 07 08 09 10 11 12
2004 : 01 02 03 04 05 06 07 08 09 10 11 12
最終更新時間: 2013-05-02 16:12
