我正在尝试制作一个结合GCM+PHP+MYSQL的应用程序。我的应用程序可以从 Google 服务器获取注册 ID 并将其存储到我的服务器,但是当我向设备发送消息时onReceive()方法似乎无法正常工作(genymotion Htc One 4.2.2 with google API17)。
我的服务器显示的回显表:
{"multicast_id":6654020603006207086,"success":1,"failure":0,"canonical_ids":0,"results":[{"message_id":"0:1383807091667423%6852480ef9fd7ecd"}]}
所以我认为服务器部分可能工作正常。
在我发送消息之前,这些应用程序收到了以下通知:
Recieved:Bundle[mParcelledData.dataSize=48]
但是消息表单服务器消失了, onRecive(...) 什么也没发生。
我在这里阅读了服务器主题,但我仍然不知道为什么。
我只是在没有 GCMIntentService 的情况下实现 Broadcastreceiver 因为有些参考比谷歌的参考更容易做到这一点。
这个问题困扰了我两天,请帮助我 m(_ _)m ..
这是我的清单:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.csie.gcmtest"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="18" />
<permission android:name="com.csie.gcmtest.permission.C2D_MESSAGE" android:protectionLevel="signature"></permission>
<uses-permission android:name="com.csie.gcmtest.permission.C2D_MESSAGE"/>
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.GET_ACCOUNTS"/>
<uses-permission android:name="android.permission.WAKE_LOCK"/>
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.csie.gcmtest.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver
android:name=".GcmBroadcastReceiver"
android:permission="com.google.android.c2dm.permission.SEND" >
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<action android:name="com.google.android.c2dm.intent.REGISTRATION" />
<category android:name="com.csie.gcmtest" />
</intent-filter>
</receiver>
</application>
</manifest>
主要活动:
public class MainActivity extends Activity {
GoogleCloudMessaging gcm;
String SENDER_ID = "327943842431"; //project ID
Context context;
String strRegId;
TextView tvRegisterMsg;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvRegisterMsg = (TextView) findViewById(R.id.tvRegisterMsg);
context = getApplicationContext();
// initial GCM
gcm = GoogleCloudMessaging.getInstance(this);
// register with Google.
new AsyncTask<Void,String,String>() {
@Override
protected String doInBackground(Void... params) {
String msg = "";
try {
if (gcm == null) {
gcm = GoogleCloudMessaging.getInstance(context);
}
strRegId = gcm.register(SENDER_ID);
msg = "Device registered, registration id=" + strRegId;
// send id to our server
sendRegIdToServer(strRegId);
} catch (IOException ex) {
msg = "Error :" + ex.getMessage();
}
return msg;
}
@Override
protected void onPostExecute(String msg) {
tvRegisterMsg.append(msg + "\n");
}
}.execute(null, null, null);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
private void sendRegIdToServer(final String strId) {
new AsyncTask<Void,String,String>() {
@Override
protected String doInBackground(Void... params) {
String strResponseCode = "";
HttpPost httpRequest = new HttpPost("http://89.0.1.213/android_add.php");
List<NameValuePair> p = new ArrayList<NameValuePair>();
p.add(new BasicNameValuePair("data", strId));
try {
/* 發出HTTP request */
httpRequest.setEntity(new UrlEncodedFormEntity(p, HTTP.UTF_8));
/* 取得HTTP response */
HttpResponse httpResponse = new DefaultHttpClient().execute(httpRequest);
strResponseCode = Integer.toString(httpResponse.getStatusLine().getStatusCode());
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return strResponseCode;
}
@Override
protected void onPostExecute(String msg) {
tvRegisterMsg.append("status code: " + msg + "\n");
}
}.execute(null, null, null);
}
}
广播接收器:
public class GcmBroadcastReceiver extends BroadcastReceiver {
static final String TAG = "GCMDemo";
public static final int NOTIFICATION_ID = 1;
private NotificationManager mNotificationManager;
NotificationCompat.Builder builder;
Context ctx;
@Override
public void onReceive(Context context, Intent intent) {
Log.i("onReceive","fuck");
GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(context);
ctx = context;
String messageType = gcm.getMessageType(intent);
if (GoogleCloudMessaging.MESSAGE_TYPE_SEND_ERROR.equals(messageType)) {
sendNotification("Send error: " + intent.getExtras().toString());
Log.i("onReceive","fuck_type_error");
} else if (GoogleCloudMessaging.MESSAGE_TYPE_DELETED .equals(messageType)) {
sendNotification("Deleted messages on server: " + intent.getExtras().toString());
Log.i("onReceive","deleted");
} else {
sendNotification("Received: " + intent.getExtras().toString());
Log.i("onReceive","received:"+ intent.getExtras().toString());
}
setResultCode(Activity.RESULT_OK);
Log.i("onReceive","fuck done");
}
// Put the GCM message into a notification and post it.
private void sendNotification(String msg) {
mNotificationManager = (NotificationManager) ctx.getSystemService(Context.NOTIFICATION_SERVICE);
PendingIntent contentIntent = PendingIntent.getActivity(ctx, 0,
new Intent(ctx, MainActivity.class), 0);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(ctx)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("GCM Notification")
.setStyle(new NotificationCompat.BigTextStyle().bigText(msg))
.setContentText(msg);
mBuilder.setContentIntent(contentIntent);
mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
}
}