onClick通知片段Android

时间:2017-09-05 10:32:55

标签: java android android-fragments

我正在处理通知部分。我能够将用户导航到活动点击通知消息。我的实际任务是将用户导航到片段。

这是通知代码,工作正常。

NotificationCompat.Builder builder =
            new NotificationCompat.Builder(getApplicationContext())
                    .setSmallIcon(R.mipmap.ic_launcher)
                    .setContentTitle("Lugmah Order Status")
                    .setContentText("The Order Status of Order Id: "+selectedOrderId+ " is: "+status_desc)
                    .setDefaults(NotificationCompat.DEFAULT_SOUND)
                    .setAutoCancel(true);
    int NOTIFICATION_ID = 12345;

    Intent targetIntent = new Intent(getApplicationContext(), MainActivity.class);

    targetIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);

    targetIntent.putExtra("isTrackOrder", false);
    targetIntent.putExtra("orderNotification", "orderNotification");
    targetIntent.putExtra("isLoggedIn", true);
    targetIntent.putExtra("status_desc", status_desc);
    targetIntent.putExtra("selectedOrderId", selectedOrderId);

    PendingIntent contentIntent = PendingIntent
                .getActivity(getApplicationContext(), 0, targetIntent, PendingIntent.FLAG_ONE_SHOT);

    builder.setContentIntent(contentIntent);


    NotificationManager nManager = (NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
    nManager.notify(NOTIFICATION_ID, builder.build());

我在意图中添加了 MainActivity.java ,因为这是我加载所有片段的地方。在这项活动中,我做了类似的事情。

这是onCreate()中的代码:

String orderNotification = getIntent().getStringExtra("orderNotification");

        android.support.v4.app.FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();

        if (orderNotification != null)
        {
            if (orderNotification.equals("orderNotification"))
            {
                TrackOrderFragment trackOrderFragment = new TrackOrderFragment();
                fragmentTransaction.replace(android.R.id.content, trackOrderFragment);
                fragmentTransaction.addToBackStack(null);
                fragmentTransaction.commit();
            }
        }

帮助将不胜感激。

1 个答案:

答案 0 :(得分:4)

您的通知代码可以正常工作,您需要调整onCreate上的代码。

if(getIntent().getExtras() != null) {
   String orderNotification = getIntent().getStringExtra("orderNotification");  

  if (orderNotification.equals("orderNotification"))
            {
                TrackOrderFragment trackOrderFragment = new TrackOrderFragment();
                fragmentTransaction.replace(android.R.id.content, trackOrderFragment);
                fragmentTransaction.addToBackStack(null);
                fragmentTransaction.commit();
            }
        }

每次活动运行onCreate时,您需要检查是否收到任何额外内容,因为可能会发生空指针异常。