点击通知栏触发广播的多种方式

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());

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章