2016-07-07 10 views
1

Nun, ich versuche, Benachrichtigungen zu verwenden, aber dieser Code funktioniert nicht. Ich habe es auf 4.4 und 5.0 getestet. Ich kann nicht verstehen, was falsch ist.Benachrichtigungen Android

public void onClick(View view) { 
    Context context = getApplicationContext(); 

    Intent notificationIntent = new Intent(context, MainActivity.class); 
    PendingIntent contentIntent = PendingIntent.getActivity(context, 0,notificationIntent, PendingIntent.FLAG_CANCEL_CURRENT); 

    Resources res = context.getResources(); 
    Notification.Builder builder = new Notification.Builder(context); 

    builder.setContentIntent(contentIntent) 
      .setWhen(System.currentTimeMillis()) 
      .setAutoCancel(true) 
      .setContentTitle("Title") 
      .setContentText("Text"); 

    Notification notification = builder.build(); 
    NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);   
    notificationManager.notify(NOTIFY_ID, notification); 
} 

Ich bin dankbar für die Antwort.

Antwort

0

Vermutlich ändert Google seine Benachrichtigungs-API in jeder Android-Edition ziemlich stark. Also die API, die du benutzt hast, ist nicht kompatibel für die Multi-Android-Version. Aber Google veröffentlicht appcompat-v7 \ appcompat-v4, um dieses Problem zu lösen.

Versuchen Sie, den folgenden Code:

public void send(View v) { 
    NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); 
    Context context = getApplicationContext(); 
    Intent notificationIntent = new Intent(context, TestNotificationActivity.class); 
    PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, PendingIntent.FLAG_CANCEL_CURRENT); 
    NotificationCompat.Builder builder = new NotificationCompat.Builder(this); 
    Notification notification = builder 
      .setContentIntent(contentIntent) 
      .setContentTitle("this is title") 
      .setContentText("this is content") 
      .setWhen(System.currentTimeMillis()) 
      .setSmallIcon(R.mipmap.ic_launcher) 
      .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher)) 
      .build(); 
    manager.notify(NOTIFY_ID, notification); 
} 

Denken Sie daran, android.support.v7.app.NotificationCompat zu importieren.

Verwandte Themen