Search code examples
androidnotificationsstatusbar

How can I put notification icon in notification area while app is running android?


I want to place my app icon in notification area while my app is running. I searched a lot and made this possible, to show it in the notification area.

public class MainActivity extends ActionBarActivity {

    NotificationManager mNotificationManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Context context = getApplicationContext();
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
                .setTicker("This is a new notification")
                .setContentTitle("Notification")
                .setContentText("App runing..")
                .setSmallIcon(R.mipmap.ic_launcher);
        Intent intent = new Intent(context, MainActivity.class);
        PendingIntent pIntent = PendingIntent.getActivity(context, 0, intent, 0);
        builder.setContentIntent(pIntent);
        mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        Notification notif = builder.build();
        mNotificationManager.notify(1, notif);

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
       mNotificationManager.cancel(1);
    }
}

But what I want is I don't want to open any activity when clicking the notification.

eg: the battery info icon comming when battery is full, it willnot open any application or activity, also tapping it willnot remove it from notification area.

PendingIntent pIntent = PendingIntent.getActivity(context, 0, intent, 0);

By changing this one line code to this

PendingIntent pIntent = PendingIntent.getActivity(context, 0, null, 0);

It will work like what I want, But only on emulator, when I run this code in real device it will crash.

how to achieve this task in my app? How can I put notification icon without Intent and PendingIntent ?


Solution

  • You could use this code, like mentioned in the answers here and here:

    PendingIntent contentIntent = PendingIntent.getActivity(
        getApplicationContext(),
        0,
        new Intent(), // add this
        PendingIntent.FLAG_UPDATE_CURRENT);