Android 设备重新格式化后无法接收来自GCM服务器的通知
我有一个简单的Android应用程序,它获取GCM注册令牌并将其发送到PHP服务器,以便服务器向应用程序发送通知 以下是我的工作代码: 我的注册服务类别:Android 设备重新格式化后无法接收来自GCM服务器的通知,android,google-cloud-messaging,Android,Google Cloud Messaging,我有一个简单的Android应用程序,它获取GCM注册令牌并将其发送到PHP服务器,以便服务器向应用程序发送通知 以下是我的工作代码: 我的注册服务类别: public class RegistrationIntentService extends IntentService { private static final String TAG = "RegistrationIntentService"; private static final String pathToServ
public class RegistrationIntentService extends IntentService {
private static final String TAG = "RegistrationIntentService";
private static final String pathToServer = "http://192.168.5.200/phpserverside/registeruser.php";
public RegistrationIntentService() {
super(TAG);
}
@Override
protected void onHandleIntent(Intent intent) {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
try {
// Initially this call goes out to the network to retrieve the token, subsequent calls are local.
// R.string.gcm_defaultSenderId (the Sender ID) is typically derived from google-services.json.
InstanceID instanceID = InstanceID.getInstance(this);
String token = instanceID.getToken(getString(R.string.gcm_defaultSenderId), GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);
Log.i(TAG, "GCM Registration Token: " + token);
postData(token);
// You should store a boolean that indicates whether the generated token has been
// sent to your server. If the boolean is false, send the token to your server,
// otherwise your server should have already received the token.
sharedPreferences.edit().putBoolean(QuickstartPreferences.SENT_TOKEN_TO_SERVER, true).apply();
} catch (Exception e) {
Log.d(TAG, "Failed to complete token refresh", e);
// If an exception happens while fetching the new token or updating our registration data
// on a third-party server, this ensures that we'll attempt the update at a later time.
sharedPreferences.edit().putBoolean(QuickstartPreferences.SENT_TOKEN_TO_SERVER, false).apply();
}
// Notify UI that registration has completed, so the progress indicator can be hidden.
Intent registrationComplete = new Intent(QuickstartPreferences.REGISTRATION_COMPLETE);
LocalBroadcastManager.getInstance(this).sendBroadcast(registrationComplete);
}
public static String postData(String token) {
// Create a new HttpClient and Post Header
String _response = "";
String uristr = pathToServer;
Log.v(TAG, "URI: " + uristr);
if(uristr!=null){
HttpClient httpclient = new DefaultHttpClient();
HttpParams params = httpclient.getParams();
HttpConnectionParams.setConnectionTimeout(params, 10000);
HttpConnectionParams.setSoTimeout(params, 10000);
HttpPost httppost = new HttpPost(uristr);
Log.d(TAG, "1 wit username: " + token);
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("registrationId", token));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
InputStream inputStream = response.getEntity().getContent();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
StringBuilder stringBuilder = new StringBuilder();
String bufferedStrChunk = null;
while((bufferedStrChunk = bufferedReader.readLine()) != null){
stringBuilder.append(bufferedStrChunk);
}
_response = stringBuilder.toString();
} catch (ClientProtocolException e) {
Log.d(TAG,e.toString());
_response = "";
// TODO Auto-generated catch block
} catch (IOException e) {
Log.d(TAG,e.toString());
_response = "";
// TODO Auto-generated catch block
}
Log.v(TAG, "response: " + _response);
Log.v("reply of the server: ",_response);
return _response ;
}
return "";
}
}
public class MyGcmListenerService extends GcmListenerService {
private static final String TAG = "MyGcmListenerService";
@Override
public void onMessageReceived(String from, Bundle data) {
//super.onMessageReceived(from, data);
String message = data.getString("message");
Log.d(TAG, "Message: " + message);
Log.d(TAG, "From: " + from);
Log.d(TAG, "Message: " + message);
if (from.startsWith("/topics/")) {
// message received from some topic.
} else {
// normal downstream message.
}
sendNotification(message);
}
private void sendNotification(String message) {
Log.d("MyGcmListenerService", "message: " + message);
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.notification_icon)
.setContentTitle("GCM Message Received")
.setContentText(message)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, notificationBuilder.build());
}
}
还有我的清单文件
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.ictcsu.mybuangproject" >
<uses-permission android:name="android.permission.INTERNET"/>
<!-- For checking current network state -->
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<receiver
android:name="com.google.android.gms.gcm.GcmReceiver"
android:exported="true"
android:permission="com.google.android.c2dm.permission.SEND" >
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<category android:name="com.example.gcm" />
</intent-filter>
</receiver>
<service
android:name="com.ictcsu.mybuangproject.MyGcmListenerService"
android:exported="false" >
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
</intent-filter>
</service>
<service
android:name="com.ictcsu.mybuangproject.MyInstanceIDListenerService"
android:exported="false">
<intent-filter>
<action android:name="com.google.android.gms.iid.InstanceID" />
</intent-filter>
</service>
<service
android:name="com.ictcsu.mybuangproject.RegistrationIntentService"
android:exported="false">
</service>
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
该程序在我的华为MediaPad 7 Vogue上运行正常,但由于一些重要原因,我不得不重新格式化我的设备,并且当我重新安装应用程序时,它不再收到任何通知
我的PHP服务器的回复表明它成功了。我还将该应用程序安装到了我的LG L70上,并且它能够正确地接收通知
我真的不知道该怎么办,我已经搜索并尝试了许多代码,但都不起作用。你认为设备重新格式化与此有关吗?每次你重置设备id时,你都需要重新登录,以便在服务器端更新你的设备id。请浏览谷歌文档,了解更多关于设备id和GCM的信息,以及它是如何工作的,这将有助于跟踪问题。你在哪里订阅主题?我想是多次登录。。已为其他人保存了其他人的注册Id。。把诺蒂送去。对于其他设备…我不知道当你重新格式化设备时会发生什么,因为我自己从来没有这样做过,但是google play服务是否仍然存在或者当前是否已安装?此外,我还发现,在实践中,有时甚至重新安装应用程序也会导致GCM服务暂停一段时间。通常持续30-60分钟。如果是这种情况,请结束问题。我从上周五开始就面临这个问题,因此我猜GCM服务停止可能不是问题。出于调试目的,每次用户登录应用程序时,我都会将我的注册/设备ID发送到我的服务器。所以我想注册ID不是问题所在,但我希望能看看GCM是如何解决这个问题的。