我在我的应用程序中嵌入GCM推送通知。我面临一个非常奇怪的问题,第一次运行时,我无法获得GCM注册令牌,但是当您第二次运行我的应用程序时,您将在控制台上获得注册ID打印。我不知道我在做什么。这是我迄今为止所做的。Android GCM:未在onCreate()方法上获取注册令牌
这是我的onCreate()方法,我想打印GCM的RegID:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final String regId = GCMRegistrar.getRegistrationId(this);
GCM_regID = regId;
System.out.println("GCM regId: "+GCM_regID);
否则里面的onCreate()下面的代码:
/**
* Google Cloud Messaging - Getting server Url and device ID to send it
* across Google server for the notification..
*/
mGCMReceiver = new GCMReceiver();
mOnRegisteredFilter = new IntentFilter();
mOnRegisteredFilter.addAction(Constants.ACTION_ON_REGISTERED);
if (Constants.SENDER_ID == null) {
// mStatus.setText("Missing SENDER_ID");
return;
}
if (Constants.SERVER_URL == null) {
// mStatus.setText("Missing SERVER_URL");
return;
}
GCMRegistrar.checkDevice(this);
GCMRegistrar.checkManifest(this);
if (!regId.equals("")) {
sendIdToServer(regId);
} else {
GCMRegistrar.register(getApplicationContext(), Constants.SENDER_ID);
}
sendIdToServer(regId);
}
通过这些方法,发送GCM_regId服务器教程之一:
/**
* GCM - sending the data in json format to server db
* */
public void sendIdToServer(String regId) {
(new SendRegistrationIdTask(regId)).execute();
GCM_regID = regId;
}
private class GCMReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String regId = intent
.getStringExtra(Constants.FIELD_REGISTRATION_ID);
token = regId;
}
}
private final class SendRegistrationIdTask extends
AsyncTask<String, Void, HttpResponse> {
// private String mRegId;
public SendRegistrationIdTask(String regId) {
// mRegId = regId;
}
@Override
protected HttpResponse doInBackground(String... regIds) {
// String url = Constants.SERVER_URL + "/register";
return null;
}
@Override
protected void onPostExecute(HttpResponse response) {
if (response == null) {
return;
}
StatusLine httpStatus = response.getStatusLine();
if (httpStatus.getStatusCode() != 200) {
Log.e(Constants.TAG, "Status: " + httpStatus.getStatusCode());
return;
}
}
}
我不这么认为,需要GCMIntentService类这里是为了我的问题。请仔细研究并帮助我解决这个问题。
我可以在GCMIntentService类的onRegistered()中打印。这里是:
@Override
protected void onRegistered(Context context, String regId) {
Intent intent = new Intent(Constants.ACTION_ON_REGISTERED);
intent.putExtra(Constants.FIELD_REGISTRATION_ID, regId);
context.sendBroadcast(intent);
}
我必须在onCreate()MainActivity上打印regId。
我得到了GCMIntentService的值,所以如何在MainActivity中获取该值。我试过这样做,但没有为我工作。 – Anupam
在GCMIntentService中,覆盖onRegistered()方法,并且您的值在String arg1中与上述参数类似。只需打印它。 – dominic
把一个静态字符串等同于它并在ur类中访问该字符串。 – dominic