How to create notifications that don't go away when clicked in Android?

前端 未结 5 880
独厮守ぢ
独厮守ぢ 2021-02-05 21:18
int icon = R.drawable.icon4;        
CharSequence tickerText = \"Hello\"; // ticker-text
long when = System.currentTimeMillis();         
Context context = getApplicatio         


        
5条回答
  •  野趣味
    野趣味 (楼主)
    2021-02-05 21:49

    If you are using Android 5.0 > it became a lot easier, functionallity changed, but you can use the same code.

    //Some Vars
    public static final int NOTIFICATION_ID = 1; //this can be any int
    
    
    //Building the Notification
    NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
    builder.setSmallIcon(R.drawable.ic_stat_notification);
    builder.setContentTitle("BasicNotifications Sample");
    builder.setContentText("Time to learn about notifications!");
    
    NotificationManager notificationManager = (NotificationManager) getSystemService(
                NOTIFICATION_SERVICE);
    notificationManager.notify(NOTIFICATION_ID, builder.build());
    

    Make sure you are in an application context, if not you may need to pass the context and change your sourcecode as follows

    NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
    ...
    ..
    .
    
    NotificationManager notificationManager = (NotificationManager) context.getSystemService(
                context.NOTIFICATION_SERVICE);
    

    You can see the full-source-code at: https://github.com/googlesamples/android-BasicNotifications/blob/master/Application/src/main/java/com/example/android/basicnotifications/MainActivity.java#L73

提交回复
热议问题