android - getIntent.getExtras() 在通知点击时返回空数据 (Fcm)

标签 android firebase push-notification firebase-cloud-messaging android-push-notification

我正在使用 fcm 发送带有数据有效负载的通知(我排除了通知对象,因为我希望用户无论应用程序处于前台/后台还是已被终止,都能收到通知)。

我能够获取通知并在用户点击通知时将用户导航到特定 Activity 。但是,我无法从 getIntent extras 中获取值。每次我尝试获取值时,我都会得到空值。我想不出哪里出了问题。

FCM 消息服务类

public class MyFirebaseMessagingService extends FirebaseMessagingService {

private static final String TAG = "MyFirebaseMessagingServ";

NotificationManager notificationManager;



@Override
public void onNewToken(String token) {
    super.onNewToken(token);
    Log.e(TAG, "onNewToken: "+token );
    if(PrefManager.isVendorLoggedIn(MyFirebaseMessagingService.this))
            sendNewTokenToServer(token);
}

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


private void showNotification(RemoteMessage remoteMessage){
    String orderID="";
    Map<String,String> dataMap = remoteMessage.getData();
    orderID = dataMap.get("order_id");


    String title="New Order";
    String message="Click here to view the Details";
    String click_action=dataMap.get("click_action");



    Intent intent=new Intent(click_action);
    intent.addFlags( Intent.FLAG_ACTIVITY_NEW_TASK);
    intent.addFlags( Intent.FLAG_ACTIVITY_CLEAR_TASK);
    PendingIntent pendingIntent=PendingIntent.getActivity(this,0,intent,PendingIntent.FLAG_UPDATE_CURRENT);
    intent.putExtra(StringConstants.CURRENT_ORDER_ID,orderID);
    intent.putExtra(StringConstants.BUZ_ID,dataMap.get("business_id"));
    intent.putExtra("TITLE",title);
    intent.putExtra("BODY",message);


    NotificationCompat.Builder notificationBuilder=new NotificationCompat.Builder(this);
    notificationBuilder.setContentTitle(title);
    notificationBuilder.setContentText(message);
    notificationBuilder.setSmallIcon(R.drawable.splash_logo);
    notificationBuilder.setAutoCancel(true);
    notificationBuilder.setContentIntent(pendingIntent);
    notificationManager=(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.notify(8,notificationBuilder.build());
}

private void sendNoti(RemoteMessage remoteMessage){

    String click_action=remoteMessage.getData().get("click_action");
    Intent intent=new Intent(click_action);
    //Intent intent = new Intent(this, MainActivity.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
            PendingIntent.FLAG_ONE_SHOT|PendingIntent.FLAG_UPDATE_CURRENT);

    String channelId = "101";
    Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    NotificationCompat.Builder notificationBuilder =
            new NotificationCompat.Builder(this, channelId)
                    .setSmallIcon(R.drawable.splash_logo)
                    .setContentTitle("New Order receieved!!")
                    .setContentText("Click to view details")
                    .setAutoCancel(true)
                    .setSound(defaultSoundUri)
                    .setContentIntent(pendingIntent);

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

    // Since android Oreo notification channel is needed.
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        NotificationChannel channel = new NotificationChannel(channelId,
                "Channel human readable title",
                NotificationManager.IMPORTANCE_DEFAULT);
        notificationManager.createNotificationChannel(channel);
    }

    notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}

private void sendNewTokenToServer(String token){
    PrefManager prefManager = new PrefManager(MyFirebaseMessagingService.this);
    String url = Constants.BASE_URL+"vendor/add-refresh-token";
    JSONObject jsonObject = new JSONObject();
    try {
        jsonObject.put("vendor_id",prefManager.getVendorId(getApplicationContext()));
        jsonObject.put("token",token);
    } catch (JSONException e) {
        e.printStackTrace();
    }
    CustomJsonRequest customJsonRequest = new CustomJsonRequest(Request.Method.POST, url, jsonObject, new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject response) {

        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {

        }
    });
    customJsonRequest.setPriority(Request.Priority.HIGH);
    ReatchAll helper = ReatchAll.getInstance();
    helper.addToRequestQueue(customJsonRequest,"UPDATE_TOKEN");
}}

目标 Activity 类(匹配 intent 过滤器)

public class VendorCurrentOrderActivity extends AppCompatActivity {

private static final String TAG = "VendorCurrentOrderActiv";
Context context;
ReatchAll helper = ReatchAll.getInstance();
CustomProgressDialog customProgressDialog;
PrefManager prefManager;


String orderId,buzId;
OrderedItemsAdapter orderedItemsAdapter;
ArrayList<OrderedItem> orderedItemArrayList;

RecyclerView itemsRcv;
ImageView backArrow;
FontTextView acceptOrder,rejectOrder;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_vendor_current_order);
    context = VendorCurrentOrderActivity.this;
    customProgressDialog = new CustomProgressDialog(context);
    prefManager = new PrefManager(context);

    backArrow =(ImageView)findViewById(R.id.back_arrow);
    backArrow.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            finish();
        }
    });

    initViews();

    orderId = getIntent().getExtras().getString(StringConstants.CURRENT_ORDER_ID);
    buzId = getIntent().getExtras().getString(StringConstants.BUZ_ID);
    Log.e(TAG, "onCreate: "+orderId);
    Log.e(TAG, "onCreate: NOTI DATA "+getIntent().getExtras().getString("TITLE")+" "+getIntent().getExtras().getString("BODY") );
    customProgressDialog.showDialog();
    getOrderDetails();

   // onNewIntent(getIntent());
}}

list

 <activity android:name=".Vendor.Orders.VendorCurrentOrderActivity"
        android:launchMode="singleTask"
        android:taskAffinity=""
        android:excludeFromRecents="true"
        android:exported="true">
        <intent-filter>
            <action android:name="NEW_ORDER" />
            <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>
    </activity>

最佳答案

当您通过您创建的 Intent 发送数据时。而不是 getExtras。试试 getStringExtragetIntExtra。因为 getExtras 只会在应用程序处于后台且 onMessageRecieved 未被调用时由 android 系统创建通知时为您提供数据。

关于android - getIntent.getExtras() 在通知点击时返回空数据 (Fcm),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53780253/

相关文章:

android - 应用程序在后台运行时查找当前位置不起作用

java - 如何从两个数组列表中删除不常见的元素

android - OnGestureListener.onDown()返回false的含义

javascript - 需要从 firebase html 调用数据的帮助

ios - 无法使用 APN 授权 key 发送推送通知 iOS

android - onActivityResult应该在哪里处理,dialog fragment,fragment,还是activity?

android - 在 Firebase 中生成 6 位唯一编号

asp.net-mvc - Asp.Net MVC 和 HTML5 推送通知

java - FCM : onMessageReceived is not called, 即使在向 fcm 发送消息后也没有收到通知?

iphone - AdHoc 构建未收到推送通知