简体   繁体   English

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

[英]How to open the particular fragment on the click of the push notification message in the notification tab?

This is my GcmIntentService class by which i am sending the message. 这是我通过其发送消息的GcmIntentService类。 The problem is when i click on the push notification message it opens the main activity.but i want to open the particular fragment.I knew for that some changes would be in sendNotification() method. 问题是当我单击推送通知消息时,它将打开主要活动。但是我想打开特定的片段。我知道对sendNotification()方法进行了一些更改。 Can anyone tell me how can i open the particular fragment on the click of the push notification ? 谁能告诉我如何在单击推送通知时打开特定片段?

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

This is the fragment which i want to open on the click of the push notification message:- 这是我要在单击推送通知消息时打开的片段:-

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

Manage some flag and pass information from notification to MainActivity via Intent . 管理一些标志并将信息从通知通过Intent传递给MainActivity

use switch case or if/else in your MainActivity , if you are receiving perticular flag/data, load desired fragment. 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);

in your MainActivity.java 在您的MainActivity.java中

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM