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



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

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");
    }
  }
}

好吧,我试图实现这一点,但它不起作用,因为我无法从邻近性IntentReceiver类中获得任何上下文

 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);也不起作用,因为我想它已被弃用。如何显示来自此类的通知?谢谢

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

最新更新