Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android show a notification not working

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: screenshot

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

like image 939
Marcus Avatar asked Sep 29 '22 15:09

Marcus


1 Answers

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.

like image 148
ianhanniballake Avatar answered Oct 03 '22 02:10

ianhanniballake