regId在android gcm

时间:2015-04-22 10:30:52

标签: android google-cloud-messaging

您好,在下面的代码中我得到的regId显示为empty.but用户名和密码值工作正常。但我不明白为什么设备ID显示为空。

单击注册按钮后,

显示已向GCM注册。

public class MainActivity extends Activity {
    // label to display gcm messages
    TextView lblMessage;

    // Asyntask
    AsyncTask<Void, Void, Void> mRegisterTask;

    // Alert dialog manager
    AlertDialogManager alert = new AlertDialogManager();

    // Connection detector
    ConnectionDetector cd;

    public static String username;
    public static String password;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        cd = new ConnectionDetector(getApplicationContext());

        // Check if Internet present
        if (!cd.isConnectingToInternet()) {
            // Internet Connection is not present
            alert.showAlertDialog(MainActivity.this,
                    "Internet Connection Error",
                    "Please connect to working Internet connection", false);
            // stop executing code by return
            return;
        }

        // Getting name, email from intent
        Intent i = getIntent();

        username = i.getStringExtra("username");
        password = i.getStringExtra("password");        

        // Make sure the device has the proper dependencies.
        GCMRegistrar.checkDevice(this);

        // Make sure the manifest was properly set - comment out this line
        // while developing the app, then uncomment it when it's ready.
        GCMRegistrar.checkManifest(this);

        lblMessage = (TextView) findViewById(R.id.lblMessage);

        registerReceiver(mHandleMessageReceiver, new IntentFilter(
                DISPLAY_MESSAGE_ACTION));

        // Get GCM registration id
        final String regId = GCMRegistrar.getRegistrationId(this);

        // Check if regid already presents
        if (regId.equals("")) {
            // Registration is not present, register now with GCM           
            GCMRegistrar.register(this, SENDER_ID);
        } else {
            // Device is already registered on GCM
            if (GCMRegistrar.isRegisteredOnServer(this)) {
                // Skips registration.              
                Toast.makeText(getApplicationContext(), "Already registered with GCM", Toast.LENGTH_LONG).show();
            } else {
                // Try to register again, but not in the UI thread.
                // It's also necessary to cancel the thread onDestroy(),
                // hence the use of AsyncTask instead of a raw thread.
                final Context context = this;
                mRegisterTask = new AsyncTask<Void, Void, Void>() {

                    @Override
                    protected Void doInBackground(Void... params) {
                        // Register on our server
                        // On server creates a new user
                        ServerUtilities.register(context, username, password, regId);
                        return null;
                    }

                    @Override
                    protected void onPostExecute(Void result) {
                        mRegisterTask = null;
                    }

                };
                mRegisterTask.execute(null, null, null);
            }
        }
    }       

    /**
     * Receiving push messages
     * */
    private final BroadcastReceiver mHandleMessageReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String newMessage = 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(), "New Message: " + newMessage, Toast.LENGTH_LONG).show();

            // Releasing wake lock
            WakeLocker.release();
        }
    };

    @Override
    protected void onDestroy() {
        if (mRegisterTask != null) {
            mRegisterTask.cancel(true);
        }
        try {
            unregisterReceiver(mHandleMessageReceiver);
            GCMRegistrar.onDestroy(this);
        } catch (Exception e) {
            Log.e("UnRegister Receiver Error", "> " + e.getMessage());
        }
        super.onDestroy();
    }

}

logcat的

04-22 04:05:46.389: E/UnRegister Receiver Error(2355): > Receiver not registered: com.google.android.gcm.GCMBroadcastReceiver@4175aa98

2 个答案:

答案 0 :(得分:0)

使用与eclipse中应用程序名称相同的谷歌控制台创建一个新项目帮助我解决了这个问题。

答案 1 :(得分:0)

试试这个... Fisrt检查谷歌播放服务

  if (checkPlayServices()) {
        gcm = GoogleCloudMessaging.getInstance(this);
        mRegistrationId = getRegistrationId(mContext);

        if (mRegistrationId.isEmpty()) {
            try {
                registerInBackground(senderId);
            } catch (Exception e) {
                Toast.makeText(mContext, "Unsupported for this            device", Toast.LENGTH_SHORT).show();
            }
        } else {
            Log.d("TAG", mRegistrationId);
                        }
    } else {
        Log.i(TAG, "No valid Google Play Services found.");
    }

检查Google Play服务

  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.i(TAG, "This device is not supported.");
            Toast.makeText(mContext, "This device is not supported.", Toast.LENGTH_SHORT).show();
            finish();
        }
        return false;
    }
    return true;
}

获取RegistrationId就在这里

   private String getRegistrationId(Context context) {
    final SharedPreferences prefs = getGCMPreferences(context);
    String registrationId = prefs.getString(PROPERTY_REG_ID, "");
    assert registrationId != null;
    if (registrationId.isEmpty()) {
        //Log.i(TAG, "Registration not found.");
        return "";
    }

    int registeredVersion = prefs.getInt(PROPERTY_APP_VERSION, Integer.MIN_VALUE);
    int currentVersion = getAppVersion(context);
    if (registeredVersion != currentVersion) {
        Log.i(TAG, "App version changed.");
        return "";
    }
    return registrationId;
}

这里是registerInBackground Async Task

    private void registerInBackground(final String senderID) {

    new AsyncTask<Void, Void, String>() {

        @Override
        protected String doInBackground(Void... voids) {
            String msg = "";
            try {
                if (gcm == null) {
                    gcm = GoogleCloudMessaging.getInstance(mContext);
                }
                try {
                    mRegistrationId = gcm.register(senderID);
                } catch (UnsupportedOperationException e) {
                    Toast.makeText(mContext, "Unsupported", Toast.LENGTH_SHORT).show();
                }
                msg = "Device registered, registration ID=" + mRegistrationId;


            } catch (IOException ex) {
                msg = "Error :" + ex.getMessage();
            }
            return msg;
        }

        @Override
        protected void onPostExecute(String s) {
            Log.d(TAG, s);
        }

    }.execute(null, null, null);

}

这对我有用。希望它会对你有所帮助。