Skip to content

Instantly share code, notes, and snippets.

@a1yama
Last active January 20, 2016 04:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save a1yama/aa8b68201ffd785106ed to your computer and use it in GitHub Desktop.
Save a1yama/aa8b68201ffd785106ed to your computer and use it in GitHub Desktop.
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.content.Context;
import com.google.android.gms.gcm.GoogleCloudMessaging;
import com.google.android.gms.iid.InstanceID;
import java.io.IOException;
public class MainActivity extends Activity {
/** Google Cloud Messagingオブジェクト */
private GoogleCloudMessaging gcm;
/** コンテキスト */
private Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context = getApplicationContext();
gcm = GoogleCloudMessaging.getInstance(this);
registerInBackground();
}
private void registerInBackground() {
new AsyncTask<Void, Void, String>() {
@Override
protected String doInBackground(Void... params) {
String regId = "";
try {
if (gcm == null) {
gcm = GoogleCloudMessaging.getInstance(MainActivity.this);
}
InstanceID instanceID = InstanceID.getInstance(context);
// senderIdはプロジェクト番号
regId = instanceID.getToken("senderId", GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);
} catch (IOException ex) {
ex.printStackTrace();
}
return regId;
}
@Override
protected void onPostExecute(String regId) {
Log.d("hoge", regId);
}
}.execute(null, null, null);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment