Android Notificationからレシーバーを呼びだす
スマホの上のバーに出るNotificationから、レシーバーを起動させるサンプルスクリプトです。
//呼び出し元のActivity
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test);
Button btn1 = (Button) findViewById(R.id.btn1);
btn1.setOnClickListener(this);
Intent intent = new Intent("STOP_ASYNC_TASK_VIDEO_UPLOAD");
PendingIntent contentIntent = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder b = new NotificationCompat.Builder(this);
b.setAutoCancel(true)
.setDefaults(Notification.DEFAULT_ALL)
.setWhen(System.currentTimeMillis())
.setSmallIcon(R.drawable.ic_launcher)
.setTicker("テスト")
.setContentTitle("テストタイトル")
.setContentText("テストだってばよ!!")
.setDefaults(Notification.DEFAULT_LIGHTS| Notification.DEFAULT_SOUND)
.setContentIntent(contentIntent)
.setContentInfo("Info");
NotificationManager notificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(1, b.build());
}
//AndroidManifest.xml
<receiver
android:name=".receivers.StopVideoUploadReceiver"
android:exported="false" >
<intent-filter>
<action android:name="STOP_ASYNC_TASK_VIDEO_UPLOAD" >
</action>
</intent-filter>
</receiver>
//レシーバー本体
public class StopVideoUploadReceiver extends BroadcastReceiver {
private Handler handler;
private final static String TAG = "StopVideoUploadReceiver";
@Override
public void onReceive(Context context, Intent intent) {
Log.d(TAG, "レシーバー起動");
if(handler !=null){
Message msg = new Message();
handler.sendMessage(msg);
}
}
}
ちょっとつまらないことで実ははまりまして、呼び出し元のPendingIntentを
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
とやっていて、どうしてレシーバーが呼び出されないの??ってずっとなてtました。
getActivityじゃなくって、getBroadcastしないと、Broadcastされないんですね!!
ボタンを押されたらレシーバー発動するのは、次のように作りますが、この時ももちろんsendBroadcastなわけです。
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn1:
Intent intent = new Intent("STOP_ASYNC_TASK_VIDEO_UPLOAD");
sendBroadcast(intent);
break;
}
}
