如何创建在Android中点击时不会消失的通知?

Tes*_*234 11 notifications android

int icon = R.drawable.icon4;        
CharSequence tickerText = "Hello"; // ticker-text
long when = System.currentTimeMillis();         
Context context = getApplicationContext();     
CharSequence contentTitle = "Hello";  
CharSequence contentText = "Hello";      
Intent notificationIntent = new Intent(this, Example.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
Notification notification = new Notification(icon, tickerText, when);
notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
Run Code Online (Sandbox Code Playgroud)

这对我不起作用.

我怎么能创建一个可点击的通知并转到我的应用程序,但点击后不会消失?

Pet*_*ton 25

你应该阅读所有的东西,不仅仅是一个部分,伙伴.请仔细阅读一步一步.

// this
String ns = Context.NOTIFICATION_SERVICE;
NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);

int icon = R.drawable.icon4;        
CharSequence tickerText = "Hello"; // ticker-text
long when = System.currentTimeMillis();         
Context context = getApplicationContext();     
CharSequence contentTitle = "Hello";  
CharSequence contentText = "Hello";      
Intent notificationIntent = new Intent(this, Example.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
Notification notification = new Notification(icon, tickerText, when);
notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);

// and this
private static final int HELLO_ID = 1;
mNotificationManager.notify(HELLO_ID, notification);
Run Code Online (Sandbox Code Playgroud)

  • `setLatestEventInfo()`在API级别11中已弃用.必须使用[Notification.Builder](http://developer.android.com/reference/android/app/Notification.Builder.html). (6认同)

Kis*_*han 12

int icon = R.drawable.ic_launcher;
long when = System.currentTimeMillis();
NotificationManager nm=(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
Intent intent=new Intent(context,MainActivity.class);
PendingIntent  pending=PendingIntent.getActivity(context, 0, intent, 0);
Notification notification;
    if (Build.VERSION.SDK_INT < 11) {
        notification = new Notification(icon, "Title", when);
        notification.setLatestEventInfo(
                context,
                "Title",
                "Text",
                pending);
    } else {
        notification = new Notification.Builder(context)
                .setContentTitle("Title")
                .setContentText(
                        "Text").setSmallIcon(R.drawable.ic_launcher)
                .setContentIntent(pending).setWhen(when).setAutoCancel(true)
                .build();
    }
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notification.defaults |= Notification.DEFAULT_SOUND;
nm.notify(0, notification);
Run Code Online (Sandbox Code Playgroud)

或者您可以从这里下载直接教程:http://www.demoadda.com/demo/android/how-to-create-local-notification-notification-manager-demo-with-example-android-source-code_26