Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.9k views
in Technique[技术] by (71.8m points)

android - Unable to launch activity from notification when app is in background

I am using the following code to display the notification and launching the activity when user taps on the notification. Everything is working as expected when the app is in foreground. i.e. when the user taps on the notification the specified activity is displayed with all the back stack of activities. But when the app is in background or killed, then tapping on notification does not opens the specified activity, it re-runs the app and the launcher activity is started.

Please Help!

Here is my NotificationHelper class:


import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.provider.Settings;

import androidx.core.app.NotificationCompat;
import androidx.core.app.NotificationManagerCompat;
import androidx.core.app.TaskStackBuilder;

import java.util.Date;


public class NotificationHelper {
    public static final String CH_ID="zsms001";
    public static final String CH_NAME="zenotek sms";
    public static final String CH_DESC="Zenotek SMS Notifications";
    private static int rCode=(int) new Date().getTime();

    public static void displayNotification(Context context, String mtitle, String mbody){
        Intent intent;

        if (mtitle.equals("New Homework")){
            intent=new Intent(context, HomeworkActivity.class);
        }
        else {
            if (mtitle.equals("New Circular")){
                intent=new Intent(context, CircularActivity.class);
            }
            else {
                intent=new Intent(context, NavigationActivity.class);
            }
        }

        TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
        stackBuilder.addParentStack(NavigationActivity.class);
        stackBuilder.addNextIntent(intent);
        PendingIntent pintent = PendingIntent.getActivity(context, rCode, intent, PendingIntent.FLAG_UPDATE_CURRENT);

        NotificationCompat.Builder nBuilder=new NotificationCompat.Builder(context,CH_ID)
                .setSmallIcon(R.drawable.ic_ghs_logo_small)
                .setContentTitle(mtitle)
                .setContentText(mbody)
                .setContentIntent(pintent)
                .setAutoCancel(true)
                .setSound(Settings.System.DEFAULT_NOTIFICATION_URI)
                .setPriority(Notification.PRIORITY_DEFAULT)
                .setLights(Color.RED,1000,2000);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
            NotificationManager nMan;

            NotificationChannel nChannel =new NotificationChannel(CH_ID,CH_NAME, NotificationManager.IMPORTANCE_DEFAULT);
            nChannel.setDescription(CH_DESC);
            nChannel.enableLights(true);
            nChannel.setLightColor(Color.RED);

            nMan=context.getSystemService(NotificationManager.class);
            assert nMan != null;
            nBuilder.setChannelId(CH_ID);
            nMan.createNotificationChannel(nChannel);
            nMan.notify(rCode,nBuilder.build());
        }
        else {
            NotificationManagerCompat nMan;
            nMan=NotificationManagerCompat.from(context);
            nMan.notify(rCode,nBuilder.build());
        }
    }
}

FirebaseMsgService class:

package com.zenotek.ghsvaranasi;

import android.annotation.SuppressLint;
import android.os.AsyncTask;
import android.util.Log;

import androidx.annotation.NonNull;

import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;

import org.json.JSONException;
import org.json.JSONObject;

public class FirebaseMsgService extends FirebaseMessagingService {
    private FirebaseAuth mAuth = FirebaseAuth.getInstance();
    private int cuid;
    public static boolean NewTokenGenerated=false;

    @Override
    public void onNewToken(@NonNull String s) {
        Log.d("New Token",s);
        if (mAuth.getCurrentUser()!=null){
            Log.d("Current user",mAuth.getCurrentUser().getUid());
            cuid=Integer.parseInt(mAuth.getCurrentUser().getUid().substring(1));
            SaveTokentoServer savetoken=new SaveTokentoServer();
            savetoken.execute(s);
        }
        else{
            NewTokenGenerated=true;
        }
    }

    @Override
    public void onMessageReceived(@NonNull RemoteMessage remoteMessage) {
        super.onMessageReceived(remoteMessage);

        if (remoteMessage.getNotification()!=null){
            String mTitle=remoteMessage.getNotification().getTitle();
            String mBody=remoteMessage.getNotification().getBody();

            NotificationHelper.displayNotification(getApplicationContext(), mTitle, mBody);
        }
    }

    public class SaveTokentoServer extends AsyncTask<String,String,String> {
        String msg;

        @Override
        protected String doInBackground(String... strings) {
            String ftoken=strings[0];
            RestAPI api=new RestAPI();

            try {
                JSONObject joRoot=api.Save_SFirebase_Token(cuid,ftoken);
                Log.d("Save Token joRoot",joRoot.toString());
                boolean RStat=joRoot.getBoolean("Successful");

                if (!RStat){
                    msg=joRoot.getString("ErrorMessage");
                    Log.d("save token joRoot Error",msg);
                }
                else {
                    Log.d("save token joRoot","Token Refreshed Successfully!");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

First, you need extend your class from FirebaseMessagingService. Here is the an example of implementation: https://gist.github.com/jirawatee/85d4b46a89b9ae821b63c31f5d5189de

Also If you want to handle notifications in background, you need to send your notifications with "data" not with the "notification"

https://firebase.google.com/docs/cloud-messaging/android/receive


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...