如何在android中使用GCM获取RegistrationID
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11516782/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get RegistrationID using GCM in android
提问by Neha
I am trying to do push notification in android using GCM. I read the Google docs for GCM and their demo application. I created the client side program mentioned here
http://android.amolgupta.in/
. But i am not getting registration ID. Also I am not getting some points like:
我正在尝试使用 GCM 在 android 中进行推送通知。我阅读了 GCM 的 Google 文档及其演示应用程序。我创建了这里提到的客户端程序
http://android.amolgupta.in/
。但是我没有得到注册ID。我也没有得到一些要点,例如:
- do i need to server program too with this
- on Google demo app they mention that i need to change api key at "samples/gcm-demo-server/WebContent/WEB-INF/classes/api.key" is it necessary to do it every time as i am creating new project
- 我也需要用这个服务器程序吗
- 在 Google 演示应用程序上,他们提到我需要在“samples/gcm-demo-server/WebContent/WEB-INF/classes/api.key”处更改 api 密钥,每次我创建新项目时都需要这样做吗
Can any one provide me proper project other than google provided so that i clear my concepts.
除了谷歌提供的之外,任何人都可以为我提供适当的项目,以便我清除我的概念。
Any help will be appreciated.
任何帮助将不胜感激。
回答by swiftBoy
Here I have written a few steps for How to Get RegID and Notification starting from scratch
这里我写了几个步骤如何从头开始获取RegID和通知
- Create/Register App on Google Cloud
- Setup Cloud SDK with Development
- Configure project for GCM
- Get Device Registration ID
- Send Push Notifications
- Receive Push Notifications
- 在 Google Cloud 上创建/注册应用
- 使用开发设置 Cloud SDK
- 为 GCM 配置项目
- 获取设备注册 ID
- 发送推送通知
- 接收推送通知
You can find a complete tutorial here:
您可以在此处找到完整的教程:
Code snippet to get Registration ID (Device Token for Push Notification).
获取注册 ID(推送通知的设备令牌)的代码片段。
Configure project for GCM
为 GCM 配置项目
Update AndroidManifest file
更新 AndroidManifest 文件
To enable GCM in our project we need to add a few permissions to our manifest file. Go to AndroidManifest.xml
and add this code:
Add Permissions
要在我们的项目中启用 GCM,我们需要向清单文件添加一些权限。转到AndroidManifest.xml
并添加此代码:添加权限
<uses-permission android:name="android.permission.INTERNET”/>
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name=“.permission.RECEIVE" />
<uses-permission android:name=“<your_package_name_here>.permission.C2D_MESSAGE" />
<permission android:name=“<your_package_name_here>.permission.C2D_MESSAGE"
android:protectionLevel="signature" />
Add GCM Broadcast Receiver declaration in your application tag:
在您的应用程序标签中添加 GCM 广播接收器声明:
<application
<receiver
android:name=".GcmBroadcastReceiver"
android:permission="com.google.android.c2dm.permission.SEND" ]]>
<intent-filter]]>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<category android:name="" />
</intent-filter]]>
</receiver]]>
<application/>
Add GCM Service declaration
添加 GCM 服务声明
<application
<service android:name=".GcmIntentService" />
<application/>
Get Registration ID (Device Token for Push Notification)
获取注册 ID(推送通知的设备令牌)
Now Go to your Launch/Splash Activity
现在转到您的启动/启动活动
Add Constants and Class Variables
添加常量和类变量
private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;
public static final String EXTRA_MESSAGE = "message";
public static final String PROPERTY_REG_ID = "registration_id";
private static final String PROPERTY_APP_VERSION = "appVersion";
private final static String TAG = "LaunchActivity";
protected String SENDER_ID = "Your_sender_id";
private GoogleCloudMessaging gcm =null;
private String regid = null;
private Context context= null;
Update OnCreate and OnResume methods
更新 OnCreate 和 OnResume 方法
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_launch);
context = getApplicationContext();
if (checkPlayServices()) {
gcm = GoogleCloudMessaging.getInstance(this);
regid = getRegistrationId(context);
if (regid.isEmpty()) {
registerInBackground();
} else {
Log.d(TAG, "No valid Google Play Services APK found.");
}
}
}
@Override
protected void onResume() {
super.onResume();
checkPlayServices();
}
// # Implement GCM Required methods(Add below methods in LaunchActivity)
private boolean checkPlayServices() {
int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if (resultCode != ConnectionResult.SUCCESS) {
if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
GooglePlayServicesUtil.getErrorDialog(resultCode, this,
PLAY_SERVICES_RESOLUTION_REQUEST).show();
} else {
Log.d(TAG, "This device is not supported - Google Play Services.");
finish();
}
return false;
}
return true;
}
private String getRegistrationId(Context context) {
final SharedPreferences prefs = getGCMPreferences(context);
String registrationId = prefs.getString(PROPERTY_REG_ID, "");
if (registrationId.isEmpty()) {
Log.d(TAG, "Registration ID not found.");
return "";
}
int registeredVersion = prefs.getInt(PROPERTY_APP_VERSION, Integer.MIN_VALUE);
int currentVersion = getAppVersion(context);
if (registeredVersion != currentVersion) {
Log.d(TAG, "App version changed.");
return "";
}
return registrationId;
}
private SharedPreferences getGCMPreferences(Context context) {
return getSharedPreferences(LaunchActivity.class.getSimpleName(),
Context.MODE_PRIVATE);
}
private static int getAppVersion(Context context) {
try {
PackageInfo packageInfo = context.getPackageManager()
.getPackageInfo(context.getPackageName(), 0);
return packageInfo.versionCode;
} catch (NameNotFoundException e) {
throw new RuntimeException("Could not get package name: " + e);
}
}
private void registerInBackground() {
new AsyncTask() {
@Override
protected Object doInBackground(Object...params) {
String msg = "";
try {
if (gcm == null) {
gcm = GoogleCloudMessaging.getInstance(context);
}
regid = gcm.register(SENDER_ID);
Log.d(TAG, "########################################");
Log.d(TAG, "Current Device's Registration ID is: " + msg);
} catch (IOException ex) {
msg = "Error :" + ex.getMessage();
}
return null;
}
protected void onPostExecute(Object result) {
//to do here
};
}.execute(null, null, null);
}
Note: please store REGISTRATION_KEY
, it is important for sending PN Message to GCM. Also keep in mind: this key will be unique for all devices and GCM will send Push Notifications by REGISTRATION_KEY
only.
注意:请保存REGISTRATION_KEY
,向 GCM 发送 PN Message 很重要。还要记住:这个密钥对所有设备都是唯一的,GCM 将REGISTRATION_KEY
仅发送推送通知。
回答by Sparky
In response to your first question: Yes, you have to run a server app to send the messages, as well as a client app to receive them.
回答你的第一个问题:是的,你必须运行一个服务器应用程序来发送消息,以及一个客户端应用程序来接收它们。
In response to your second question: Yes, every application needs its own API key. This key is for your server app, not the client.
回答您的第二个问题:是的,每个应用程序都需要自己的 API 密钥。此密钥用于您的服务器应用程序,而不是客户端。
回答by Gagan Deep
Use this code to get Registration ID using GCM
使用此代码使用 GCM 获取注册 ID
String regId = "", msg = "";
public void getRegisterationID() {
new AsyncTask() {
@Override
protected Object doInBackground(Object...params) {
String msg = "";
try {
if (gcm == null) {
gcm = GoogleCloudMessaging.getInstance(Login.this);
}
regId = gcm.register(YOUR_SENDER_ID);
Log.d("in async task", regId);
// try
msg = "Device registered, registration ID=" + regId;
} catch (IOException ex) {
msg = "Error :" + ex.getMessage();
}
return msg;
}
}.execute(null, null, null);
}
and don't forget to write permissions in manifest...
I hope it helps!
并且不要忘记在清单中写入权限......
我希望它有所帮助!