getIntent.getExtras () возвращает нулевые данные при щелчке уведомления (Fcm) - PullRequest
0 голосов
/ 14 декабря 2018

Я использую fcm для отправки уведомлений с полезной нагрузкой данных (я исключаю объект уведомления, поскольку хочу, чтобы пользователь получал уведомления независимо от того, находится ли приложение на переднем плане / в фоне или убито).

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

Класс службы обмена сообщениями 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");
}}

Класс целевой активности (соответствует фильтру намерений)

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());
}}

Манифест

 <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>

Ответы [ 2 ]

0 голосов
/ 03 мая 2019

В Манифесте вы должны поместить MyFirebaseMessagingService в качестве службы

<service
    android:name=".MyFirebaseMessagingService ">
    <intent-filter>
        <action android:name="com.google.firebase.MESSAGING_EVENT" />
    </intent-filter>
</service>
0 голосов
/ 14 декабря 2018

Когда вы отправляете данные через созданное вами намерение.Вместо getExtras.Попробуйте getStringExtra или getIntExtra.потому что getExtras выдаст вам данные только тогда, когда система Android создаст уведомление, когда приложение находится в фоновом режиме, а onMessageReceded не вызывается.

...