如何在android中使用GCM获取RegistrationID

Neh*_*eha 23 android push-notification google-cloud-messaging

我正在尝试使用GCM在android中进行推送通知.我阅读了有关GCM的Google文档及其演示应用程序.我创建了这里提到的客户端程序 http://android.amolgupta.in/.但我没有获得注册ID.此外,我没有得到一些点,如:

  1. 我是否需要服务器程序呢?
  2. 在Google演示应用程序中,他们提到我需要更改api键"samples/gcm-demo-server/WebContent/WEB-INF/classes/api.key"是否有必要每次都这样做,因为我正在创建新项目

任何人都可以为我提供除谷歌提供的正确项目,以便我清除我的概念.

任何帮助将不胜感激.

swi*_*Boy 22

在这里,我已经为如何从头开始获取RegID和Notification编写了几个步骤

  1. 在Google Cloud上创建/注册应用
  2. 使用开发设置Cloud SDK
  3. 为GCM配置项目
  4. 获取设备注册ID
  5. 发送推送通知
  6. 接收推送通知

你可以在这里找到一个完整的教程:

Android推送通知入门:最新的Google云消息传递(GCM) - 一步一步的完整教程

在此输入图像描述

用于获取注册ID的代码段(用于推送通知的设备令牌).

为GCM配置项目


更新AndroidManifest文件

要在我们的项目中启用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" />
Run Code Online (Sandbox Code Playgroud)

在应用程序标记中添加GCM Broadcast Receiver声明:

<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/>
Run Code Online (Sandbox Code Playgroud)

添加GCM服务声明

<application
     <service android:name=".GcmIntentService" />
<application/>
Run Code Online (Sandbox Code Playgroud)

获取注册ID(推送通知的设备令牌)

现在转到您的启动/启动活动

添加常量和类变量

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;
Run Code Online (Sandbox Code Playgroud)

更新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);
}
Run Code Online (Sandbox Code Playgroud)

注意:请存储REGISTRATION_KEY,将PN消息发送到GCM非常重要.另请注意:此密钥对于所有设备都是唯一的,GCM将REGISTRATION_KEY仅发送推送通知.

  • 一旦你生成了REGISTRATION_KEY(可能是在你的手机上),你如何得到你的服务器? (3认同)

Spa*_*rky 5

回答您的第一个问题:是的,您必须运行服务器应用程序来发送消息,以及客户端应用程序来接收它们.

回答您的第二个问题:是的,每个应用程序都需要自己的API密钥.此密钥适用于您的服务器应用程序,而不是客户端.