在這邊寫一些範例
@Override
public void onClick(View arg0) {
Intent intent = new Intent().setAction(
"myAction").putExtra("Tag",
"Data");
sendBroadcast(intent);
}
在button click的時候 ,sendBroadcast 送廣播給手機, 並且設定 action為我自己客製化的action,
這時所有監聽這個action的都會被呼叫。
public void onReceive(Context context, Intent intent) {
Log.d("Ted","OnReceive");
this.context = context;
if(intent.getAction().equals("myAction")){
Log.v("Ted", intent.getStringExtra("Tag"));
showNotification();
}
}
我在接收到action的時候發送Notification,使手機出現Notification。
附註:
使用BroadcastReceiver 必須在manifest裡增加receiver,範例如下
<receiver android:name="Receiver1" >
<intent-filter>
<action android:name="myAction" >
</action>
</intent-filter>
</receiver>
myAction為客製化的action,在button click時我有設定action,所以在button click之後會去呼叫Receiver1,並且在 OnReceive可以做相關的動作。
附上 sample Code
沒有留言:
張貼留言