如何将GCM通知消息放入android中的活动? [英] How to get GCM notification messages into an activity in android?
问题描述
我使用GCM向用户发送通知。一切都完成了。我创建了一个服务器端编程,为push_message创建一个休息,并完成了所有事情。
当我点击通知时,这些消息会打开到我的活动中。
如何在我的活动中打开我的消息?
这是我的GCMIntentService.java
package com.angelnx。 angelnx.mygcm.gcm;
导入android.app.IntentService;
导入android.content.Intent;
导入android.content.SharedPreferences;
导入android.preference.PreferenceManager;
导入android.support.v4.content.LocalBroadcastManager;
导入android.util.Log;
导入android.widget.Toast;
import com.angelnx.angelnx.mygcm.R;
import com.angelnx.angelnx.mygcm.app.Config;
import com.angelnx.angelnx.mygcm.app.EndPoints;
import com.angelnx.angelnx.mygcm.app.MyApplication;
import com.angelnx.angelnx.mygcm.model.User;
导入com.google.android.gms.gcm.GoogleCloudMessaging;
import com.google.android.gms.iid.InstanceID;
import com.android.volley.NetworkResponse;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.google.android.gms.gcm.GcmPubSub;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
public class GcmIntentService extends IntentService {
private static final String TAG = GcmIntentService.class.getSimpleName();
public GcmIntentService(){
super(TAG);
}
public static final String KEY =key;
public static final String TOPIC =topic;
public static final String SUBSCRIBE =subscribe;
public static final String UNSUBSCRIBE =unsubscribe;
@Override
protected void onHandleIntent(意图意图){
String key = intent.getStringExtra(KEY);
switch(key){
case SUBSCRIBE:
//订阅某个主题
String topic = intent.getStringExtra(TOPIC);
subscribeToTopic(topic);
休息;
情况UNSUBSCRIBE:
break;
默认值:
//如果指定了密钥,用GCM注册
registerGCM();
}
}
private void registerGCM(){
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
尝试{
InstanceID instanceID = InstanceID.getInstance(this);
String token = instanceID.getToken(getString(R.string.gcm_defaultSenderId),GoogleCloudMessaging.INSTANCE_ID_SCOPE,null);
Log.e(TAG,GCM注册令牌:+令牌);
sendRegistrationToServer(token);
sharedPreferences.edit()。putBoolean(Config.SENT_TOKEN_TO_SERVER,true).apply();
catch(Exception e){
Log.e(TAG,FAILED TO COMPLETED TASK+ e);
sharedPreferences.edit()。putBoolean(Config.SENT_TOKEN_TO_SERVER,false).apply();
}
//通知UI注册已完成,因此可以隐藏进度指示器。
Intent registrationComplete = new Intent(Config.REGISTRATION_COMPLETE);
LocalBroadcastManager.getInstance(this).sendBroadcast(registrationComplete);
}
private void sendRegistrationToServer(final String token){
User user = MyApplication.getInstance()。getPrefManager()。getUser();
if(user == null){
return;
}
String endPoint = EndPoints.USER.replace(_ ID _,user.getId());
Log.e(TAG,endpoints:+ endPoint);
StringRequest strReq = new StringRequest(Request.Method.PUT,
endPoint,new Response.Listener< String>(){
@Override
public void onResponse(String response){
Log.e(TAG,response:+ response);
try {
JSONObject obj = new JSONObject(response);
//检查错误
if(obj.getBoolean(error)== false){
//广播令牌发送到服务器
Intent registrationComplete = new Intent(Config.SENT_TOKEN_TO_SERVER);
LocalBroadcastManager.getInstance(getApplicationContext())。sendBroadcast(registrationComplete);
} else {
Toast.makeText(getApplicationContext(),无法发送gcm注册id给我们的服务器。+ obj.getJSONObject(error)。getStrin g(message),Toast.LENGTH_LONG).show();
}
} catch(JSONException e){
Log.e(TAG,json parsing error:+ e.getMessage());
Toast.makeText(getApplicationContext(),Json parse error:+ e.getMessage(),Toast.LENGTH_SHORT).show();
},new Response.ErrorListener(){
$ b @Override
public void onErrorResponse(VolleyError error){
NetworkResponse networkResponse = error.networkResponse;
Log.e(TAG,Volley error:+ error.getMessage()+,code:+ networkResponse);
Toast.makeText(getApplicationContext(),Volley error:+ error.getMessage(),Toast.LENGTH_SHORT).show();
}
}){
@Override
保护地图< String,String> getParams(){
Map< String,String> params = new HashMap<>();
params.put(gcm_registration_id,token);
Log.e(TAG,params:+ params.toString());
返回参数;
}
};
//向请求队列添加请求
MyApplication.getInstance()。addToRequestQueue(strReq);
$ b $ **
*订阅主题
* /
public static void subscribeToTopic(String topic){
GcmPubSub pubSub = GcmPubSub.getInstance(MyApplication.getInstance()。getApplicationContext());
InstanceID instanceID = InstanceID.getInstance(MyApplication.getInstance()。getApplicationContext());
String token = null;
try {
token = instanceID.getToken(MyApplication.getInstance()。getApplicationContext()。getString(R.string.gcm_defaultSenderId),
GoogleCloudMessaging.INSTANCE_ID_SCOPE,null);
if(token!= null){
pubSub.subscribe(token,/ topics /+ topic,null);
Log.e(标签,订阅主题:+主题);
} else {
Log.e(TAG,error:gcm registration id is null);
}
} catch(IOException e){
Log.e(TAG,Topic subscribe error。Topic:+ topic +,error:+ e.getMessage());
Toast.makeText(MyApplication.getInstance()。getApplicationContext(),Topic subscribe error。Topic:+ topic +,error:+ e.getMessage(),Toast.LENGTH_SHORT).show();
public void unsubscribeFromTopic(String topic){
GcmPubSub pubSub = GcmPubSub.getInstance(getApplicationContext());
InstanceID instanceID = InstanceID.getInstance(getApplicationContext());
String token = null;
尝试{
token = instanceID.getToken(getString(R.string.gcm_defaultSenderId),
GoogleCloudMessaging.INSTANCE_ID_SCOPE,null);
if(token!= null){
pubSub.unsubscribe(token,);
Log.e(标签,取消订阅主题:+主题);
} else {
Log.e(TAG,error:gcm registration id is null);
}
} catch(IOException e){
Log.e(TAG,Topic unsubscribe error。Topic:+ topic +,error:+ e.getMessage());
Toast.makeText(getApplicationContext(),Topic subscribe error。Topic:+ topic +,error:+ e.getMessage(),Toast.LENGTH_SHORT).show();
}
}
}
请帮我解决。
您只需创建一个实现GcmListenerService的服务即可。
public class EMSListenerService extends GcmListenerService {
private static final String TAG =ems_service;
@Override
public void onMessageReceived(String from,Bundle data){
super.onMessageReceived(from,data);
Display.log(TAG,EMS received);
$ b $ / code $ / pre
当你收到你的信息时需要使用 LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
广播到活动Explanation:
I am using GCM to send notification to the users.Everything is completed.I was created a server side programming to create a rest for push_message and all the thing is done.
When i click on the notification this messages are open into my activity.
How can i do to open my messages in my activity?
Here is my GCMIntentService.java
package com.angelnx.angelnx.mygcm.gcm;
import android.app.IntentService;
import android.content.Intent;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;
import android.widget.Toast;
import com.angelnx.angelnx.mygcm.R;
import com.angelnx.angelnx.mygcm.app.Config;
import com.angelnx.angelnx.mygcm.app.EndPoints;
import com.angelnx.angelnx.mygcm.app.MyApplication;
import com.angelnx.angelnx.mygcm.model.User;
import com.google.android.gms.gcm.GoogleCloudMessaging;
import com.google.android.gms.iid.InstanceID;
import com.android.volley.NetworkResponse;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.google.android.gms.gcm.GcmPubSub;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
public class GcmIntentService extends IntentService{
private static final String TAG = GcmIntentService.class.getSimpleName();
public GcmIntentService() {
super(TAG);
}
public static final String KEY = "key";
public static final String TOPIC = "topic";
public static final String SUBSCRIBE = "subscribe";
public static final String UNSUBSCRIBE = "unsubscribe";
@Override
protected void onHandleIntent(Intent intent) {
String key = intent.getStringExtra(KEY);
switch (key) {
case SUBSCRIBE:
// subscribe to a topic
String topic = intent.getStringExtra(TOPIC);
subscribeToTopic(topic);
break;
case UNSUBSCRIBE:
break;
default:
// if key is specified, register with GCM
registerGCM();
}
}
private void registerGCM(){
SharedPreferences sharedPreferences= PreferenceManager.getDefaultSharedPreferences(this);
try{
InstanceID instanceID=InstanceID.getInstance(this);
String token=instanceID.getToken(getString(R.string.gcm_defaultSenderId), GoogleCloudMessaging.INSTANCE_ID_SCOPE,null);
Log.e(TAG,"GCM Registration Token:"+token);
sendRegistrationToServer(token);
sharedPreferences.edit().putBoolean(Config.SENT_TOKEN_TO_SERVER,true).apply();
}
catch (Exception e){
Log.e(TAG,"FAILED TO COMPLETED TASK"+e);
sharedPreferences.edit().putBoolean(Config.SENT_TOKEN_TO_SERVER,false).apply();
}
//Notify UI that registration has completed, so the progress indicator can be hidden.
Intent registrationComplete = new Intent(Config.REGISTRATION_COMPLETE);
LocalBroadcastManager.getInstance(this).sendBroadcast(registrationComplete);
}
private void sendRegistrationToServer(final String token) {
User user= MyApplication.getInstance().getPrefManager().getUser();
if(user==null){
return;
}
String endPoint= EndPoints.USER.replace("_ID_",user.getId());
Log.e(TAG,"endpoints :"+endPoint);
StringRequest strReq = new StringRequest(Request.Method.PUT,
endPoint, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Log.e(TAG, "response: " + response);
try {
JSONObject obj = new JSONObject(response);
// check for error
if (obj.getBoolean("error") == false) {
// broadcasting token sent to server
Intent registrationComplete = new Intent(Config.SENT_TOKEN_TO_SERVER);
LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(registrationComplete);
} else {
Toast.makeText(getApplicationContext(), "Unable to send gcm registration id to our sever. " + obj.getJSONObject("error").getString("message"), Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
Log.e(TAG, "json parsing error: " + e.getMessage());
Toast.makeText(getApplicationContext(), "Json parse error: " + e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
NetworkResponse networkResponse = error.networkResponse;
Log.e(TAG, "Volley error: " + error.getMessage() + ", code: " + networkResponse);
Toast.makeText(getApplicationContext(), "Volley error: " + error.getMessage(), Toast.LENGTH_SHORT).show();
}
}) {
@Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
params.put("gcm_registration_id", token);
Log.e(TAG, "params: " + params.toString());
return params;
}
};
//Adding request to request queue
MyApplication.getInstance().addToRequestQueue(strReq);
}
/**
* Subscribe to a topic
*/
public static void subscribeToTopic(String topic) {
GcmPubSub pubSub = GcmPubSub.getInstance(MyApplication.getInstance().getApplicationContext());
InstanceID instanceID = InstanceID.getInstance(MyApplication.getInstance().getApplicationContext());
String token = null;
try {
token = instanceID.getToken(MyApplication.getInstance().getApplicationContext().getString(R.string.gcm_defaultSenderId),
GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);
if (token != null) {
pubSub.subscribe(token, "/topics/" + topic, null);
Log.e(TAG, "Subscribed to topic: " + topic);
} else {
Log.e(TAG, "error: gcm registration id is null");
}
} catch (IOException e) {
Log.e(TAG, "Topic subscribe error. Topic: " + topic + ", error: " + e.getMessage());
Toast.makeText(MyApplication.getInstance().getApplicationContext(), "Topic subscribe error. Topic: " + topic + ", error: " + e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
public void unsubscribeFromTopic(String topic) {
GcmPubSub pubSub = GcmPubSub.getInstance(getApplicationContext());
InstanceID instanceID = InstanceID.getInstance(getApplicationContext());
String token = null;
try {
token = instanceID.getToken(getString(R.string.gcm_defaultSenderId),
GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);
if (token != null) {
pubSub.unsubscribe(token, "");
Log.e(TAG, "Unsubscribed from topic: " + topic);
} else {
Log.e(TAG, "error: gcm registration id is null");
}
} catch (IOException e) {
Log.e(TAG, "Topic unsubscribe error. Topic: " + topic + ", error: " + e.getMessage());
Toast.makeText(getApplicationContext(), "Topic subscribe error. Topic: " + topic + ", error: " + e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
}
Please, help me to solve out.
解决方案 All you need to do is create one service that implements GcmListenerService.
public class EMSListenerService extends GcmListenerService {
private static final String TAG = "ems_service";
@Override
public void onMessageReceived(String from, Bundle data) {
super.onMessageReceived(from, data);
Display.log(TAG, "EMS received");
}
}
And when you receive the message you need to broadcast to the activity using LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
这篇关于如何将GCM通知消息放入android中的活动?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!