首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何显示来自广播接收器的通知?

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

Stack Overflow用户
提问于 2019-05-29 07:15:34
回答 2查看 1.1K关注 0票数 0

我正在从服务注册广播接收器。我需要显示通知给用户,如果设备的位置是关闭的代码工作正常,但接收器不创建通知。我可以看到有关更改位置状态的logcat消息,但未创建通知。请检查该问题!有没有办法更新服务的当前通知?

这是服务:

代码语言:javascript
复制
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);
      }*/


   }

这是广播接收器:

代码语言:javascript
复制
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);

            }
        }
    }

我可以看到有关更改位置状态的logcat消息,但未创建通知

EN

回答 2

Stack Overflow用户

发布于 2019-05-29 07:46:12

将通知代码更改为此解决了问题

代码语言:javascript
复制
          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());

                   }
票数 0
EN

Stack Overflow用户

发布于 2019-05-29 13:25:10

因此,基本上您需要创建一个前台通知,并在位置更改时更新其内容。

您可以使用以下代码创建前台通知:-

代码语言:javascript
复制
  //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();

}

你需要调用startForegroundService();

代码语言:javascript
复制
  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));
    }

因此,它将传递更新后的位置、名称和位置,您可以从SharedPreference收集这些信息,也可以直接调用onLocationChanged。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56351173

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档