我正在开发一个多玩家测验应用程序。我使用GCM从我的服务器向设备发送消息。注册由此代码完成 //skeletonactivity.java
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart(): Connecting to Google APIs");
mGoogleApiClient.connect();
regId = registerGCM();
appUtil=new ShareExternalServer();
shareRegidTask = new AsyncTask<Void, Void, String>() {
@Override
protected String doInBackground(Void... params) {
String result = appUtil.shareRegIdWithAppServer(context, regId);
return result;
}
@Override
protected void onPostExecute(String result) {
shareRegidTask = null;
Toast.makeText(getApplicationContext(), result,
Toast.LENGTH_LONG).show();
}
};
shareRegidTask.execute(null, null, null);
Log.d("RegisterActivity", "GCM RegId: " + regId);
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
Intent intent=new Intent(SkeletonActivity.this,Quizform.class);
startActivity(intent);
finish();
}
}, 1000);
//我已经尝试过一段时间后启动活动,以便收到GCM消息。但是没有变化。
}
public String registerGCM() {
gcm = GoogleCloudMessaging.getInstance(this);
regId = getRegistrationId(context);
if (TextUtils.isEmpty(regId)) {
registerInBackground();
Log.d("RegisterActivity",
"registerGCM - successfully registered with GCM server - regId: "
+ regId);
}
return regId;
}
private String getRegistrationId(Context context) {
final SharedPreferences prefs = getSharedPreferences(
SkeletonActivity.class.getSimpleName(), Context.MODE_PRIVATE);
String registrationId = prefs.getString(REG_ID, "");
if (registrationId.isEmpty()) {
Log.i(TAG, "Registration not found.");
return "";
}
return registrationId;
}
private void registerInBackground() {
new AsyncTask<Void,Void,String>() {
@Override
protected String doInBackground(Void...Params) {
String msg = "";
try {
if (gcm == null) {
gcm = GoogleCloudMessaging.getInstance(context);
}
regId = gcm.register(GOOGLE_PROJECT_ID);
Log.d("RegisterActivity", "registerInBackground - regId: "
+ regId);
msg = "Device registered, registration ID=" + regId;
storeRegistrationId(context, regId);
} catch (IOException ex) {
msg = "Error :" + ex.getMessage();
Log.d("RegisterActivity", "Error: " + msg);
}
Log.d("RegisterActivity", "AsyncTask completed: " + msg);
return msg;
}
@Override
protected void onPostExecute(String msg) {
Toast.makeText(getApplicationContext(),
"Registered with GCM Server." + msg, Toast.LENGTH_LONG)
.show();
}
}.execute(null, null, null);
}
private void storeRegistrationId(Context context, String regId) {
final SharedPreferences prefs = getSharedPreferences(
SkeletonActivity.class.getSimpleName(), Context.MODE_PRIVATE);
Log.i(TAG, "Saving regId on app version" );
SharedPreferences.Editor editor = prefs.edit();
editor.putString(REG_ID, regId);
editor.commit();
}
与外部活动共享的代码是 shareExternalServer
public class ShareExternalServer {
public String shareRegIdWithAppServer(final Context context,
final String regId) {
String result = "";
Map paramsMap = new HashMap();
paramsMap.put("regId", regId);
try {
URL serverUrl = null;
try {
serverUrl = new URL(Config.APP_SERVER_URL);
} catch (MalformedURLException e) {
Log.e("AppUtil", "URL Connection Error: "
+ Config.APP_SERVER_URL, e);
result = "Invalid URL: " + Config.APP_SERVER_URL;
}
StringBuilder postBody = new StringBuilder();
Iterator<Entry> iterator = paramsMap.entrySet()
.iterator();
while (iterator.hasNext()) {
Entry param = iterator.next();
postBody.append(param.getKey()).append('=')
.append(param.getValue());
if (iterator.hasNext()) {
postBody.append('&');
}
}
String body = postBody.toString();
byte[] bytes = body.getBytes();
HttpURLConnection httpCon = null;
try {
httpCon = (HttpURLConnection) serverUrl.openConnection();
httpCon.setDoOutput(true);
httpCon.setUseCaches(false);
httpCon.setFixedLengthStreamingMode(bytes.length);
httpCon.setRequestMethod("POST");
httpCon.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded;charset=UTF-8");
OutputStream out = httpCon.getOutputStream();
out.write(bytes);
out.close();
int status = httpCon.getResponseCode();
if (status == 200) {
result = "RegId shared with Application Server. RegId: "
+ regId;
} else {
result = "Post Failure." + " Status: " + status;
}
} finally {
if (httpCon != null) {
httpCon.disconnect();
}
}
} catch (IOException e) {
result = "Post Failure. Error in sharing with App Server.";
Log.e("AppUtil", "Error in sharing with App Server: " + e);
}
return result;
}
}
GCMIntentService.java的代码 公共类GcmIntentService扩展了IntentService {
public GcmIntentService() {
super("GcmIntentService");
}
public SharedPreferences sharedPreferences;
public static SharedPreferences getSharedPreferences (Context ctxt) {
return ctxt.getSharedPreferences("message",0);
}
public static boolean flag;
public static final String TAG = "GCM Demo";
public String mess=" ";
@Override
protected void onHandleIntent(Intent intent) {
Bundle extras = intent.getExtras();
sharedPreferences= getSharedPreferences(this);
SharedPreferences.Editor editor=sharedPreferences.edit();
GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
String messageType=gcm.getMessageType(intent);
if (!extras.isEmpty()) { // has effect of unparcelling Bundle
if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE.equals(messageType)) {
Log.i(TAG, "Completed work @ " + SystemClock.elapsedRealtime());
mess= extras.getString("message");
editor.putString("mess",mess);
editor.commit();
Log.i(TAG, "Received: " + mess);
}
}
GcmBroadcastReceiver.completeWakefulIntent(intent);
}
}
以上代码从广播接收器获取值并将其存储为字符串msg。 我尝试在quizform.java
中访问它protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); sharedPreferences=getApplicationContext().getSharedPreferences("messages",0);
setContentView(R.layout.activity_quizform);
txt = sharedPreferences.getString("mess","empty");
Toast.makeText(this, txt, Toast.LENGTH_LONG).show();
}
txt的值为空,所以我只得到一个空白的吐司。 服务器在获得regID后立即发送消息。代码是:
<?php
//generic php function to send GCM push notification
function sendPushNotificationToGCM($registatoin_ids, $message) {
//Google cloud messaging GCM-API url
$url = 'https://android.googleapis.com/gcm/send';
$fields = array(
'registration_ids' => $registatoin_ids,
'data' => $message,
);
// Google Cloud Messaging GCM API Key
define("GOOGLE_API_KEY", "apikey");
$headers = array(
'Authorization: key=' . GOOGLE_API_KEY,
'Content-Type: application/json'
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
$result = curl_exec($ch);
if ($result === FALSE) {
die('Curl failed: ' . curl_error($ch));
}
curl_close($ch);
return $result;
}
function sendquestions()
{
$servername = " ";
$username = " ";
$password = " ";
$dbname=" ";
$conn = mysqli_connect($servername, $username, $password,$dbname);
$pushStatus = "";
$result= mysqli_query($conn,"SELECT id FROM regid");
while($row = $result->fetch_assoc()){
$gcmRegID=$row['id'];}
$pushMessage = "hello";
if (isset($gcmRegID) && isset($pushMessage)) {
$gcmRegIds = array($gcmRegID);
$message = array("message" => $pushMessage);
$pushStatus = sendPushNotificationToGCM($gcmRegIds, $message);
}
}
//this block is to receive the GCM regId from external (mobile apps)
if(!empty($_GET["shareRegId"]))
{
$gcmRegID = $_POST["regId"];
mysqli_query($conn,"INSERT INTO regid (id) VALUES('$gcmRegID')");
$retval = mysql_query( $mysqli, $conn );
mysqli_close($conn);
sendquestions();
exit;
}
?>
请建议如何克服延误。谢谢