如何在通知选项卡中单击推送通知消息打开特定片段?
Posted
技术标签:
【中文标题】如何在通知选项卡中单击推送通知消息打开特定片段?【英文标题】:How to open the particular fragment on the click of the push notification message in the notification tab? 【发布时间】:2016-09-07 12:35:58 【问题描述】:这是我发送消息的GcmIntentService
类。问题是当我单击推送通知消息时,它会打开主要活动。但我想打开特定的片段。我知道sendNotification()
method 中会有一些更改。谁能告诉我如何在点击推送通知时打开特定片段?
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);
【问题讨论】:
【参考方案1】:管理一些标志并通过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.
【讨论】:
亲爱的先生,它不工作。当我点击通知消息时没有加载片段。而不是片段主要活动正在打开。 你能告诉我主要活动的哪个方法我得到了意图并加载片段。我在 create() 方法中完成了这项工作。以上是关于如何在通知选项卡中单击推送通知消息打开特定片段?的主要内容,如果未能解决你的问题,请参考以下文章