Created Project and got server api key and sender id from https://developers.google.com/cloud-messaging/android/start .and used following code to generate registration id
GoogleCloudMessaging gcm;
String SENDER_ID = "mysenderid";
String Reg_id;
Context context;
EditText firstNumber;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Reg_id=registerGCM();
}
public String registerGCM()
{
String regid=null;
try {
firstNumber = (EditText)findViewById(R.id.regisid_1);
context = getApplicationContext();
gcm = GoogleCloudMessaging.getInstance(context);
regid = gcm.register(SENDER_ID);
firstNumber.setText(regid);
}
catch(Exception ae)
{
}
return regid;
}
But after executing code ,regid shows null.
if gcm id is null try to start a background task and get the id.check the below code
private void registerInBackground() {
new AsyncTask() {
@Override
protected String doInBackground(Object[] params) {
String msg = "";
try {
if (gcm == null) {
gcm = GoogleCloudMessaging.getInstance(context);
}
regid = gcm.register(SENDER_ID);
msg = "Device registered, registration ID=" + regid;
sendRegistrationIdToBackend();
// Persist the regID - no need to register again.
storeRegistrationId(context, regid);
} catch (IOException ex) {
msg = "Error :" + ex.getMessage();
}
return msg;
}
@Override
protected void onPostExecute(Object msg) {
// mDisplay.append(msg + "\n");
}
}.execute(null, null, null);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.