2016-05-14 5 views
0

説明: 私はGCMを使用してusers.Everythingに通知を送信しています。私はpush_messageの残りの部分を作成するサーバー側のプログラミングを作成し、すべてのことが行われます。GCM通知メッセージをAndroidのアクティビティに送信するにはどうすればよいですか?

通知をクリックすると、このメッセージが自分のアクティビティに表示されます。

自分のアクティビティでメッセージを開くにはどうすればよいですか?

はここで、アウト解決するために私を助けてください、私のGCMIntentService.java

package com.angelnx.angelnx.mygcm.gcm; 

import android.app.IntentService; 
import android.content.Intent; 

import android.content.SharedPreferences; 
import android.preference.PreferenceManager; 
import android.support.v4.content.LocalBroadcastManager; 
import android.util.Log; 
import android.widget.Toast; 


import com.angelnx.angelnx.mygcm.R; 
import com.angelnx.angelnx.mygcm.app.Config; 
import com.angelnx.angelnx.mygcm.app.EndPoints; 
import com.angelnx.angelnx.mygcm.app.MyApplication; 
import com.angelnx.angelnx.mygcm.model.User; 
import com.google.android.gms.gcm.GoogleCloudMessaging; 
import com.google.android.gms.iid.InstanceID; 
import com.android.volley.NetworkResponse; 
import com.android.volley.Request; 
import com.android.volley.Response; 
import com.android.volley.VolleyError; 
import com.android.volley.toolbox.StringRequest; 
import com.google.android.gms.gcm.GcmPubSub; 

import org.json.JSONException; 
import org.json.JSONObject; 

import java.io.IOException; 
import java.util.HashMap; 
import java.util.Map; 

public class GcmIntentService extends IntentService{ 

    private static final String TAG = GcmIntentService.class.getSimpleName(); 
    public GcmIntentService() { 
     super(TAG); 
    } 
    public static final String KEY = "key"; 
    public static final String TOPIC = "topic"; 
    public static final String SUBSCRIBE = "subscribe"; 
    public static final String UNSUBSCRIBE = "unsubscribe"; 

    @Override 
    protected void onHandleIntent(Intent intent) { 
     String key = intent.getStringExtra(KEY); 
     switch (key) { 
      case SUBSCRIBE: 
       // subscribe to a topic 
       String topic = intent.getStringExtra(TOPIC); 
       subscribeToTopic(topic); 
       break; 
      case UNSUBSCRIBE: 
       break; 
      default: 
       // if key is specified, register with GCM 
       registerGCM(); 
     } 

    } 
    private void registerGCM(){ 
     SharedPreferences sharedPreferences= PreferenceManager.getDefaultSharedPreferences(this); 

     try{ 
      InstanceID instanceID=InstanceID.getInstance(this); 
      String token=instanceID.getToken(getString(R.string.gcm_defaultSenderId), GoogleCloudMessaging.INSTANCE_ID_SCOPE,null); 
      Log.e(TAG,"GCM Registration Token:"+token); 

      sendRegistrationToServer(token); 
      sharedPreferences.edit().putBoolean(Config.SENT_TOKEN_TO_SERVER,true).apply(); 
     } 
     catch (Exception e){ 
      Log.e(TAG,"FAILED TO COMPLETED TASK"+e); 
      sharedPreferences.edit().putBoolean(Config.SENT_TOKEN_TO_SERVER,false).apply(); 
     } 
     //Notify UI that registration has completed, so the progress indicator can be hidden. 
     Intent registrationComplete = new Intent(Config.REGISTRATION_COMPLETE); 
     LocalBroadcastManager.getInstance(this).sendBroadcast(registrationComplete); 
    } 
    private void sendRegistrationToServer(final String token) { 

     User user= MyApplication.getInstance().getPrefManager().getUser(); 

     if(user==null){ 
      return; 
     } 
     String endPoint= EndPoints.USER.replace("_ID_",user.getId()); 
     Log.e(TAG,"endpoints :"+endPoint); 

     StringRequest strReq = new StringRequest(Request.Method.PUT, 
       endPoint, new Response.Listener<String>() { 

      @Override 
      public void onResponse(String response) { 
       Log.e(TAG, "response: " + response); 

       try { 
        JSONObject obj = new JSONObject(response); 

        // check for error 
        if (obj.getBoolean("error") == false) { 
         // broadcasting token sent to server 
         Intent registrationComplete = new Intent(Config.SENT_TOKEN_TO_SERVER); 
         LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(registrationComplete); 
        } else { 
         Toast.makeText(getApplicationContext(), "Unable to send gcm registration id to our sever. " + obj.getJSONObject("error").getString("message"), Toast.LENGTH_LONG).show(); 
        } 

       } catch (JSONException e) { 
        Log.e(TAG, "json parsing error: " + e.getMessage()); 
        Toast.makeText(getApplicationContext(), "Json parse error: " + e.getMessage(), Toast.LENGTH_SHORT).show(); 
       } 
      } 
     }, new Response.ErrorListener() { 

      @Override 
      public void onErrorResponse(VolleyError error) { 
       NetworkResponse networkResponse = error.networkResponse; 
       Log.e(TAG, "Volley error: " + error.getMessage() + ", code: " + networkResponse); 
       Toast.makeText(getApplicationContext(), "Volley error: " + error.getMessage(), Toast.LENGTH_SHORT).show(); 
      } 
     }) { 

      @Override 
      protected Map<String, String> getParams() { 
       Map<String, String> params = new HashMap<>(); 
       params.put("gcm_registration_id", token); 

       Log.e(TAG, "params: " + params.toString()); 
       return params; 
      } 
     }; 

     //Adding request to request queue 
     MyApplication.getInstance().addToRequestQueue(strReq); 

    } 
    /** 
    * Subscribe to a topic 
    */ 
    public static void subscribeToTopic(String topic) { 
     GcmPubSub pubSub = GcmPubSub.getInstance(MyApplication.getInstance().getApplicationContext()); 
     InstanceID instanceID = InstanceID.getInstance(MyApplication.getInstance().getApplicationContext()); 
     String token = null; 
     try { 
      token = instanceID.getToken(MyApplication.getInstance().getApplicationContext().getString(R.string.gcm_defaultSenderId), 
        GoogleCloudMessaging.INSTANCE_ID_SCOPE, null); 
      if (token != null) { 
       pubSub.subscribe(token, "/topics/" + topic, null); 
       Log.e(TAG, "Subscribed to topic: " + topic); 
      } else { 
       Log.e(TAG, "error: gcm registration id is null"); 
      } 
     } catch (IOException e) { 
      Log.e(TAG, "Topic subscribe error. Topic: " + topic + ", error: " + e.getMessage()); 
      Toast.makeText(MyApplication.getInstance().getApplicationContext(), "Topic subscribe error. Topic: " + topic + ", error: " + e.getMessage(), Toast.LENGTH_SHORT).show(); 
     } 
    } 

    public void unsubscribeFromTopic(String topic) { 
     GcmPubSub pubSub = GcmPubSub.getInstance(getApplicationContext()); 
     InstanceID instanceID = InstanceID.getInstance(getApplicationContext()); 
     String token = null; 
     try { 
      token = instanceID.getToken(getString(R.string.gcm_defaultSenderId), 
        GoogleCloudMessaging.INSTANCE_ID_SCOPE, null); 
      if (token != null) { 
       pubSub.unsubscribe(token, ""); 
       Log.e(TAG, "Unsubscribed from topic: " + topic); 
      } else { 
       Log.e(TAG, "error: gcm registration id is null"); 
      } 
     } catch (IOException e) { 
      Log.e(TAG, "Topic unsubscribe error. Topic: " + topic + ", error: " + e.getMessage()); 
      Toast.makeText(getApplicationContext(), "Topic subscribe error. Topic: " + topic + ", error: " + e.getMessage(), Toast.LENGTH_SHORT).show(); 
     } 
    } 
} 

です。

+0

を使用して活動にブロードキャストする必要があるメッセージを受信したとき、あなたはnotificaitonのクリックで所望の活性を開くようにしたいですか? –

+0

Localbroadcastレシーバーを使ってあなたのアクティビティに通知が来たときにあなたが通知すると思います。私は正しい? – Masum

+0

はい私は確信していないと思います。私はより安心してAndroidプラットフォームにいます。だから私は助けが必要です –

答えて

0

投稿したコードは、サーバー用のデバイスをGCMに登録するIntentServiceです。

あなたはGCMからメッセージを受信する必要があるコードをここにされています。基本的に、あなた自身のGcmListenerServiceを作成する必要が

https://github.com/googlesamples/google-services/blob/master/android/gcm/app/src/main/java/gcm/play/android/samples/com/gcmquickstart/MyGcmListenerService.java#L43-L69

すべてのサービスと受信者をAndroidManifest.xmlに入れることを忘れないでください。

<!-- [START gcm_receiver] --> 
    <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.RECEIVE" /> 
      <category android:name="your package" /> 
     </intent-filter> 
    </receiver> 
    <!-- [END gcm_receiver] --> 

    <!-- [START gcm_listener] --> 
    <service 
     android:name=".MyGcmListenerService" 
     android:exported="false" > 
     <intent-filter> 
      <action android:name="com.google.android.c2dm.intent.RECEIVE" /> 
     </intent-filter> 
    </service> 
    <!-- [END gcm_listener] --> 
    <!-- [START instanceId_listener] --> 
    <service 
     android:name=".MyInstanceIDListenerService" 
     android:exported="false"> 
     <intent-filter> 
      <action android:name="com.google.android.gms.iid.InstanceID"/> 
     </intent-filter> 
    </service> 
    <!-- [END instanceId_listener] --> 
    <service 
     android:name=".GcmIntentService" 
     android:exported="false"> 
    </service> 
+0

私はこのクラスをどこで使ったのですか? –

+0

私はこのクラスを使って自分のクラスを削除できますか? –

+0

@MilanGajera googleからこの例をチェック:https://github.com/googlesamples/google-services/tree/master/android/gcm – Mussa

0

GcmListenerServiceを実装するサービスを1つ作成するだけで済みます。

public class EMSListenerService extends GcmListenerService { 

    private static final String TAG = "ems_service"; 

    @Override 
    public void onMessageReceived(String from, Bundle data) { 
     super.onMessageReceived(from, data); 

     Display.log(TAG, "EMS received"); 

    } 
} 

そして、あなたはあなたがLocalBroadcastManager.getInstance(context).sendBroadcast(intent);

+0

私は理解できません。 –

関連する問題