非活动类通知无效

时间:2017-01-14 15:38:24

标签: java android

我正在尝试在非活动类的通知管理器中显示通知,但我无法实现通知

public void showNotification(Context context) {
NotificationCompat.Builder mBuilder =
        new NotificationCompat.Builder(context)
                //.setSmallIcon(R.drawable.notif1)
                .setContentTitle("Car crash occure!")
                .setContentText("Tap to view location.");

PendingIntent contentIntent = PendingIntent.getActivity(context, 0,
        new Intent(context, MapsActivity.class), 0);
mBuilder.setContentIntent(contentIntent);
mBuilder.setDefaults(Notification.DEFAULT_SOUND);
mBuilder.setAutoCancel(true);
NotificationManager mNotificationManager =
        (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(0, mBuilder.build());

}

1 个答案:

答案 0 :(得分:-2)

使用Intent Service代替Activity

public static class NotificationActionService extends IntentService {
    public NotificationActionService() {
        super(NotificationActionService.class.getSimpleName());
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        String action = intent.getAction();
        if (ACTION_1.equals(action)) {

            Log.d("ACTION_NOTIFICATION", "Notification Clicked");
        }
        // TODO: handle action 1.
        // If you want to cancel the notification: NotificationManagerCompat.from(this).cancel(NOTIFICATION_ID);
    }
}