Запустить приложение из панели уведомлений

Я разрабатываю приложение для Android, используя телефонную связь. Я хочу запустить приложение из панели уведомлений. Хотя это может быть повторяющийся вопрос, но, похоже, у меня ничего не работает; несколько ссылок, которые я пробовал.

http://pilhuhn.blogspot.in/2010/12/pitfall-in-pendingintent-with-solution.html

Откройте приложение для Android из уведомления PUSH

повторно открыть фоновое приложение через элемент уведомления

автономное приложение, разработанное по этим ссылкам, работает, но когда я интегрируюсь с моим реальным проектом, нажатие на панель уведомлений ничего не делает, ниже мой код

NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

Notification notification = new Notification(R.drawable.ic_launcher,"Message received", System.currentTimeMillis());
        notification.flags |= Notification.FLAG_ONLY_ALERT_ONCE | Notification.FLAG_AUTO_CANCEL;

Intent intent = new Intent(context, MyClass.class);

intent.putExtra("message", message);
intent.putExtra("shortMsg", shortMsg);
intent.putExtra("source", source);
intent.putExtra("phone", phone);
intent.putExtra("datetime", datetime);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

context.startActivity(intent);

PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
        notification.setLatestEventInfo(context, "Message", "New message received", pendingIntent);

notificationManager.notify(0, notification);

Код MyClass.class,

Bundle extras = getIntent().getExtras();
if (extras != null) 
{
    System.out.println("in extras");            
    //Retrive data from the intent and store them in instance variables
    this.message = extras.getString("message");
    this.shortMsg = extras.getString("shortMsg");
    this.source = extras.getString("source");
    this.phone = extras.getString("phone");
    this.datetime = extras.getString("datetime");
}

Заранее спасибо,

Нанаши


person Nanashi    schedule 12.11.2012    source источник


Ответы (2)


Я использую NotificationCompat.Builder, потому что это намного проще воплощать в жизнь.

Intent intent = new Intent(context, Main.class);
PendingIntent pintent = PendingIntent.getActivity(context, 0, intent, 0);
mNotification = new NotificationCompat.Builder(context)
      .setContentTitle(context.getString(R.string.app_name))
      .setContentText(message)
      .setContentIntent(pintent)
      .setSmallIcon(R.drawable.ic_notification)
      .setWhen(System.currentTimeMillis())
      .setAutoCancel(cancellable ? true : false)
      .setOngoing(cancellable ? false : true)
      .build();
notificationManager.notify(0, mNotification);
person Binoy Babu    schedule 12.11.2012
comment
Я не думаю, что вы можете помещать какие-либо пары ключ-значение в ожидающие намерения. т.е. intent.putExtra (сообщение, сообщение); и что это за строчка NotificationCompat.Builder (context); есть ли класс с таким названием ??? - person Nanashi; 12.11.2012
comment
Да, насчет пар ключ-значение вы правы. Контроль с моей стороны. NotificationCompat.Builder(context) находится в библиотеке поддержки. - person Binoy Babu; 12.11.2012

Используйте setContentIntent и передайте ожидающее намерение в качестве аргумента.

Intent intent = new Intent(context, MyClass.class);
intent.putExtra("message", message);
intent.putExtra("shortMsg", shortMsg);
intent.putExtra("source", source);
intent.putExtra("phone", phone);
intent.putExtra("datetime", datetime);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent pintent = PendingIntent.getActivity(context, 0, intent, 0);

mNotification = new NotificationCompat.Builder(context)
      .setContentTitle(context.getString(R.string.app_name))
      .setContentText(message)
      .setContentIntent(pintent)
      .setSmallIcon(R.drawable.ic_notification)
      .setContentIntent(pintent)
      .build();
notificationManager.notify(0, mNotification);
person ashwini sawanth    schedule 10.05.2016