2016-07-07 57 views
1

嗯,我試圖使用通知,但此代碼不起作用。我已經在4.4和5.0上測試過了。我不明白,什麼是錯的。通知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); 
} 

我將不勝感激。

回答

0

這可能是因爲Google在每個Android版本中都會更改其通知API。所以你使用的API不兼容多種Android版本。但Google發佈appcompat-v7 \ appcompat-v4來解決這個問題。

試試下面的代碼:

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); 
} 

記得導入android.support.v7.app.NotificationCompat。