0

我正在使用 GCM 实现推送通知,但我没有获得注册 ID。我用了这个例子

我尝试创建一个演示示例,但我得到了相同的结果,没有得到注册 ID。

 - SplashActivity (package com.wae.saterra.view;)

    final SharedPreferences prefs = this.getSharedPreferences(PREFERENCE,
                    Context.MODE_PRIVATE);
    Editor edit = prefs.edit();

    checkNotNull(SENDER_ID, "SENDER_ID");

    GCMRegistrar.checkDevice(this);
    GCMRegistrar.checkManifest(this);

    if (GCMRegistrar.isRegistered(this)) {
        Log.d("info", GCMRegistrar.getRegistrationId(this));
    }

    final String regId = GCMRegistrar.getRegistrationId(this);
    Log.v("Register ID", "Register ID ==========" + regId);

    if (regId != null && regId != "") {
        edit.putString(PREFERENCE, regId);
        edit.commit();
    }

    deviceToken = prefs.getString(PREFERENCE, "");
    Log.i("DeviceToken", "DeviceToken =====  " + deviceToken);
    deviceUDID = Secure.getString(this.getContentResolver(),
            Secure.ANDROID_ID);

    if (regId.equals("")) {
        GCMRegistrar.register(this, SENDER_ID);
        Log.d("info", GCMRegistrar.getRegistrationId(this));
    } else {
        Log.v("Saterra Push NOTIFICATION", "Already registered");
    }

    try {
        appName = this.getString(this.getPackageManager().getPackageInfo(
                this.getPackageName(), 0).applicationInfo.labelRes);

    } catch (NameNotFoundException e) {
        appName = this.getString(R.string.app_name);
        e.printStackTrace();
    }
    try {
        appVersion = this.getPackageManager().getPackageInfo(
                this.getPackageName(), 0).versionName;
    } catch (NameNotFoundException e) {
        appVersion = this.getString(R.string.version_name);
        e.printStackTrace();
    }
    deviceVersion = Build.VERSION.RELEASE;
    deviceModel = Build.MODEL;
    deviceName = Build.MANUFACTURER;

    if (Global.isNetworkAvailable(this)) {
        new GCMAsyncTask().execute(Constants.GCM_URL);
    }

GCM:GCMIntentService 类(包 com.wae.saterra;)

    public class GCMIntentService extends GCMBaseIntentService {

    private static final String TAG = "GCMIntentService";

    public GCMIntentService() {
        super(CommonUtilities.SENDER_ID);
    }

    /**
     * Method called on device registered
     **/
    @Override
    public void onRegistered(Context context, String registrationId) {
        Log.i(TAG, "Device registered: regId = " + registrationId);

//       Intent intent = new Intent(Constants.ACTION_ON_REGISTERED);
//          intent.putExtra(Constants.FIELD_REGISTRATION_ID, registrationId);
//          context.sendBroadcast(intent);

        // CommonUtilities.displayMessage(context,
        // "Your device registred with GCM");
        // --- Log.d("NAME", MainActivity.name);
        // ServerUtilities.register(context, MainActivity.name,
        // MainActivity.email, registrationId);
    }

    /**
     * Method called on device un registred
     * */
    @Override
    protected void onUnregistered(Context context, String registrationId) {
        Log.i(TAG, "Device unregistered");
        // CommonUtilities.displayMessage(context,
        // getString(R.string.gcm_unregistered));
        // ServerUtilities.unregister(context, registrationId);
    }

    /**
     * Method called on Receiving a new message
     * */
    @Override
    protected void onMessage(Context context, Intent intent) {
         Resources res = getResources();
        Log.i(TAG, "Received message");
        generateNotification(this,res.getString(R.string.hello_world, "arg1", "arg2"));
        // String message = intent.getExtras().getString("price");
        //
        // CommonUtilities.displayMessage(context, message);
        // // notifies user
        // generateNotification(context, message);
    }

    /**
     * Method called on receiving a deleted message
     * */
    @Override
    protected void onDeletedMessages(Context context, int total) {
        Log.i(TAG, "Received deleted messages notification");
        String message = getString(R.string.gcm_deleted, total);
        // CommonUtilities.displayMessage(context, message);
        // // notifies user
        // generateNotification(context, message);
    }

    /**
     * Method called on Error
     * */
    @Override
    public void onError(Context context, String errorId) {
        Log.i(TAG, "Received error: " + errorId);
        // CommonUtilities.displayMessage(context, getString(R.string.gcm_error,
        // errorId));
    }

    @Override
    protected boolean onRecoverableError(Context context, String errorId) {
        // log message
        Log.i(TAG, "Received recoverable error: " + errorId);
        // CommonUtilities.displayMessage(context,
        // getString(R.string.gcm_recoverable_error,
        // errorId));
        return super.onRecoverableError(context, errorId);
    }

    /**
     * Issues a notification to inform the user that server has sent a message.
     */
    private static void generateNotification(Context context, String message) {
        int icon = R.drawable.ic_launcher;



    }

}
- Menifest give all the required permission are below


 <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.GET_ACCOUNTS" />
    <uses-permission android:name="android.permission.VIBRATE" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />
     <permission
        android:name="com.wae.saterra.permission.C2D_MESSAGE"
        android:protectionLevel="signature" />

    <uses-permission android:name="com.wae.saterra.permission.C2D_MESSAGE" />
    <!-- This app has permission to register and receive data message. -->
    <uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />

 - in application tag

     <receiver
                android:name="com.google.android.gcm.GCMBroadcastReceiver"
                android:permission="com.google.android.c2dm.permission.SEND" >
                <intent-filter>

                    <!-- Receives the actual messages. -->
                    <action android:name="com.google.android.c2dm.intent.RECEIVE" />
                    <!-- Receives the registration id. -->
                    <action android:name="com.google.android.c2dm.intent.REGISTRATION" />

                    <category android:name="com.wae.saterra" />
                </intent-filter>
            </receiver>

            <service android:name=".GCMIntentService" />
  • 我正在使用 GCM 实现推送通知,但我没有获得注册 ID。我用了这个例子。``
4

1 回答 1

0

你可以从这里下载演示

像这样的 GCMIntentService

import static com.androidhive.pushnotifications.CommonUtilities.SENDER_ID;
import static com.androidhive.pushnotifications.CommonUtilities.displayMessage;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

import com.google.android.gcm.GCMBaseIntentService;

public class GCMIntentService extends GCMBaseIntentService {

    private static final String TAG = "GCMIntentService";

    public GCMIntentService() {
        super(SENDER_ID);
    }
    /**
     * Method called on device registered
     **/
    @Override
    protected void onRegistered(Context context, String registrationId) {
        Log.i(TAG, "Device registered: regId = " + registrationId);
        displayMessage(context, "Your device registred with GCM");
        Log.d("NAME", MainActivity.name);
        ServerUtilities.register(context, MainActivity.name, MainActivity.email, registrationId);
    }

    /**
     * Method called on device un registred
     * */
    @Override
    protected void onUnregistered(Context context, String registrationId) {
        Log.i(TAG, "Device unregistered");
        displayMessage(context, getString(R.string.gcm_unregistered));
        ServerUtilities.unregister(context, registrationId);
    }

    /**
     * Method called on Receiving a new message
     * */
    @Override
    protected void onMessage(Context context, Intent intent) {
        Log.i(TAG, "Received message");
        String message = intent.getExtras().getString("message");
        displayMessage(context, message);
        // notifies user
        generateNotification(context, message);
    }

    /**
     * Method called on receiving a deleted message
     * */
    @Override
    protected void onDeletedMessages(Context context, int total) {
        Log.i(TAG, "Received deleted messages notification");
        String message = getString(R.string.gcm_deleted, total);
        displayMessage(context, message);
        // notifies user
        generateNotification(context, message);
    }

    /**
     * Method called on Error
     * */
    @Override
    public void onError(Context context, String errorId) {
        Log.i(TAG, "Received error: " + errorId);
        displayMessage(context, getString(R.string.gcm_error, errorId));
    }

    @Override
    protected boolean onRecoverableError(Context context, String errorId) {
        // log message
        Log.i(TAG, "Received recoverable error: " + errorId);
        displayMessage(context, getString(R.string.gcm_recoverable_error,errorId));
        return super.onRecoverableError(context, errorId);
    }
    /**
     * Issues a notification to inform the user that server has sent a message.
     */
    private static void generateNotification(Context context, String message) {
        int icon = R.drawable.ic_launcher;
        long when = System.currentTimeMillis();
        NotificationManager notificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
        Notification notification = new Notification(icon, message, when);

        String title = context.getString(R.string.app_name);        
        Intent notificationIntent = new Intent(context, MainActivity.class);
        // set intent so it does not start a new activity
        notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|Intent.FLAG_ACTIVITY_SINGLE_TOP);
        PendingIntent intent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
        notification.setLatestEventInfo(context, title, message, intent);
        notification.flags |= Notification.FLAG_AUTO_CANCEL;        
        // Play default notification sound
        notification.defaults |= Notification.DEFAULT_SOUND;        
        //notification.sound = Uri.parse("android.resource://" + context.getPackageName() + "your_sound_file_name.mp3");        
        // Vibrate if vibrate is enabled
        notification.defaults |= Notification.DEFAULT_VIBRATE;
        notificationManager.notify(0, notification);      

    }

在 MainActivity 你可以得到注册 ID 并且需要注册和注销 BroadcastReceiver

private final BroadcastReceiver mHandleMessageReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String regid = intent.getExtras().getString(EXTRA_MESSAGE);
            // Waking up mobile if it is sleeping
            WakeLocker.acquire(getApplicationContext());

            /**
             * Take appropriate action on this message
             * depending upon your app requirement
             * For now i am just displaying it on the screen
             * */

            // Showing received message
            lblMessage.append(newMessage + "\n");           
            Toast.makeText(getApplicationContext(), "Reg ID: " + regid, Toast.LENGTH_LONG).show();
            // Releasing wake lock
            WakeLocker.release();
        }
    };

有关更多信息,请参阅给定的 url

于 2013-05-18T05:28:19.530 回答