How to use NotificationCompat.Builder and startForeground?

廉价感情. 提交于 2020-01-12 14:07:51

问题


Short question:

I'm trying to use the NotificationCompat.Builder class in order to create a notification that will be used for the service, but for some reason, i either don't see the notification, or can't cancel it when the service should be destroyed (or stopping from being in the foreground) .

my code:

@Override
public int onStartCommand(final Intent intent, final int flags, final int startId) {
    final String action = intent == null ? null : intent.getAction();
    Log.d("APP", "service action:" + action);
    if (ACTION_ENABLE_STICKING.equals(action)) {
        final NotificationCompat.Builder builder = new Builder(this);
        builder.setSmallIcon(R.drawable.ic_launcher);
        builder.setContentTitle("content title");
        builder.setTicker("ticker");
        builder.setContentText("content text");
        final Intent notificationIntent = new Intent(this, FakeActivity.class);
        final PendingIntent pi = PendingIntent.getActivity(this, 0, notificationIntent, 0);
        builder.setContentIntent(pi);
        final Notification notification = builder.build();
        // notification.flags |= Notification.FLAG_FOREGROUND_SERVICE;
        // notification.flags |= Notification.FLAG_NO_CLEAR;
        // notification.flags |= Notification.FLAG_ONGOING_EVENT;

        startForeground(NOTIFICATION_ID, notification);
        // mNotificationManager.notify(NOTIFICATION_ID, notification);

    } else if (ACTION_DISABLE_STICKING.equals(action)) {
        stopForeground(true);
        stopSelf();
        // mNotificationManager.cancel(NOTIFICATION_ID);
    }
    return super.onStartCommand(intent, flags, startId);
}

The commented commands are my trials to make it work. none worked for some reason.

I even added a fake activity since it wanted a contentIntent , but it still doesn't work.

Can anyone please help?


回答1:


I had the exact same problem a while ago, and I found out that for some reason, the notification ID 0 doesn't work well with startForeground(), is it the value of NOTIFICATION_ID in your code?


EDIT: the documentation has now been updated to state that 0 is an invalid ID



来源:https://stackoverflow.com/questions/16262193/how-to-use-notificationcompat-builder-and-startforeground

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!