2016-07-07 28 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をインポートすることを忘れないでください。