如果应用程序背景,Firebase推送通知将转到错误的页面

时间:2017-02-24 12:49:59

标签: android firebase firebase-cloud-messaging

我创建了发送推送通知的应用。一切都运作良好。如果应用程序正在运行或未关闭,则会直接转到第二页。但问题是,运行我的应用程序后如果我将我的应用程序放在后台或关闭它,然后发送通知。点击通知后,它会转到主页而不是第二页。即使应用已关闭或在后台,我希望它必须带我到第二页。 以下是我的代码:

MainActivity.java

public class MainActivity extends Activity {

    private static final String TAG="MainActivity";


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button BtnshowToken=(Button)findViewById(R.id.buttonshowtoken);
        BtnshowToken.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String token= FirebaseInstanceId.getInstance().getToken();
                Log.d(TAG,"Token: "+token);
                Toast.makeText(MainActivity.this,token,Toast.LENGTH_SHORT).show();

            }
        });
    }


}

MyFirebaseInstanceIDService.java

public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService {

    private static final String TAG="MyFirebaseInsIDService";

    @Override
    public void onTokenRefresh() {

        //get updated token
        String refreshedToken= FirebaseInstanceId.getInstance().getToken();
        Log.d(TAG,"New Token: "+refreshedToken);



    }
}


MyFirebaseMessagingService.java
public class MyFirebaseMessagingService extends FirebaseMessagingService{
    private static final String TAG="MyFirebaseMsgService";


    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
       Log.d(TAG, "FROM:" +remoteMessage.getFrom());

        //Check if msg contains data
        if(remoteMessage.getData().size() > 0){
            Log.d(TAG, "Message data: "+remoteMessage.getData());
        }


        //Check if msg contains notification
        if(remoteMessage.getNotification()!=null){
            Log.d(TAG,"Message body: "+remoteMessage.getNotification().getBody());
            sendNotification(remoteMessage.getNotification().getBody());
        }
    }

        //Display notification
private void  sendNotification(String body){

    Intent intent=new Intent(this,SecondActivity.class);
    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

    PendingIntent pendingIntent=PendingIntent.getActivity(this, 0/*Request code*/, intent, PendingIntent.FLAG_ONE_SHOT);
    //Set sound of notification
    Uri notificationsound= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

    NotificationCompat.Builder notifiBuilder=new NotificationCompat.Builder(this)
            .setSmallIcon(R.mipmap.ic_launcher)
            .setContentTitle("Firebase Cloud Messaging")
            .setContentText(body)
            .setAutoCancel(true)
            .setSound(notificationsound)
            .setContentIntent(pendingIntent);


    NotificationManager notificationManager=(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.notify(0/*Id of notification*/,notifiBuilder.build());



    }
}


SecondActivity.java
public class SecondActivity extends Activity {

     TextView tv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.second);


    }
}


activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">





    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="200dp"
        android:id="@+id/imageView"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="151dp"
        android:src="@drawable/firebase"/>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Show Token"
        android:id="@+id/buttonshowtoken"
        android:layout_below="@+id/imageView"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="49dp" />
</RelativeLayout>


second.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">


<TextView
    android:id="@+id/tv2"
    android:layout_width="match_parent"
    android:layout_height="150dp"
    android:text="Second Activity"
    android:textColor="#000"
    android:gravity="center"
    android:textSize="30dp"/>

    <ImageView
        android:layout_marginTop="10dp"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/image"
        android:src="@drawable/welcome"
        />

</LinearLayout>


AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.abc.firebasenoteg" >


    <uses-permission android:name="android.permission.INTERNET"/>
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>


        <activity
            android:name=".SecondActivity"
            android:label="@string/app_name">
            <intent-filter>
                <action android:name="YourActivity" />
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>

        </activity>

        <service
            android:name=".MyFirebaseMessagingService"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="com.google.firebase.MESSAGING_EVENT" />


            </intent-filter>
        </service>

        <service
            android:name=".MyFirebaseInstanceIDService"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="com.google.firebase.INSTANCE_ID_EVENT" />


            </intent-filter>
        </service>



    </application>

</manifest>


google-services.json
{

  "project_info": {
    "project_number": "785125209715",
    "firebase_url": "https://fir-notification-a5fce.firebaseio.com",
    "project_id": "fir-notification-a5fce",
    "storage_bucket": "fir-notification-a5fce.appspot.com"
  },
  "client": [
    {
      "client_info": {
        "mobilesdk_app_id": "1:785125209715:android:676ef33a2e673fd3",
        "android_client_info": {
          "package_name": "com.example.abc.firebasenoteg"
        }
      },
      "oauth_client": [
        {
          "client_id": "785125209715-496loih2csg0egp7h9hphtiaui49coeb.apps.googleusercontent.com",
          "client_type": 3
        }
      ],
      "api_key": [
        {
          "current_key": "AIzaSyCdvlwxewCNStJwTwcqq3CGBGZ08j9MVdU"
        }
      ],
      "services": {
        "analytics_service": {
          "status": 1
        },
        "appinvite_service": {
          "status": 1,
          "other_platform_oauth_client": []
        },
        "ads_service": {
          "status": 2
        }
      }



    }
  ],


  "configuration_version": "1",



}

2 个答案:

答案 0 :(得分:4)

您需要从服务器请求中单击ClickListener,并在您的活动中的清单intent-action中添加侦听器名称。

"notification" : {
"body" : "Body",
"title" : "Titme",
"icon" : "YourIcon"
"click_action" : "<<yourkey e.g. MainActivity>>"
}

<activity
     android:name=".MainActivity">
     <intent-filter>
        <action android:name="<<yourkey e.g. MainActivity>>" />
        <category android:name="android.intent.category.DEFAULT" />
    </intent-filter>

这适用于您的应用在前台无法使用的情况。 希望这有用,谢谢

答案 1 :(得分:0)

如果应用程序处于后台并且您单击通知,则数据将存储在intent的附加内容中。所以你需要的是firebase请求中的 action_code 。这是一个例子:

Firebase请求:

{
  "to": "/topics/order",
  "priority": "high",
  "notification": {
    "title": "Hello admin",
    "body":"There's new order :)",
    "sound":"default"
  },
  "data": {
    "msgCode":"newOrder"
  }
}

<强> MainActivity.java

Intent intent = getIntent();
if (intent.hasExtra("msgCode")) {
    String msgCode = intent.getStringExtra("msgCode");
    if (msgCode.equals("newOrder")) {
        Toast.makeText(this, "newOrder", Toast.LENGTH_SHORT).show();
        Log.i("zihad", "newOrder");
        startActivity(new Intent(this, ListOrderActivity.class));
        intent.removeExtra("msgCode");
    }
}