1、靜態註冊廣播
編輯廣播類
public class MyReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Log.e("TAG","觸發");
}
}
PendingIntent pendingIntent = PendingIntent.getBroadcast(this,0,new Intent(this,MyReceiver.class),PendingIntent.FLAG_UPDATE_CURRENT);
NotificationManager manager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
builder = new NotificationCompat.Builder(this,"通知渠道id");
builder.setContentIntent(pendingIntent);
記得註冊
<receiver android:name=".MyReceiver"/>
如果使用混合開發的話廣播類裏面可能會要用到一個上下文對象,這樣可以使用內部類的方式,將廣播類寫在需要使用的類中,需要加上static修飾,註冊的方式也變爲
<receiver android:name=".MainActivity$MyReceiver"/>
2、動態註冊廣播
可能是對於reactnative來說最好用的方式,這樣的好處是可以在newBroadCastReceiver中直接使用getReactApplicationContext()
public BroadcastReceiver newBroadCastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Log.e("TAG","觸發");
}
};
private static String BROADCASTNAME = "com.vision.broadcast";
IntentFilter intentFilter = new IntentFilter(BROADCASTNAME);
registerReceiver(newBroadCastReceiver,intentFilter);
broadcastIntent = new Intent();
broadcastIntent.setAction(BROADCASTNAME);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this,0,broadcastIntent,PendingIntent.FLAG_UPDATE_CURRENT);
NotificationManager manager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
builder = new NotificationCompat.Builder(this,"渠道id");
builder.setContentTitle("title");
builder.setContentText("context");
builder.setWhen(System.currentTimeMillis());
builder.setContentIntent(pendingIntent);
builder.setSmallIcon(R.drawable.ic_chat);
builder.setAutoCancel(true);
manager.notify(2,builder.build());