我有一个简单的Android应用程序,它获取GCM注册令牌并将其发送到PHP服务器,以便服务器向应用程序发送通知。
以下是我的工作代码:
我的RegistrationIntentService类:
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 "";
}
}
我的MyGcmListenerService类:
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 上正常运行,但由于某些重要原因我不得不重新格式化我的设备,当我重新安装该应用程序时,它不再收到任何通知。 / p>
我的PHP服务器的回复表明它成功了。我还将应用程序安装到我的 LG L70 手机上,并正确接收通知。
我真的不知道该怎么做,我已经搜索并尝试了很多代码,但它没有用。你认为设备重新格式化与此有关吗?
答案 0 :(得分:0)
每次重置设备时,设备ID都会更改,因此您需要再次登录,以便在服务器端更新设备ID。请浏览google文档以了解有关设备ID和GCM的更多信息以及它如何工作,这将有助于跟踪问题。