如何在android中使用GCM获取RegistrationID

时间:2012-07-17 05:58:27

标签: 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”是否有必要在我每次创建时都这样做新项目
  3. 任何人都可以为我提供除谷歌提供的正确项目,以便我清除我的概念。

    任何帮助将不胜感激。

3 个答案:

答案 0 :(得分:21)

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

  1. 在Google Cloud上创建/注册应用
  2. 使用开发设置Cloud SDK
  3. 为GCM配置项目
  4. 获取设备注册ID
  5. 发送推送通知
  6. 接收推送通知
  7. 您可以在此处找到完整的教程:

      

    Getting Started with Android Push Notification : Latest Google Cloud Messaging (GCM) - step by step complete tutorial

    enter image description here

    获取注册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" />
    

    在应用程序标记中添加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/>
    

    添加GCM服务声明

    <application
         <service android:name=".GcmIntentService" />
    <application/>
    

    获取注册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;
    

    更新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);
    }
    

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

答案 1 :(得分:5)

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

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

答案 2 :(得分:4)

使用此代码使用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);
 }

并且不要忘记在清单中写权限...
我希望它有所帮助!