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

Я разрабатываю приложение flashLight и столкнулся с проблемой в уведомлении: когда я нажимаю текст уведомления, я хочу выключить вспышку и закрыть все приложение. Как я могу изменить метод уведомления, чтобы сделать это? Я попытался сделать анторную активность и поместить в нее методы включения и закрытия приложения, но это не работает. пожалуйста, помогите и спасибо заранее.

это мой метод уведомления

public void getNotification()
{
    Intent intent = new Intent();
    PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent , PendingIntent.FLAG_CANCEL_CURRENT);

    NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
            .setContentIntent(pIntent)
            .setContentTitle(res.getString(R.string.notification_title))
            .setContentText(res.getString(R.string.notification_text))
            .setSmallIcon(R.drawable.icon)
            .setAutoCancel(true)
            .setTicker(getString(R.string.notification_ticker_msg));
    // Build the notification:
    Notification notification = builder.build();

    // Get the notification manager:
    NotificationManager notificationManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);

    // Publish the notification:
    final int notificationId = 0;
    notificationManager.notify(notificationId, notification);
}

person Ali Bahaj    schedule 03.05.2016    source источник


Ответы (3)


Если вы используете тот же Activity, то снова будет вызван метод onCreate. Вы можете отправить один extra с вашим Intent, который указывает, что это Intent, сгенерированный в результате щелчка уведомления. В своем Activity onCreate проверьте наличие этого дополнения и вызовите finish(), если оно присутствует.

public void getNotification() {
    Intent intent = new Intent(this, FlashActivity.class);
    intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
    intent.putExtra("origin", "notification");

    PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent , PendingIntent.FLAG_CANCEL_CURRENT);

    NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
            .setContentIntent(pIntent)
            .setContentTitle(res.getString(R.string.notification_title))
            .setContentText(res.getString(R.string.notification_text))
            .setSmallIcon(R.drawable.icon)
            .setAutoCancel(true)
            .setTicker(getString(R.string.notification_ticker_msg));
    // Build the notification:
    Notification notification = builder.build();

    // Get the notification manager:
    NotificationManager notificationManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);

    // Publish the notification:
    final int notificationId = 0;
    notificationManager.notify(notificationId, notification);
}

А в вашем методе onCreate в FlashActivity проверьте доп.

@Override
public void onCreate(Bundle savedInstanceState) {
    ...

    if("notification".equals(getIntent().getStringExtra("origin"))) {
        finish();
    }
}
person jaibatrik    schedule 03.05.2016
comment
Вы скопировали из ОП намерение = новое намерение(); - может быть, лучше что-то вроде намерения Intent = new Intent(this, MyActivity.class); - person Bö macht Blau; 03.05.2016
comment
Правильно, и даже я считаю, что для них будет лучше использовать FLAG_ACTIVITY_SINGLE_TOP или FLAG_ACTIVITY_SINGLE_TASK. - person jaibatrik; 03.05.2016
comment
о флагах - кажется, что они игнорируются при использовании с уведомлением (хотя они работают при использовании с виджетом на главном экране). Я просто попытался использовать FLAG_ACTIVITY_REORDER_TO_FRONT из уведомления, и это воссоздало действие в любом случае. То же самое касается FLAG_ACTIVITY_SINGLE_TOP. Было бы лучше избежать этого, если вы просто собираетесь закончить деятельность, но я не знаю, как это сделать. - person Bö macht Blau; 03.05.2016
comment
Имеет смысл. И похоже, что FLAG_ACTIVITY_SINGLE_TASK устарела. - person jaibatrik; 03.05.2016
comment
Поэтому я думаю, что лучшее, что вы можете сделать с точки зрения производительности, - это проверить Intent перед setContentView(). - person Bö macht Blau; 03.05.2016
comment
Спасибо за ваш ответ @jaibatrik, но он не закрывает активность, просто восстанавливает активность, и вспышка включена. - person Ali Bahaj; 03.05.2016

Я считаю, что вы можете использовать finish() в своей деятельности, когда уведомление нажато.

РЕДАКТИРОВАТЬ: Как закрыть любую активность моего приложения, нажав на уведомление?

person Omar Aflak    schedule 03.05.2016
comment
Приложение-фонарик обычно представляет собой приложение с одним действием. Если у вас более одного действия, ссылка, которую вы разместили, будет полезной (но, будучи просто ссылкой, она должна быть опубликована как комментарий, а не как ответ). Если вы хотите закончить только одно действие, предлагаемые методы слишком дороги. - person Bö macht Blau; 03.05.2016

Вы хотите использовать PendingIntent.

 Intent resultIntent = new Intent(this, MainActivity.class);
 resultIntent.putExtra("FINISH",true);
 PendingIntent resultPendingIntent =
        PendingIntent.getActivity(
        this,
        0,
        resultIntent,
        PendingIntent.FLAG_UPDATE_CURRENT
    );

builder.setContentIntent(resultPendingIntent);

// Build the notification:
    Notification notification = builder.build();
//rest of your methods to show notification

В вашем обновлении MainActivity в зависимости от вашего кода

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    onNewIntent(getIntent());
}

@Override
public void onNewIntent(Intent intent){
     setContentView(R.layout.activity_main);
    Bundle extras = intent.getExtras();
    if(extras != null){
        if(extras.containsKey("FINISH"))
        {
           finish();
        }
    }


}
person Sanif SS    schedule 03.05.2016