2015-06-20 59 views
0

我已经在GitHub上下载了谷歌最新的GCM示例。Android GCM示例 - 如何在现有项目中实施?

它运作良好,但我不能让它在我自己的项目中工作。 我有甜甜圈转向和消息“生成InstanceID令牌...”

我不明白在他们的例子中与类GcmSender的链接。

这里是我的代码

 
    public class MainActivity extends ActionBarActivity { 

     private static final int PLAY_SERVICES_RESOLUTION_REQUEST = 9000; 
     private static final String TAG = "MainActivity"; 

     private BroadcastReceiver mRegistrationBroadcastReceiver; 
     private ProgressBar mRegistrationProgressBar; 
     private TextView mInformationTextView; 

     @Override 
     protected void onCreate(Bundle savedInstanceState) { 
      super.onCreate(savedInstanceState); 

      setContentView(R.layout.activity_main); 

      // url 
      String url="http://www.monurl.org/"; 
      WebView mWview=(WebView) this.findViewById(R.id.webView); 
      //autorise javascript 
      mWview.getSettings().setJavaScriptEnabled(true); 
      mWview.loadUrl(url); 

      //partie notif 

      mRegistrationProgressBar = (ProgressBar) findViewById(R.id.registrationProgressBar); 
      mRegistrationBroadcastReceiver = new BroadcastReceiver() { 
       @Override 
       public void onReceive(Context context, Intent intent) { 
        mRegistrationProgressBar.setVisibility(ProgressBar.GONE); 
        SharedPreferences sharedPreferences = 
          PreferenceManager.getDefaultSharedPreferences(context); 
        boolean sentToken = sharedPreferences 
          .getBoolean(QuickstartPreferences.SENT_TOKEN_TO_SERVER, false); 
        if (sentToken) { 
         mInformationTextView.setText(getString(R.string.gcm_send_message)); 
        } else { 
         mInformationTextView.setText(getString(R.string.token_error_message)); 
        } 
       } 
      }; 
      mInformationTextView = (TextView) findViewById(R.id.informationTextView); 


      // check si Google Play Services APK est sur le phone 
      if (checkPlayServices()) { 
       // Start IntentService to register this application with GCM. 
       Intent intent = new Intent(this, MyGcmRegistrationIntentService.class); 
       startService(intent); 
      } 

     } 

     @Override 
     public boolean onCreateOptionsMenu(Menu menu) { 
      // Inflate the menu; this adds items to the action bar if it is present. 
      getMenuInflater().inflate(R.menu.menu_main, menu); 
      return true; 
     } 

     @Override 
     public boolean onOptionsItemSelected(MenuItem item) { 
      // Handle action bar item clicks here. The action bar will 
      // automatically handle clicks on the Home/Up button, so long 
      // as you specify a parent activity in AndroidManifest.xml. 
      int id = item.getItemId(); 

      //noinspection SimplifiableIfStatement 
      if (id == R.id.action_settings) { 
       return true; 
      } 

      return super.onOptionsItemSelected(item); 
     } 



     /** 
     * Check the device to make sure it has the Google Play Services APK. If 
     * it doesn't, display a dialog that allows users to download the APK from 
     * the Google Play Store or enable it in the device's system settings. 
     */ 
     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, "Ce peripherique n'est pas supporte."); 
        finish(); 
       } 
       return false; 
      } 
      return true; 
     } 
    } 
 
    public class MyGcmListenerService extends GcmListenerService { 

     private static final String TAG = "MyGcmListenerService"; 
     public MyGcmListenerService() { 
     } 


     /** 
     * Called when message is received. 
     * 
     * @param from SenderID of the sender. 
     * @param data Data bundle containing message data as key/value pairs. 
     *    For Set of keys use data.keySet(). 
     */ 
     // [START receive_message] 
     @Override 
     public void onMessageReceived(String from, Bundle data) { 
      String message = data.getString("message"); 
      Log.d(TAG, "From: " + from); 
      Log.d(TAG, "Message: " + message); 

      /** 
      * Production applications would usually process the message here. 
      * Eg: - Syncing with server. 
      *  - Store message in local database. 
      *  - Update UI. 
      */ 

      /** 
      * In some cases it may be useful to show a notification indicating to the user 
      * that a message was received. 
      */ 
      sendNotification(message); 
     } 
     // [END receive_message] 



     /** 
     * Create and show a simple notification containing the received GCM message. 
     * 
     * @param message GCM message received. 
     */ 
     private void sendNotification(String message) { 
      Intent intent = new Intent(this, MainActivity.class); 
      intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
      PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent, 
        PendingIntent.FLAG_ONE_SHOT); 

      Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); 
      NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this) 
        .setSmallIcon(R.drawable.ic_stat_ic_notification) 
        .setContentTitle("GCM Message") 
        .setContentText(message) 
        .setAutoCancel(true) 
        .setSound(defaultSoundUri) 
        .setContentIntent(pendingIntent); 

      NotificationManager notificationManager = 
        (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); 

      notificationManager.notify(0 /* ID of notification */, notificationBuilder.build()); 

      Log.v("notification message",message); 
     } 
    } 
 
    public class MyGcmRegistrationIntentService extends IntentService { 


     private static final String TAG = "MyGcmRegistrationIntentService"; 
     private static final String[] TOPICS = {"global"}; 




     /** 
     * Starts this service to perform action Foo with the given parameters. If 
     * the service is already performing a task this action will be queued. 
     * 
     * @see IntentService 
     */ 
     // TODO: Customize helper method 
     public static void startActionFoo(Context context, String param1, String param2) { 
      Intent intent = new Intent(context, MyGcmRegistrationIntentService.class); 
      intent.setAction(ACTION_FOO); 
      intent.putExtra(EXTRA_PARAM1, param1); 
      intent.putExtra(EXTRA_PARAM2, param2); 
      context.startService(intent); 
     } 

     /** 
     * Starts this service to perform action Baz with the given parameters. If 
     * the service is already performing a task this action will be queued. 
     * 
     * @see IntentService 
     */ 
     // TODO: Customize helper method 
     public static void startActionBaz(Context context, String param1, String param2) { 
      Intent intent = new Intent(context, MyGcmRegistrationIntentService.class); 
      intent.setAction(ACTION_BAZ); 
      intent.putExtra(EXTRA_PARAM1, param1); 
      intent.putExtra(EXTRA_PARAM2, param2); 
      context.startService(intent); 
     } 

     public MyGcmRegistrationIntentService() { 
      // super("MyGcmRegistrationIntentService"); 
      // ajout 
      super(TAG); 
        //fin ajout 
     } 

     @Override 
     protected void onHandleIntent(Intent intent) { 


      SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this); 

      try { 
       // In the (unlikely) event that multiple refresh operations occur simultaneously, 
       // ensure that they are processed sequentially. 
       synchronized (TAG) { 
        // [START register_for_gcm] 
        // Initially this call goes out to the network to retrieve the token, subsequent calls 
        // are local. 
        // [START get_token] 
        InstanceID instanceID = InstanceID.getInstance(this); 
        String token = instanceID.getToken(getString(R.string.gcm_defaultSenderId), 
          GoogleCloudMessaging.INSTANCE_ID_SCOPE, null); 
        // [END get_token] 
        Log.i(TAG, "GCM Registration Token: " + token); 

        // TODO: Implement this method to send any registration to your app's servers. 
        sendRegistrationToServer(token); 

        // Subscribe to topic channels 
        subscribeTopics(token); 

        // You should store a boolean that indicates whether the generated token has been 
        // sent to your server. If the boolean is false, send the token to your server, 
        // otherwise your server should have already received the token. 
        sharedPreferences.edit().putBoolean(QuickstartPreferences.SENT_TOKEN_TO_SERVER, true).apply(); 
        // [END register_for_gcm] 
       } 
      } catch (Exception e) { 
       Log.d(TAG, "Failed to complete token refresh", e); 
       // If an exception happens while fetching the new token or updating our registration data 
       // on a third-party server, this ensures that we'll attempt the update at a later time. 
       sharedPreferences.edit().putBoolean(QuickstartPreferences.SENT_TOKEN_TO_SERVER, false).apply(); 
      } 
      // Notify UI that registration has completed, so the progress indicator can be hidden. 
      Intent registrationComplete = new Intent(QuickstartPreferences.REGISTRATION_COMPLETE); 
      LocalBroadcastManager.getInstance(this).sendBroadcast(registrationComplete); 


     } 

     /** 
     * Handle action Foo in the provided background thread with the provided 
     * parameters. 
     */ 
     private void handleActionFoo(String param1, String param2) { 
      // TODO: Handle action Foo 
      throw new UnsupportedOperationException("Not yet implemented"); 
     } 

     /** 
     * Handle action Baz in the provided background thread with the provided 
     * parameters. 
     */ 
     private void handleActionBaz(String param1, String param2) { 
      // TODO: Handle action Baz 
      throw new UnsupportedOperationException("Not yet implemented"); 
     } 


     private void subscribeTopics(String token) throws IOException { 
      for (String topic : TOPICS) { 
       GcmPubSub pubSub = GcmPubSub.getInstance(this); 
       pubSub.subscribe(token, "/topics/" + topic, null); 
      } 
     } 


     /** 
     * Persist registration to third-party servers. 
     * 
     * Modify this method to associate the user's GCM registration token with any server-side account 
     * maintained by your application. 
     * 
     * @param token The new token. 
     */ 
     private void sendRegistrationToServer(String token) { 
      // Add custom implementation, as needed. 
     } 

     private void sendTokenToServer(String token) { 


     } 


    } 

 

    public class MyInstanceIDListenerService extends InstanceIDListenerService { 
    public MyInstanceIDListenerService() { 
    } 

     @Override 
     public IBinder onBind(Intent intent) { 
       // TODO: Return the communication channel to the service. 
       throw new UnsupportedOperationException("Not yet implemented"); 
     } 

      // pour les notifs 
     @Override 
     public void onTokenRefresh() { 
       // Fetch updated Instance ID token and notify our app's server of any changes (if applicable). 
       Intent intent = new Intent(this, MyGcmRegistrationIntentService.class); 
       startService(intent); 
     } 
    } 

+0

忘了这能否请您提供一些源代码将示例集成到您的应用程序中? – alesc

回答

1

你好,我发现了什么事,我在主

 

     @Override 
     protected void onResume() { 
      super.onResume(); 
      LocalBroadcastManager.getInstance(this).registerReceiver(mRegistrationBroadcastReceiver, 
        new IntentFilter(QuickstartPreferences.REGISTRATION_COMPLETE)); 
     } 

     @Override 
     protected void onPause() { 
      LocalBroadcastManager.getInstance(this).unregisterReceiver(mRegistrationBroadcastReceiver); 
      super.onPause(); 
     }