Вопрос

So this code is run from inside my service after it has started to start it in the foreground. This also creates the notification that will stay up there. I have a number of problems/questions:

1) Clicking the notification only opens the app info and not my PendingIntent.

2) My content title and text aren't being set. I get "MyApp is running. Touch for more information or to stop the activity." shown in the notification rather than "TEST1 TEST2".

3) note.flags|=Notification.FLAG_NO_CLEAR seems redundant. I commented it out before and the notification would still stay up there after I try to clear all notifications.

4) Using notificationManager.notify actually seems to remove my previously set notification. No new notification is actually set. So my app has no notification after this line executes.

private void setupStartForeground() {   

    int id = 11;

    Intent intent = new Intent(this, MyActivity.class);     
    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|Intent.FLAG_ACTIVITY_SINGLE_TOP|Intent.FLAG_ACTIVITY_NEW_TASK);      

    PendingIntent pi = PendingIntent.getActivity(this, 0, intent, 0);

    Notification note = new Notification.Builder(this)
            .setContentTitle("TEST1")
            .setContentText("TEST2")
            .setContentIntent(pi)
            .build();
    note.flags|=Notification.FLAG_NO_CLEAR;

    startForeground(id, note);

    //NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    //notificationManager.notify(id, note);
}
Это было полезно?

Решение 2

Ok...so I used the code from here, Lines 49-72. https://github.com/commonsguy/cw-android/blob/master/Notifications/FakePlayer/src/com/commonsware/android/fakeplayerfg/PlayerService.java

It's deprecated (as in doesn't use Notification.Builder), but it works! I get my proper title up and clicking the notification will launch my activity.

I'd still prefer a non-deprecated way of doing this though, if anyone knows one.

Другие советы

I had the same problem and got it resolved by setting the right resource to setSmallIcon. Setting the icon is mandatory and if this is not done, the default notification with title='My App' and text='MyApp is running. Touch for more information or to stop the activity.' is displayed. Here is the code I use:

       Resources res   = this.getResources();
    String pkgName  = this.getPackageName();
    int resId;
    resId = res.getIdentifier("myIcon", "drawable", pkgName);
    int resId = 
    Notification note = new Notification.Builder(this)
        .setSmallIcon(resId)
        .setContentTitle("TEST1")
        .setContentText("TEST2")
        .setContentIntent(pi)
        .build();
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top