以下代码未完整。但只包含可能有助于查找错误的相关代码部分。如果需要其他代码部分,请通知。
我的AndroidManifest.xml内容如下
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.priteshvikram.mywhatsapp"
android:versionCode="1"
android:versionName="1.0" xmlns:tools="http://schemas.android.com/tools">
<uses-sdk
android:minSdkVersion="9"
android:targetSdkVersion="16" tools:ignore="OldTargetApi"/>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="com.priteshvikram.mywhatsapp.permission.C2D_MESSAGE" />
<permission android:name="com.priteshvikram.mywhatsapp.permission.C2D_MESSAGE"
android:protectionLevel="signature" />
<uses-permission android:name="com.priteshvikram.mywhatsapp.permission.C2D_MESSAGE" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<meta-data android:name="com.google.android.gms.version"
android:value="4323030" />
<activity
android:name="com.priteshvikram.mywhatsapp.Login"
android:label="@string/title_activity_login"
android:windowSoftInputMode="adjustResize|stateVisible" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="com.priteshvikram.mywhatsapp.Home"
android:configChanges="orientation|keyboardHidden|screenSize"
android:label="@string/app_name"
android:theme="@style/FullscreenTheme" >
</activity>
<activity
android:name="com.priteshvikram.mywhatsapp.ListItemDetails"
android:configChanges="orientation|keyboardHidden|screenSize"
android:label="@string/Details"
android:theme="@style/FullscreenTheme" >
</activity>
<activity
android:name="com.priteshvikram.mywhatsapp.Chat"
android:label="@string/title_activity_chat_window"
android:theme="@style/FullscreenTheme" >
</activity>
<receiver
android:name=".BroadcastReceiver"
android:permission="com.google.android.c2dm.permission.SEND" >
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<action android:name="com.google.android.c2dm.intent.REGISTRATION" />
<action android:name="com.google.android.gcm.intent.RETRY" />
<category android:name="com.priteshvikram.mywhatsapp" />
</intent-filter>
</receiver>
<service android:name=".GcmIntentService" />
</application>
</manifest>
我的Login.java文件如下
package com.priteshvikram.mywhatsapp;
public class Login extends Activity {
String SENDER_ID = "XXXXXXXXXXXX";
...
GoogleCloudMessaging gcm;
SharedPreferences prefs;
String regid;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
context = getApplicationContext();
gcm = GoogleCloudMessaging.getInstance(this);
regid = getRegistrationId(context);
if (regid.isEmpty()) {
registerInBackground();
Log.d("empty"," executing");
}
}
private String getRegistrationId(Context context) {
final SharedPreferences prefs = getGCMPreferences(context);
String registrationId = prefs.getString(PROPERTY_REG_ID, "");
if (registrationId.isEmpty()) {
Log.i("gcm", "Registration not found.");
return "";
}
// Check if app was updated; if so, it must clear the registration ID
// since the existing regID is not guaranteed to work with the new
// app version.
int registeredVersion = prefs.getInt(PROPERTY_APP_VERSION, Integer.MIN_VALUE);
int currentVersion = getAppVersion(context);
if (registeredVersion != currentVersion) {
Log.i("gcm", "App version changed.");
return "";
}
return registrationId;
}
private void registerInBackground() {
Log.d("registerinbackground"," executing");
new AsyncTask() {
@Override
protected String doInBackground(Object... params) {
String msg = "";
//try {
if (gcm == null) {
Log.d("async task"," executing");
gcm = GoogleCloudMessaging.getInstance(context);
}
//regid = gcm.register(SENDER_ID);
GCMRegistrar.register(context, SENDER_ID);
regid = GCMRegistrar.getRegistrationId(context);
//regid="1";
//Toast.makeText(getApplicationContext(), "User Registered", Toast.LENGTH_SHORT).show();
msg = "Device registered, registration ID=" + regid;
Log.d("regid","executing");
// You should send the registration ID to your server over HTTP,
// so it can use GCM/HTTP or CCS to send messages to your app.
// The request to your server should be authenticated if your app
// is using accounts.
sendRegistrationIdToBackend();
// For this demo: we don't need to send it because the device
// will send upstream messages to a server that echo back the
// message using the 'from' address in the message.
// Persist the regID - no need to register again.
storeRegistrationId(context, regid);
//} catch (IOException ex) {
//msg = "Error :" + ex.getMessage();
// If there is an error, don't just keep trying to register.
// Require the user to click a button again, or perform
// exponential back-off.
Log.d("error",msg);
//Toast.makeText(getApplicationContext(), "Unable to register", Toast.LENGTH_SHORT).show();
//}
return msg;
}
}.execute();
}
private void sendRegistrationIdToBackend() {
new SendRegId().execute();
}
private void storeRegistrationId(Context context, String regId) {
final SharedPreferences prefs = getGCMPreferences(context);
int appVersion = getAppVersion(context);
Log.i("gcs", "Saving regId on app version " + appVersion);
SharedPreferences.Editor editor = prefs.edit();
editor.putString(PROPERTY_REG_ID, regId);
editor.putInt(PROPERTY_APP_VERSION, appVersion);
editor.commit();
}
public class SendRegId extends AsyncTask<Void, Void, Boolean> {
@Override
protected Boolean doInBackground(Void... params) {
try {
return downloadUrl(regid);
} catch (IOException e) {
return false;
}
}
private Boolean downloadUrl(String reg) throws IOException {
final String DEBUG_TAG = "XMLData";
InputStream is = null;
// Only display the first 500 characters of the retrieved
// web page content.
int len = 500;
String urlParameters="regid="+reg+"&email="+mEmail;
try {
URL url = new URL("https://priteshvikram-dawud.rhcloud.com/gcm_reg_store.php");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setInstanceFollowRedirects(false);
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("charset", "utf-8");
conn.setRequestProperty("Content-Length", "" + Integer.toString(urlParameters.getBytes().length));
conn.setUseCaches (false);
// Starts the query
DataOutputStream wr = new DataOutputStream(conn.getOutputStream ());
wr.writeBytes(urlParameters);
wr.flush();
int response = conn.getResponseCode();
Log.d(DEBUG_TAG, "gcm_reg_store.php response is: " + response);
is = conn.getInputStream();
// Convert the InputStream into a string
String contentAsString = readIt(is, len).replaceFirst("\\s+$", "");
//Integer.parseInt(contentAsString);
Log.d("data",contentAsString);
return true;
// Makes sure that the InputStream is closed after the app is
// finished using it.
} finally {
if (is != null) {
is.close();
}
}
}
public String readIt(InputStream stream, int len) throws IOException, UnsupportedEncodingException {
BufferedReader reader = null;
reader = new BufferedReader(new InputStreamReader(stream, "UTF-8"));
String buffer;
buffer = reader.readLine();
return buffer;
}
@Override
protected void onPostExecute(final Boolean success) {
}
}
答案 0 :(得分:1)
您正在将旧的注册方式与新的注册方式混合在一起。以新的方式,您根本不使用GCMRegistrar
(该类已被弃用)。你拨打gcm.register(SENDER_ID)
。
private void registerInBackground() {
Log.d("registerinbackground"," executing");
new AsyncTask() {
@Override
protected String doInBackground(Object... params) {
String msg = "";
//try {
if (gcm == null) {
Log.d("async task"," executing");
gcm = GoogleCloudMessaging.getInstance(context);
}
regid = gcm.register(SENDER_ID);
GCMRegistrar
异步注册,这就是GCMRegistrar.getRegistrationId(context)
返回null的原因。后台运行registerInBackground()
的重点是调用阻塞注册方法,该方法返回注册ID(这是gcm.register(SENDER_ID)
所做的)。