如何从广播接收器发出通知

How to make a notification from broadcastreceiver

所以我一直在与接近警报作斗争,最后我的代码可以工作,但我不知道如何让它向我显示通知而不是日志消息:

public class ProximityIntentReceiver extends BroadcastReceiver {

private static final int NOTIFICATION_ID = 1000;

@Override
public void onReceive(Context context, Intent intent) {
    Log.d(getClass().getSimpleName(), "in receiver");

    String key = LocationManager.KEY_PROXIMITY_ENTERING;

    Boolean entering = intent.getBooleanExtra(key, false);

    if (entering) {
        Log.d(getClass().getSimpleName(), "entering receiverrrrrrrrrrrrrrrrrr");
    } else {
        Log.d(getClass().getSimpleName(), "exiting");
    }

  }
}

好吧,我尝试实现这个,但它不会工作,因为我无法从 proximityIntentReceiver 获得任何上下文 class

 Intent notificationIntent = new    Intent(getApplicationContext(),NotificationView.class);

    /** Adding content to the notificationIntent, which will be displayed on
     * viewing the notification
     */
    notificationIntent.putExtra("content", notificationContent );

    /** This is needed to make this intent different from its previous intents */
    notificationIntent.setData(Uri.parse("tel:/"+ (int)System.currentTimeMillis()));

    /** Creating different tasks for each notification. See the flag Intent.FLAG_ACTIVITY_NEW_TASK */
    PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), 0, notificationIntent, Intent.FLAG_ACTIVITY_NEW_TASK);

    /** Getting the System service NotificationManager */
    NotificationManager nManager = (NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);

    /** Configuring notification builder to create a notification */
    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(getApplicationContext())
            .setWhen(System.currentTimeMillis())
            .setContentText(notificationContent)
            .setContentTitle(notificationTitle)
            .setSmallIcon(R.drawable.ic_menu_notification)
            .setAutoCancel(true)
            .setTicker(tickerMessage)
            .setContentIntent(pendingIntent)
            .setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));

    /** Creating a notification from the notification builder */
    Notification notification = notificationBuilder.build();

    /** Sending the notification to system.
     * The first argument ensures that each notification is having a unique id
     * If two notifications share same notification id, then the last notification replaces the first notification
     * */
    nManager.notify((int)System.currentTimeMillis(), notification);

NotificationManager nm = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE); 不会工作,因为我猜它已被弃用。 我如何显示来自此 class 的通知?谢谢

在您的 BroadcastReceiver 中,使用传递给 onReceive 方法的 context 对象而不是 getApplicationContext。这应该为 运行 上的通知提供适当的上下文。