2014-05-20 2 views
1

다음 코드는 완전하지 않습니다. 그러나 오류 발견에 도움이되는 관련 코드 섹션 만 포함합니다. 추가 코드 섹션이 필요한지 알려주십시오.GCMRegister를 사용하여 등록 ID를 얻을 수 없습니다.

나는 다음과 같이 내 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> 

당신은 등록의 새로운 방법으로 등록 옛날 방식을 혼합하는

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

아이디를 얻기 위해 [이 코드] (http://stackoverflow.com/questions/22533952/getting-null-device-id-while-registering-to-gcm/22534888#22534888)를 시도하십시오 ... – Dev

답변

1

를 다음과 같이 내 Login.java 파일입니다. 새로운 방식에서는 GCMRegistrar을 전혀 사용하지 않습니다 (이 클래스는 사용되지 않습니다). gcm.register(SENDER_ID)으로 전화하십시오. GCMRegistrar.getRegistrationId(context) 반환 널 (null) 왜

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 레지스터 비동기 적으로, 그입니다. 백그라운드에서 registerInBackground()을 실행하는 요점은 등록 ID (즉, gcm.register(SENDER_ID))를 반환하는 차단 등록 메소드를 호출하는 것입니다.

관련 문제