4

これは機能します: NotificationManager.notify() .setContentIntent(pendingIntent) で使用する通知を提供する NotificationCompat.Builder を使用した IntentService が必要です。通知が送信されると、通知は通知に表示され、永続的です (ユーザーがクリックするまで存続し、クリックすると、.setContentIntent で指定されたアクティビティが開始されます)。良い!うまくいかないこと: サービスを電話サービスのように長寿命にしたいので、startForeground() をお勧めします。ただし、それを含めると、関連する通知は実際にトレイに表示されますが、永続的ではなく、IntentService が終了すると消えます (上記とは異なります)。(関連する通知も .setContentIntent を使用し、別のアクティビティを開始します。) 何かご意見は?特定の (まれな) "イベント" を検出するまで、サービスが終了しないことが重要です。また、ユーザーがクリックして応答するまで通知が有効であることも重要です。
これが煮詰めたコードです (後者の場合): ありがとう!

    public class SService extends IntentService {
public SService() {
    super("SService");                          
}
@Override
protected void onHandleIntent(Intent sIntent) {

  //Notification construction:
    Notification notif;
    Context context = this;

    NotificationManager mNotificationManager = 
            (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

    Intent bIntent = new Intent(context, BarNotifActivity.class);       
    PendingIntent pbIntent = PendingIntent.getActivity(context, 0, bIntent,0);
    Notification barNotif;

    NotificationCompat.Builder bBuilder =
            new NotificationCompat.Builder(this)
                .setSmallIcon(R.drawable.ic_launcher)
                .setContentTitle(getString(R.string.bar_title))
                .setContentText(getString(R.string.bar_text))
                //.setAutoCancel(true)
                .setOngoing(true)
                .setContentIntent(pbIntent);
    barNotif = bBuilder.build();
    this.startForeground(1, barNotif);

    long[] vibration = {0, 300, 1000, 300, 1000, 300, 1000, 300, 1000};
    Intent mIntent = new Intent(context, NotifReceiverActivity.class);
    PendingIntent pIntent = PendingIntent.getActivity(context, 0, mIntent,0);

    NotificationCompat.Builder mBuilder =
        new NotificationCompat.Builder(context)
            .setSmallIcon(R.drawable.ic_launcher)
            .setContentTitle(getString(R.string.alert_text))
            .setContentText(getString(R.string.alert_text))
            .setTicker("**Notification Arrived!**")
            .setVibrate(vibration)
            //.setAutoCancel(true)
            .setOngoing(true)
            .setContentIntent(pIntent);
    notif = mBuilder.build();
    notif.flags |= Notification.FLAG_AUTO_CANCEL;
    notif.flags |= Notification.FLAG_INSISTENT;  

    try {
        Thread.sleep(7000);                         //Pause 7 sec.
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    mNotificationManager.notify(1, notif);
}

}

4

0 に答える 0