Android show a notification not working

梦想的初衷 提交于 2019-11-26 14:48:07

问题


Currently I have a service that plays music. I want to show a notification when the service start to play music. This is what I do:

public void setUpNotification() {
    /*
     * Set up the notification for the started service
     */

    Notification.Builder notifyBuilder = new Notification.Builder(this);
    notifyBuilder.setTicker("ticker");
    notifyBuilder.setOngoing(true);
    notifyBuilder.setContentTitle("title");
    notifyBuilder.setContentInfo("content info");

    // set up an Intent if the user clicks the notification
    int NOTIFICATION_ID = 1;
    Intent notifyIntent = new Intent(this, MainActivity.class);

    notifyIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
            | Intent.FLAG_ACTIVITY_SINGLE_TOP);

    PendingIntent pi = PendingIntent.getActivity(this, 0, notifyIntent,
            NOTIFICATION_ID);

    notifyBuilder.setContentIntent(pi);
    Notification notification = notifyBuilder.build();
    // start ongoing
    startForeground(NOTIFICATION_ID, notification);
}

The method gets called in the service playMusic() like this:

public void playMusic(String songPath) {
    if(mPlayer == null || !mPlayer.isPlaying()){
        try {
            mPlayer = MediaPlayer.create(getBaseContext(), Uri.parse(songPath));
            mPlayer.start();
            this.songPath = songPath;
        } catch (IllegalStateException e) {
            e.printStackTrace();
        }
    }else{
        mPlayer.stop();
        mPlayer.release();
        mPlayer = MediaPlayer
                .create(getBaseContext(), Uri.parse(songPath));
        mPlayer.start();
        this.songPath = songPath;
    }
    setUpNotification();
}

The problem is that the notifications pending intent, content title and content info does not get displayed. The notification looks like this:

And as you can see, the title and content info doesn't get displayed. Also, when I click the notification it does not fire off my pending intent.

What am I doing wrong here? Any help is greatly appreciated.

Marcus


回答1:


Per the notification guide list of required fields, you must set a small icon via the setSmallIcon() method. Generally, this icon looks like your application icon, although entirely as white over a transparent background per the anatomy of a notification.



来源:https://stackoverflow.com/questions/26345884/android-show-a-notification-not-working

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