2015-10-25 36 views
0

我試圖將我的設備註冊到GCM服務中。 這是工作,我得到我的設備的註冊ID並將其存儲在我的服務器上。 但是當我向我的設備發送消息沒有任何影響,設備無法收回消息。在發送消息的谷歌爲什麼沒有收到來自gcm的郵件

響應:

{u'failure': 0, u'canonical_ids': 0, u'success': 1, u'multicast_id': 8319562714448073760L, u'results': [{u'message_id': u'0:1445751667241995%f044e3acf9fd7ecd'}]} 

Android清單:

<?xml version="1.0" encoding="utf-8"?> 
<manifest xmlns:android="http://schemas.android.com/apk/res/android" 
     package="ir.ac.buqaen.rc" 
     android:versionCode="5" 
     android:versionName="1.4"> 

<uses-sdk 
     android:minSdkVersion="8" 
     android:targetSdkVersion="23"/> 

<uses-permission android:name="android.permission.INTERNET" /> 
<uses-permission android:name="android.permission.WAKE_LOCK" /> 
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> 
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> 
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> 
<uses-permission android:name="android.permission.GET_ACCOUNTS" /> 
<uses-permission android:name="android.permission.VIBRATE"/> 

<permission 
     android:name="ir.ac.buqaen.rc.permission.C2D_MESSAGE" 
     android:protectionLevel="signature" /> 

<uses-permission android:name="ir.ac.buqaen.rc.permission.C2D_MESSAGE" /> 
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" /> 

<application 
     android:name=".network.AppController" 
     android:label="@string/app_name" 
     android:icon="@drawable/icon" 
     android:theme="@style/Theme.Main" 
     android:allowBackup="true"> 

    <activity 
      android:name=".MainActivity" 
      android:launchMode="singleTop" 
      android:configChanges="keyboardHidden|orientation|screenSize"/> 

    <activity 
      android:name=".SplashActivity" 
      android:label="@string/app_name" 
      android:theme="@style/Theme.AppCompat.Light.NoActionBar.FullScreen"> 
     <intent-filter> 
      <action android:name="android.intent.action.MAIN"/> 
      <category android:name="android.intent.category.LAUNCHER"/> 
     </intent-filter> 
    </activity> 

    <activity android:name=".gcm.MessageActivity"/> 

    <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="ir.ac.buqaen.rc" /> 
     </intent-filter> 
    </receiver> 

    <service android:name=".GCMIntentService" /> 

</application> 
</manifest> 

ServerUtilities.java

public final class ServerUtilities { 
    private static final String TAG = "GCM"; 

    public static void register(final Context context, final String regId){ 
     final MySharedPreferences sp = new MySharedPreferences(context); 
     long teacher_id = sp.sharedPreferences.getLong("teacher_id", -1); 
     TeacherHelper teacherHelper = new TeacherHelper(context); 
     teacherHelper.teacher = teacherHelper.findById(teacher_id); 

     Map<String, String> params = new HashMap<String, String>(); 
     Log.d("regid", "---- regId:" + regId); 
     params.put("reg_id", regId); 
     params.put("name", teacherHelper.teacher.getStringName()); 
     params.put("email", teacherHelper.teacher.getStringEmail()); 
     params.put("user_id", teacherHelper.teacher.getStringUsername()); 
     params.put("device_id", Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID)); 
     CustomRequest request = new CustomRequest(context, Globals.UrlGCMRegister, params, new CustomRequest.ResponseAction() { 
      @Override 
      public void onResponseAction(JSONObject data) throws JSONException { 
       try { 
        int vc = context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionCode; 
        if (data.getBoolean("status")) { 
         sp.saveToPreferences("gcm" + vc, data.getJSONObject("value").getString("id")); 
         sp.saveToPreferences("gcm_reg_id", regId); 
         GCMRegistrar.setRegisteredOnServer(context, true); 
        } else if (data.getString("msg").equals("already registered")) { 
         sp.saveToPreferences("gcm" + vc, data.getJSONObject("value").getString("id")); 
         GCMRegistrar.setRegisteredOnServer(context, true); 
         sp.saveToPreferences("gcm_reg_id", regId); 
        } else { 
         Log.e(TAG, "registering device failed"); 
        } 
       } catch (JSONException e) { 
        Log.e("Response Error _ " + context.getClass().getSimpleName(), "----" + e.getMessage()); 
       } catch (PackageManager.NameNotFoundException e) { 
        e.printStackTrace(); 
       } 
      } 
     }); 
     AppController.getInstance().addToRequestQueue(request, "request gcm"); 
    } 

    /** 
    * Unregister this account/device pair within the server. 
    */ 
    public static void unregister(final Context context, final String regId) { 
     final MySharedPreferences sp = new MySharedPreferences(context); 

     Map<String, String> params = new HashMap<String, String>(); 
     params.put("reg_id", regId); 
     CustomRequest request = new CustomRequest(context, Globals.UrlGCMUnRegister, params, new CustomRequest.ResponseAction() { 
      @Override 
      public void onResponseAction(JSONObject data) throws JSONException { 
       if (data.getBoolean("status")) { 
        int vc = 1; 
        try { 
         vc = context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionCode; 
        } catch (PackageManager.NameNotFoundException e) { 
         e.printStackTrace(); 
        } 
        sp.editor.remove("gcm" + vc); 
        sp.editor.remove("gcm_reg_id"); 
        sp.editor.commit(); 
        GCMRegistrar.setRegisteredOnServer(context, false); 
       } 
      } 
     }); 
     AppController.getInstance().addToRequestQueue(request, "request gcm"); 
    } 
} 

GCMInten tService.java

public class GCMIntentService extends GCMBaseIntentService { 

    private static final String TAG = "GCMIntentService"; 

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

    @Override 
    protected void onRegistered(Context context, String registrationId) { 
     ServerUtilities.register(context, registrationId); 
    } 

    @Override 
    protected void onUnregistered(Context context, String registrationId) { 
     ServerUtilities.unregister(context, registrationId); 
    } 

    @Override 
    protected void onMessage(Context context, Intent intent) { 
     Log.i("tes", "~~~" + intent.getExtras()); 
     Log.i(TAG, "Received message"); 
     MessageHelper messageHelper = new MessageHelper(context); 
     try { 
      JSONObject data = new JSONObject(intent.getExtras().getString("message")); 
      messageHelper.message = new Message(
        null, data.getInt("type"), data.getInt("status"), data.getString("content"), 
        data.getString("title"), data.getString("date") 
      ); 
      messageHelper.Save(); 

      createNotification(context, messageHelper.message); 
     } catch (JSONException e) { 
      e.printStackTrace(); 
     } 
    } 

    @Override 
    public void onError(Context context, String errorId) { 
     Log.i(TAG, "Received error: " + errorId); 
    } 

    @Override 
    protected boolean onRecoverableError(Context context, String errorId) { 
     Log.i(TAG, "Received recoverable error: " + errorId); 
     return super.onRecoverableError(context, errorId); 
    } 

    private void createNotification(Context context, Message message) { 
     Intent notificationIntent; 
     notificationIntent = new Intent(this, Message.class); 

     NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); 
     notificationIntent.putExtra("message_id", message.id); 
     notificationIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
     PendingIntent contentIntent = PendingIntent.getActivity(this, message.id.intValue(), notificationIntent, PendingIntent.FLAG_ONE_SHOT); 

     NotificationCompat.Builder builder = new NotificationCompat.Builder(this); 
     builder.setContentIntent(contentIntent) 
       .setSmallIcon(R.drawable.bu_logo) 
       .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.bu_logo)) 
       .setTicker(getString(R.string.new_message)) 
       .setWhen(System.currentTimeMillis()) 
       .setAutoCancel(true) 
       .setSound(Uri.parse("android.resource://ir.ac.buqaen.rc/raw/notification")) 
       .setContentTitle(message.title) 
       .setContentText(message.getContentText(context)); 
     Notification notification = builder.build(); 

     notificationManager.notify(message.id.intValue(), notification); 
    } 
} 

MainActivity

  try { 

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

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

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

       // Check if regid already presents 
       if (regId.equals("")) { 
        // Registration is not present, register now with GCM 
        GCMRegistrar.register(getApplicationContext(), Globals.SENDER_ID); 
       } else { 
        // Try to register again if device is not registered on GCM 
        if (!GCMRegistrar.isRegisteredOnServer(getApplicationContext())) { 
         ServerUtilities.register(getApplicationContext(), regId); 
        } 
       } 
      } catch (Exception e) { 
       e.printStackTrace(); 
      } 

我不KHOW爲什麼這個代碼不工作!我在另一個項目中使用此代碼,並在我的應用程序上獲取消息,但此應用程序中的代碼接收消息。

從我的包名稱可以問題? :)

ir.ac.buqaen.rc 

請幫我鋤頭解決這個問題。

+0

GcmBaseIntentService已被棄用。我建議看看GcmListenerService和InstanceID。 https://developers.google.com/cloud-messaging/android/start –

回答

0

根據Set up a GCM Client App on Android

對於延長WakefulBroadcastReceiver現有的應用程序,谷歌 建議遷移到GCMReceiverGcmListenerService。要 遷移:

  • 在應用清單,以「com.google.android.gms.gcm.GcmReceiver」取代你GcmBroadcastReceiver,並更換擴展IntentService到當前
    服務聲明新
    GcmListenerService
  • 從客戶端代碼中刪除廣播接收器實施
  • 重構當前IntentService服務實現使用GcmListenerService

然後,你可以參考我下面的清單文件。希望這可以幫助!

<?xml version="1.0" encoding="utf-8"?> 
<manifest xmlns:android="http://schemas.android.com/apk/res/android" 
    package="com.example.gcmclient" > 

<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="com.google.android.c2dm.permission.RECEIVE" /> 

<permission android:name="com.example.gcm.permission.C2D_MESSAGE" 
    android:protectionLevel="signature" /> 
<uses-permission android:name="com.example.gcm.permission.C2D_MESSAGE" /> 


<application 
    android:allowBackup="true" 
    android:icon="@mipmap/ic_launcher" 
    android:label="@string/app_name" 
    android:theme="@style/AppTheme" > 
    <receiver 
     android:name="com.google.android.gms.gcm.GcmReceiver" 
     android:exported="true" 
     android:permission="com.google.android.c2dm.permission.SEND" > 
     <intent-filter> 
      <action android:name="com.google.android.c2dm.intent.REGISTRATION" /> 
      <action android:name="com.google.android.c2dm.intent.RECEIVE" /> 
      <category android:name="com.example.gcm" /> 
     </intent-filter> 
    </receiver> 
    <service android:name=".service.GcmService" android:exported="false"> 
     <intent-filter> 
      <action android:name="com.google.android.c2dm.intent.RECEIVE" /> 
     </intent-filter> 
    </service> 

    <service android:name=".service.LoggingService" android:exported="false" /> 

    <activity 
     android:name=".MainActivity" 
     android:label="@string/app_name" 
     android:clearTaskOnLaunch="false" 
     android:finishOnTaskLaunch="true"> 
     <intent-filter> 
      <action android:name="android.intent.action.MAIN" /> 

      <category android:name="android.intent.category.LAUNCHER" /> 
     </intent-filter> 
    </activity> 
</application> 

</manifest> 
+0

這種方式minSdkVersion必須9,但要寫我的應用程序Sdk 8 – Zaaferani

+0

如果是這樣,請閱讀下面,看看它是否可以幫助http: //stackoverflow.com/questions/17618982/gcm-service-not-available-on-android-2-2 – BNK

相關問題