Firebase - активность возобновляется, когда пользователь нажимает на уведомление - PullRequest
0 голосов
/ 08 февраля 2020

Я пишу приложение, которое использует firebase для реализации уведомлений. В моей MainActivity у меня есть WebView с некоторым URL, но дело в том, что когда пользователь нажимает на уведомление, я хочу открыть MainActiviy с другим URL в WebView. Я много читал, и я добавил в намерение пакет (который открывает MainActivity при нажатии на уведомление), который содержит нужный URL. Но когда я нажимаю на уведомление, MainActivity перезапускается, я имею в виду, что оно не go для onNewIntent, а вместо этого оно запускается на Create. Вот как я это реализовал:

private void sendNotification(String messageTitle, String messageBody, String url){

    Intent intent = new Intent(this, MainActivity.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

    //This adds the url to the intent
    if(!url.equals("")){
        Bundle bundle = new Bundle();
        bundle.putString("url", url);
        intent.putExtras(bundle);
    }

    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,intent, PendingIntent.FLAG_ONE_SHOT);

    String channelId = getString(R.string.default_notification_channel_id);

    NotificationCompat.Builder notificationBuilder = new NotificationCompat
            .Builder(this, channelId)
            .setContentTitle(messageTitle)
            .setContentText(messageBody)
            .setPriority(NotificationCompat.PRIORITY_DEFAULT)
            .setAutoCancel(true)
            .setSmallIcon(R.drawable.ic_launcher_background)
            .setContentIntent(pendingIntent);

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

    if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
        NotificationChannel channel = new NotificationChannel(channelId,
                "Notification channel",
                NotificationManager.IMPORTANCE_DEFAULT);
        notificationManager.createNotificationChannel(channel);
    }

    notificationManager.notify(0, notificationBuilder.build());

}

onNewIntent У меня есть это:

Bundle bundle = intent.getExtras();
        if (bundle != null) {
            String url = bundle.getString("url");
            mWebView.loadUrl(url);
        }

Но при нажатии на уведомление действие просто перезапускается, поэтому оно не запускается на NewIntent, и журнал дает мне эту ошибку:

02-08 12:51:12.140 19056-19056/com.example.android.app E/ActivityThread: Activity com.example.android.app.MainActivity has leaked IntentReceiver com.example.android.app.MainActivity$1@d7818db that was originally registered here. Are you missing a call to unregisterReceiver()?
android.app.IntentReceiverLeaked: Activity com.example.android.app.MainActivity has leaked IntentReceiver com.example.android.app.MainActivity$1@d7818db that was originally registered here. Are you missing a call to unregisterReceiver()?
    at android.app.LoadedApk$ReceiverDispatcher.<init>(LoadedApk.java:999)
    at android.app.LoadedApk.getReceiverDispatcher(LoadedApk.java:795)
    at android.app.ContextImpl.registerReceiverInternal(ContextImpl.java:1329)
    at android.app.ContextImpl.registerReceiver(ContextImpl.java:1309)
    at android.app.ContextImpl.registerReceiver(ContextImpl.java:1303)
    at android.content.ContextWrapper.registerReceiver(ContextWrapper.java:554)
    at com.example.android.app.MainActivity.onCreate(MainActivity.java:264)
    at android.app.Activity.performCreate(Activity.java:6367)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1110)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2404)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2511)
    at android.app.ActivityThread.access$900(ActivityThread.java:165)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1375)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:150)
    at android.app.ActivityThread.main(ActivityThread.java:5621)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:794)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:684)

Я читал аналогичный вопрос о stackoverflow, чтобы отменить регистрацию BroadCastReceiver, чтобы исправить эту ошибку, но я немного растерялся, как это сделать.

Я пытался изменить намерение на sendNotification на

Intent intent = new Intent("android.intent.action.MAIN");

, но в том случае, когда пользователь щелкает уведомление, оно ничего не делает.

Кто-нибудь знает, как это сделать? исправить это так, что URL-адрес загружается, когда пользователь нажимает? Заранее спасибо

Ответы [ 2 ]

1 голос
/ 08 февраля 2020

Из Android документов он заявляет это:

Если он объявил свой режим запуска «множественным» (по умолчанию), и вы не установили FLAG_ACTIVITY_SINGLE_TOP в то же самое намерение, тогда это будет закончено и воссоздано; для всех других режимов запуска или если установлено значение FLAG_ACTIVITY_SINGLE_TOP, то это намерение будет доставлено в onNewIntent () текущего экземпляра.

Таким образом, похоже, что установка флага FLAG_ACTIVITY_SINGLE_TOP при создании нового намерения должна решить и запустите метод onNewIntent () вместо повторного создания приложения.

0 голосов
/ 08 февраля 2020

создайте метод, подобный этому

private PendingIntent retrievePlaybackAction(final String action) {
    Intent intent = new Intent(action);
    return PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
}

Теперь добавьте свое намерение вот так

builder.setContentIntent(retrievePlaybackAction("OPEN_MAIN")); //change action text as you want

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

private NotificationReceiver notificationReceiver;

В onCreate() зарегистрируйте своих получателей

notificationReceiver = new NotificationReceiver();

IntentFilter intentFilterNextClick = new IntentFilter("OPEN_MAIN");

registerReceiver(notificationReceiver, intentFilterNextClick); 
//can create exception, better to surround with try catch

В onDestroy() отмените регистрацию вашего получателя

unregisterReceiver(notificationReceiver); 
//can create exception, better to surround with try catch

В открыть или выполнить какое-либо действие добавить это в свой приемник

@Override
public void onReceive(Context context, Intent intent) {
    Log.e(TAG, "onReceive: received " + intent.getAction());

    String action = intent.getAction();

    //no need to create switch you can also use if
    switch (action) {
        case "OPEN_MAIN":
            openMain();
            break;
    }

}

//here is openMain();
private void openMain(Context context) {
    Intent openMainIntent = new Intent(context, MainActivity.class);
    openMainIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); //this flag is important
    context.startActivity(openMainIntent);
}

Это также будет работать, если приложение свернуто или закрыто

Надеюсь, это поможет!

Пожалуйста, спросите, если Вам нужна дополнительная помощь!

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...