简体   繁体   English

如何显示来自广播接收器的通知?

[英]How to show notification from broadcast receiver?

I am registering a broadcast receiver from a service. 我正在从服务注册广播接收器。 I need to show notification to user if location of device is off the code works fine but receiver does not create notification. 我需要向用户显示通知,如果设备的位置不在,代码工作正常,但接收器不会创建通知。 I can see logcat messages on changing location status but notification is not created Please check the issue ! 我可以看到有关更改位置状态的logcat消息,但未创建通知请检查问题! And is there any way to update the current notification of the service? 有没有办法更新当前的服务通知?

This is Service: 这是服务:

public class LockService extends Service {
BroadcastReceiver mReceiver;
Handler handler;
LocationManager locationManager;

@Override
public IBinder onBind(Intent intent) {
    return null;
}

private static final int NOTIF_ID = 1;

@Override
public void onCreate() {

    final IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
    filter.addAction(Intent.ACTION_SCREEN_OFF);
    filter.addAction(Intent.ACTION_USER_PRESENT);
    filter.addAction(LocationManager.PROVIDERS_CHANGED_ACTION);
    mReceiver = new com.example.fizatanveerkhan.citycops.ScreenReceiver();
    registerReceiver(mReceiver, filter);
    super.onCreate();

}
private void startForeground() {
    startForeground(NOTIF_ID, getMyActivityNotification(""));
}


@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    this.startForeground();
    return super.onStartCommand(intent, flags, startId);
}

@Override
public void onDestroy() {

    if (mReceiver != null) {
        unregisterReceiver(mReceiver);
        mReceiver = null;

        Log.i("onDestroy Reciever", "Called");

    }
    super.onDestroy();

}

public class LocalBinder extends Binder {
    LockService getService() {
        return LockService.this;
    }
}

private Notification getMyActivityNotification(String text) {

    CharSequence title = "new";



    Notification notification = null;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        String NOTIFICATION_CHANNEL_ID = " com.example.fizatanveerkhan.citycops";
        String channelName = "My Background Service";
        NotificationChannel chan = new NotificationChannel(NOTIFICATION_CHANNEL_ID, channelName, NotificationManager.IMPORTANCE_NONE);
        chan.setLightColor(Color.BLUE);
        chan.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
        NotificationManager manager = (NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
        assert manager != null;
        manager.createNotificationChannel(chan);

        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID);
        notification = notificationBuilder.setOngoing(true)
                .setSmallIcon(R.drawable.abc)
                .setContentTitle("Service running")
                .setContentText("new")
                .setPriority(NotificationManager.IMPORTANCE_MIN)
                .setCategory(Notification.CATEGORY_SERVICE)
                .build();

    }
    return notification;
}
     /*  public void updateNotification() {
    String text = "Some text that will update the notification";

    Notification notification = getMyActivityNotification(text);

    NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    mNotificationManager.notify(NOTIF_ID, notification);
      }*/


   }

And this is broadcast receiver: 这是广播接收器:

public class ScreenReceiver extends BroadcastReceiver {

public static boolean wasScreenOn = true;


private static final int POWER_OFF_TIMEOUT = 500;
private Handler handler = new Handler();
private Runnable powerOffCounterReset = new PowerOfTimeoutReset();
private int countPowerOff = 0;
private boolean screenOff;
//private LockService updateService = new LockService();

private final static String TAG = "LocationProviderChanged";

boolean isGpsEnabled;
boolean isNetworkEnabled;
@Override
public void onReceive(final Context context, final Intent intent) {
    if (intent.getAction().matches("android.location.PROVIDERS_CHANGED")) {
        Log.i(TAG, "Location Providers changed");

        LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        isGpsEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

        //Start your Activity if location was enabled:
        if (isGpsEnabled || isNetworkEnabled) {

            Log.i(TAG, "Location Providers on");
       }

       else {

              Log.i(TAG, "Location Providers off");
            Notification notification = null;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                String NOTIFICATION_CHANNEL_ID = " com.example.fizatanveerkhan.citycops";
                String channelName = "My Background Service";
                NotificationChannel chan = new NotificationChannel(NOTIFICATION_CHANNEL_ID, channelName, NotificationManager.IMPORTANCE_NONE);
                chan.setLightColor(Color.BLUE);
                chan.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
                NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
                assert manager != null;
                manager.createNotificationChannel(chan);

                NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context, NOTIFICATION_CHANNEL_ID);
                notification = notificationBuilder.setOngoing(true)
                        .setSmallIcon(R.drawable.abc)
                        .setContentTitle("Service running")
                        .setContentText("new")
                        .setPriority(NotificationManager.IMPORTANCE_MIN)
                        .setCategory(Notification.CATEGORY_SERVICE)
                        .build();
                NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
                mNotificationManager.notify(1, notification);

            }
        }
    }

I can see logcat messages on changing location status but notification is not created 我可以看到有关更改位置状态的logcat消息,但未创建通知

Changing notification code to this solved the problem 将通知代码更改为此可以解决问题

          if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                String NOTIFICATION_CHANNEL_ID = " 
            com.example.fizatanveerkhan.citycops";
                CharSequence name =  "My Background Service";
                String description =  "My Background Service";
                int importance = NotificationManager.IMPORTANCE_DEFAULT;
                NotificationChannel channel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, name, importance);
                channel.setDescription(description);
                // Register the channel with the system; you can't change the importance
                // or other notification behaviors after this
                NotificationManager notificationManager = context.getSystemService(NotificationManager.class);
                notificationManager.createNotificationChannel(channel);

                NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context, NOTIFICATION_CHANNEL_ID);
                notification = notificationBuilder.setOngoing(true)
                        .setSmallIcon(R.drawable.abc)
                        .setContentTitle("Service running")
                        .setContentText("new")
                        .setPriority(NotificationManager.IMPORTANCE_MIN)
                        .setCategory(Notification.CATEGORY_SERVICE)
                        .build();
                NotificationManagerCompat notificationManagerq = 
           NotificationManagerCompat.from(context);

        // notificationId is a unique int for each notification that you must define
                notificationManagerq.notify(1, notificationBuilder.build());

                   }

So basically you need to create a foreground notification and update its contents on location change. 因此,基本上您需要创建前景通知并在位置更改时更新其内容。

You can use the code below to create a foreground notification:- 您可以使用以下代码创建前景通知: -

  //for foreground service notification
public Notification showForegroundNotification(String notificationTitle, String notificationBody, Intent intent, ServiceName serviceName) {
    String id = mContext.getString(R.string.upload_notification_channel_id);
    PendingIntent lowIntent = PendingIntent.getActivity(mContext, 100, intent, PendingIntent.FLAG_ONE_SHOT);
    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(mContext, id);
    NotificationManager mNotifyManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);


    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        CharSequence name = mContext.getString(R.string.upload_notification_channel_name);
        String description = mContext.getString(R.string.upload_notification_channel_description); //user visible
        int importance = NotificationManager.IMPORTANCE_LOW;

        AudioAttributes att = new AudioAttributes.Builder()
                .setUsage(AudioAttributes.USAGE_NOTIFICATION)
                .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
                .build();

        NotificationChannel mChannel = new NotificationChannel(id, name, importance);
        mChannel.setDescription(description);
        mChannel.enableLights(false);
        mChannel.enableVibration(false);
        mChannel.setVibrationPattern(new long[]{0L});
        mChannel.setSound(null, att);


        if (mNotifyManager != null) {
            mNotifyManager.createNotificationChannel(mChannel);
        }

        notificationBuilder
                .setSmallIcon(R.mipmap.ic_launcher)
                .setCategory(NotificationCompat.CATEGORY_SERVICE)
                .setVibrate(new long[]{0L})
                .setSound(null)
                .setColor(ContextCompat.getColor(mContext, R.color.colorPrimary))
                .setContentTitle(notificationTitle)
                .setAutoCancel(true)
                .setContentIntent(lowIntent);

    } else {
        notificationBuilder.setContentTitle(notificationTitle)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setCategory(NotificationCompat.CATEGORY_SERVICE)
                .setVibrate(new long[]{0L})
                .setSound(null)
                .setColor(ContextCompat.getColor(mContext, R.color.colorPrimary))
                .setAutoCancel(true)
                .setContentIntent(lowIntent);
    }

    if (notificationBody != null) {
        notificationBuilder.setStyle(new NotificationCompat.BigTextStyle().bigText(notificationBody));
    }

    notificationBuilder.setContentText(notificationBody);

    return notificationBuilder.build();

}

and you need to call startForegroundService(); 你需要调用startForegroundService();

  private void startForegroundService(){
        String dataTitle = SharedPrefer.getLastUpdatedLocationName();
        String dataContent = SharedPrefer.getLastUpdatedLocation();

        Intent intent = new Intent(WITHU.getAppContext(), MapLocateActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK);
        startForeground(121, showNotification.showForegroundNotification(dataTitle, dataContent, intent, ServiceName.SMART_LOCATION, -1, false));
    }

So it will pass the updated location name and location which you can collect from SharedPreference or also can be called directly onLocationChanged. 因此,它将传递您可以从SharedPreference收集的更新的位置名称和位置,或者也可以直接调用onLocationChanged。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM