如何在通知选项卡中单击推送通知消息打开特定片段



这是我发送消息的GcmIntentService类。问题是当我点击推送通知消息时,它打开了主要活动。但我想打开这个特殊的片段。我知道sendNotification()方法会发生一些变化。谁能告诉我如何打开推送通知的点击上的特定片段?

public class GcmIntentService extends IntentService {
    public static final int NOTIFICATION_ID = 1;
    private NotificationManager mNotificationManager;
    private final static String TAG = "GcmIntentService";
    public GcmIntentService() {
        super("GcmIntentService");
    }
    @Override
    protected void onHandleIntent(Intent intent) {
        Bundle extras = intent.getExtras();

        GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
        String messageType = gcm.getMessageType(intent);
        if (!extras.isEmpty()) {
            if (GoogleCloudMessaging.MESSAGE_TYPE_SEND_ERROR
                    .equals(messageType)) {
                sendNotification("Send error: " + extras.toString());
            } else if (GoogleCloudMessaging.MESSAGE_TYPE_DELETED
                    .equals(messageType)) {
                sendNotification("Deleted messages on server: " + extras.toString());
            } else if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE
                    .equals(messageType)) {
                for (int i = 0; i < 5; i++) {
                    Log.d(TAG, " Working... " + (i + 1) + "/5 @ "
                            + SystemClock.elapsedRealtime());
                    try {
                        Thread.sleep(5000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                sendNotification(extras.getString("message"));
            }
        }      WakefulBroadcastReceiver.
        GcmBroadcastReceiver.completeWakefulIntent(intent);
    }    

    private void sendNotification(String msg) {
        mNotificationManager = (NotificationManager) this
                .getSystemService(Context.NOTIFICATION_SERVICE);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, MainActivity.class), 0);

        NotificationCompat.Builder mBuilder = (NotificationCompat.Builder) new NotificationCompat.Builder(this)
                .setSmallIcon(getNotificationIcon())
                .setContentTitle("Telepoh")
                .setStyle(new NotificationCompat.BigTextStyle().bigText(msg))
                .setContentText(msg)
                .setDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE);
        mBuilder.setContentIntent(contentIntent);
        mBuilder.getNotification().flags |= Notification.FLAG_AUTO_CANCEL;
        mBuilder.setAutoCancel(true);
        mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
    }
    private int getNotificationIcon() {
        boolean useWhiteIcon = (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP);
        return useWhiteIcon ? R.drawable.gcm : R.drawable.push_icon;
    }
}

这是我想在点击推送通知消息时打开的片段:-

public class NotificationActivity extends Fragment {
    ProgressDialog pd;
    private SharedPreferencesUtilities sharedPreferencesUtilities;
    private GeneralUtilities generalUtilities;
    private View rootView;
    private ListView listView;
    private TextView txtKm;
    private TextView emptyView;
    int progressValue=0;
    int progressValue2;
    public NotificationActivity notilist = null;
    HttpResponse response;
    public ArrayList<ListViewItem> notiarray = new ArrayList<ListViewItem>();
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (rootView == null) {
            rootView = inflater.inflate(R.layout.notification_screen, container, false);
            getActivity().setTitle("Notifications");
            generalUtilities = new GeneralUtilities(getActivity());
            sharedPreferencesUtilities = new SharedPreferencesUtilities(getActivity());
            notilist = this;
            new GetNotificationData().execute();
        }
        return rootView;
    }
    public class GetNotificationData extends AsyncTask<String , String , String> {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pd = new ProgressDialog(getActivity());
            pd.setCancelable(true);
            pd.setMessage("Loading...");
            pd.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            pd.show();
        }
        @Override
        protected String doInBackground(String... params) {
            notificationlistData();
            return null;
        }
        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            pd.dismiss();
            if (generalUtilities.isConnected()) {
                HttpEntity entity = response.getEntity();
                String json = null;
                try {
                    json = EntityUtils.toString(entity);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                try {
                    final JSONObject jObject = new JSONObject(json);

                    if (jObject.getString("ReplyCode").equals("1")) {
                        JSONArray jsonUserObject = jObject.getJSONArray("data");

                        for (int i = 0; i < jsonUserObject.length(); i++) {
                            notiarray.add(new ListViewItem(jsonUserObject.getJSONObject(i).getString("OtherUserName"),
                                    jsonUserObject.getJSONObject(i).getString("UserProfilePic"), jsonUserObject.getJSONObject(i).getString("Status"),
                                    jsonUserObject.getJSONObject(i).getString("ID"),jsonUserObject.getJSONObject(i).getString("EventsID"),
                                    jsonUserObject.getJSONObject(i).getString("OtherUserID")));
                        }
                        Resources res =getResources();
                        listView = (ListView) rootView.findViewById(R.id.notification_list);
                        emptyView = (TextView) rootView.findViewById(R.id.empty_view);
                        if (notiarray.isEmpty()) {
                            listView.setVisibility(View.GONE);
                            emptyView.setVisibility(View.VISIBLE);
                        }
                        else {
                            listView.setVisibility(View.VISIBLE);
                            emptyView.setVisibility(View.GONE);
                            NotificationAdapter nAdapter = new NotificationAdapter(notilist, notiarray, res);
                            listView.setAdapter(nAdapter);
                        }
                    } else {
                        generalUtilities.showAlertDialog("Request Cancelled", new JSONObject(json).getString("Message"), "OK");
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } else {
                generalUtilities.showAlertDialog("Error", getResources().getString(R.string.internet_error), "OK");
            }
        }
    }
    public void notificationlistData() {
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(getResources().getString(R.string.api_end_point) + "ShowNotification/NotificationData");
        httppost.setHeader(HTTP.CONTENT_TYPE, "application/x-www-form-urlencoded;charset=UTF-8");
        try {
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
            nameValuePairs.add(new BasicNameValuePair("ID", String.valueOf(sharedPreferencesUtilities.getUserId())));
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
            response = httpclient.execute(httppost);
        } catch (ClientProtocolException e) {
          e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);
    }
    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        inflater.inflate(R.menu.main_distance, menu);
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_distance:
                AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(getActivity());
                LayoutInflater inflater = getActivity().getLayoutInflater();
                View dialogView = inflater.inflate(R.layout.setdistance_popup, null);
                dialogBuilder.setView(dialogView);
                final AlertDialog alertDialog = dialogBuilder.create();
                alertDialog.show();
                TextView txtTitle = (TextView) dialogView.findViewById(R.id.textView58);
                txtKm = (TextView) dialogView.findViewById(R.id.textView500);
                TextView  txthn = (TextView) dialogView.findViewById(R.id.textView59);
                TextView txtDiscription = (TextView) dialogView.findViewById(R.id.textView63);
                LinearLayout btnSet = (LinearLayout) dialogView.findViewById(R.id.buttonSet);
                LinearLayout btnCancel = (LinearLayout) dialogView.findViewById(R.id.buttonCancel);
                txthn.setText(10+sharedPreferencesUtilities.getRadiodistance());
                SeekBar popupSeek = (SeekBar) dialogView.findViewById(R.id.seekBar2);
                if(sharedPreferencesUtilities.getProfiledistance()=="")
                {
                    popupSeek.setProgress(0);
                    txtKm.setText("500 Meter");
                }
                else
                {
                    Integer checkCount = Integer.parseInt(sharedPreferencesUtilities.getProfiledistance());
                    if(checkCount==0)
                    {
                        popupSeek.setProgress(0);
                        txtKm.setText("500 Meter");
                    }
                    else
                    {
              popupSeek.setProgress(Integer.parseInt(sharedPreferencesUtilities.getProfiledistance()));
                        txtKm.setText(sharedPreferencesUtilities.getProfiledistance() + sharedPreferencesUtilities.getRadiodistance());
                    }
                }
                popupSeek.setMax(10);
                popupSeek.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
                    @Override
                    public void onStopTrackingTouch(SeekBar seekBar) {
                    }
                    @Override
                    public void onStartTrackingTouch(SeekBar seekBar) {
                    }
                    @Override
                    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                        // progress = ((int)Math.round(progress/0.5));
                        progressValue2 = progressValue+progress;
                        if(progress==0)
                        {
                            txtKm.setText("500 Meter");
                        }
                        else {
                            txtKm.setText(Integer.toString(progressValue2) + sharedPreferencesUtilities.getRadiodistance());
                        }
                    }
                });
                btnSet.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        sharedPreferencesUtilities.setProfiledistance(String.valueOf(progressValue2));
                        alertDialog.dismiss();
                    }
                });
                btnCancel.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        alertDialog.dismiss();
                    }
                });
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }
}

管理一些标志,通过Intent将通知信息传递给MainActivity

MainActivity中使用switch case或if/else,如果您正在接收特定的标志/数据,则加载所需的片段。

Intent passIntent = new Intent(this, MainActivity.class);
passIntent.putExtra("flag","some value");
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, passIntent, 0);

在MainActivity.java

if(getIntent().hasExtra("flag")){
    if(getIntent.getStringExtra("flag").equalsIgnorCase("some value"))
    {
          //write code to load your fragment.
    }
}

最新更新