简体   繁体   中英

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 ! 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

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

  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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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