Search code examples
androidnotificationsstatusbar

Android Status Bar Notification: make it un-clearable and have it return to app (not start a new instance)


I am developing an Android app and I want a status bar notification that cannot be cleared by the user. Does anyone know how to do that? I've seen them with apps like Skimble where a non-clearable notification appears while using the application.

Also, I'd when the user clicks/presses the notification, I want it to return to the app instance that is already running. Right now it starts a new instance. Again like the Skimble app, I just want to return to the already running instance of the app.

Thanks.


Solution

  • I found a solution to this problem. I used FLAG_ONGOING_EVENT to make the notification persist. Here's the code:

      String ns = Context.NOTIFICATION_SERVICE;
      NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);
    
        int icon = R.drawable.mypic;
        long when = System.currentTimeMillis();
        Notification notification = new Notification(icon, tickerText, when);
        notification.flags = Notification.FLAG_ONGOING_EVENT;
    
        Context context = getApplicationContext();
        CharSequence contentTitle = "Title Text";
        CharSequence contentText = "Content text.";
    
        Intent intent = new Intent(this, MyClass.class); 
        intent.setAction("android.intent.action.MAIN"); 
        intent.addCategory("android.intent.category.LAUNCHER"); 
        PendingIntent contentIntent = PendingIntent.getActivity(this, 0, intent, 0); 
    
        notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
    
        final int HELLO_ID = 1;
        mNotificationManager.notify(HELLO_ID, notification);