将GCM推送通知纳入我的应用

时间:2016-03-29 09:50:16

标签: android google-cloud-messaging

我想在分配任务时向用户发送通知(即点击按钮)。当一个任务被分配给用户时,我改变了我服务器中的一些值(即我执行post方法)我想知道如何实现这一点。 我登录到我的应用程序&我将用户令牌ID存储到我的服务器中我也经历了谷歌开发人员指南并注册了我的应用程序并获得了senderid和serverapikey。我会将代码发布到我到达的地方,请帮助我进一步了解。

LoginActivity

 private void checkUserRegistrationToken() {
    String url = URLMap.getGcmtokenUrl("gcmtoken_url");
    employeeId = LoggedInUserStore.getLoggedInEmployeeId(getApplicationContext());
    companyId = LoggedInUserStore.getLoggedInCompanyId(getApplicationContext());
    url = url.replace("{eid}", employeeId).replace("{cid}", companyId);
    final StringRequest request = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            try {
                    JSONObject jObj = new JSONObject(response);
                tokenId = jObj.getString("TokenId");
                if (tokenId.equals("null")) {
                    registerInBackground();
                }
            } catch (JSONException e) {

            }
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            System.out.println("Error===" + error.toString());
        }
    });
    request.setRetryPolicy(new VolleyRetryPolicy().getRetryPolicy());
    RequestQueue queue = ((VolleyRequestQueue) getApplication()).getRequestQueue();
    queue.add(request);
}

private void registerInBackground() {
    new AsyncTask<Void, Void, String>() {
        @Override
        protected String doInBackground(Void... params) {
            String msg = "";
            try {
                if (gcmObj == null) {
                    gcmObj = GoogleCloudMessaging.getInstance(LoginActivity.this);
                }
                tokenId = gcmObj.register(String.valueOf(R.string.gcm_defaultSenderId));
                msg = "Registration ID:" + tokenId;
                if (new ServiceManager(getApplicationContext()).isNetworkAvailable() && checkPlayServices()) {
                    String storeUrl = URLMap.getGcmtokenPostUrl();
                    employeeId = LoggedInUserStore.getLoggedInEmployeeId(getApplicationContext());
                    companyId = LoggedInUserStore.getLoggedInCompanyId(getApplicationContext());
                    HashMap<String, String> map = new HashMap<String, String>();
                    map.put("EmployeeId", employeeId);
                    map.put("CompanyId", companyId);
                    map.put("TokenId", tokenId);
                    JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, storeUrl, new JSONObject(map), new Response.Listener<JSONObject>() {
                        @Override
                        public void onResponse(JSONObject response) {
                            Log.i(TAG, "Token has been posted in server!");
                        }
                    }, new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {
                            Log.i(TAG, "Error posting token into server!!");
                        }
                    });
                    request.setRetryPolicy(new VolleyRetryPolicy().getRetryPolicy());
                    RequestQueue queue = ((VolleyRequestQueue) getApplication()).getRequestQueue();
                    queue.add(request);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            System.out.println("Token Mesage=" + msg);
            return msg;
        }

        @Override
        protected void onPostExecute(String s) {
        }
    }.execute();
}

您可以看到我将用户的令牌ID存储到我的服务器中。 现在我还创建了一个GcmBroadcastReceiver类

public class GcmBroadcastReceiver extends WakefulBroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
    ComponentName comp = new ComponentName(context.getPackageName(),
            NotificationService.class.getName());
    startWakefulService(context, (intent.setComponent(comp)));
    setResultCode(Activity.RESULT_OK);
}

}

我还创建了一个NotificationService类,它具有MessageReceived方法

public class NotificationService extends GcmListenerService {


public static final int notifyID = 9001;
public static final String appname = "FM Ninja";
NotificationCompat.Builder builder;

public NotificationService() {
    //    super("GcmIntentService");
}

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

        Intent resultIntent = null;
        PendingIntent resultPendingIntent;
        resultIntent = new Intent(this, HomeActivity.class);
        resultPendingIntent = PendingIntent.getActivity(this, 0,
                resultIntent, PendingIntent.FLAG_CANCEL_CURRENT);

        NotificationCompat.Builder mNotifyBuilder;
        NotificationManager mNotificationManager;

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

        mNotifyBuilder = new NotificationCompat.Builder(this)
                .setContentTitle("title")
                .setTicker("New Message !")
                .setContentText("first message please")
                .setSmallIcon(R.mipmap.cms_launch_icon);

        // Set pending intent
        mNotifyBuilder.setContentIntent(resultPendingIntent);

        // Set Vibrate, Sound and Light
        int defaults = 0;
        defaults = defaults | Notification.DEFAULT_LIGHTS;
        defaults = defaults | Notification.DEFAULT_VIBRATE;
        defaults = defaults | Notification.DEFAULT_SOUND;

        mNotifyBuilder.setDefaults(defaults);
        mNotifyBuilder.setAutoCancel(true);
        // Post a notification
        mNotificationManager.notify(notifyID, mNotifyBuilder.build());
}

}

问题是即使在Manifeast中添加权限时,从服务器调用onMessageReceived永远不会执行请帮助我。 我还会发布表现文件

 <uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

<!--GCM Permissions-->

<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<uses-permission android:name="com.google.android.c2dm.permission.SEND"/>
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<permission android:name="com.six30labs.cms.permission.C2D_MESSAGE"
    android:protectionLevel="signature"/>

<uses-permission android:name="com.six30labs.cms.permission.C2D_MESSAGE" />


<application
    android:name="com.six30labs.cms.general.VolleyRequestQueue"
    android:allowBackup="true"
    android:icon="@mipmap/cms_launch_icon"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">

    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>
    </activity>

    <activity android:name=".SplashScreen">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>


    <meta-data android:name="com.google.android.gms.version"
        android:value="@integer/google_play_services_version" />

    <activity android:name=".LoginActivity" />
    <activity android:name=".ForgotPassword" />
    <activity android:name=".NoInternet" />
    <activity android:name=".HomeActivity"/>
    <activity android:name=".ComplaintDetailsSupervisor" />
    <activity android:name=".ComplaintDetailsEmployee" />
    <activity android:name=".NavBarProfile" />
    <activity android:name=".ComplaintDetailsWorker" />
    <activity android:name=".AssignedDetailSupervisor" />
    <activity android:name=".AcceptedComplaintDetailsWorker" />
    <activity android:name=".VerifyDetailSupervisor"/>
    <activity android:name=".ManagerComplaintListActivity"/>

    <!--<service android:name="com.six30labs.cms.storage.RegistrationIntentService"
        android:exported="false"/>-->

    <receiver
        android:name="com.six30labs.cms.general.GcmBroadcastReceiver"
        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="com.six30labs.cms"/>
        </intent-filter>
    </receiver>

    <!-- Register Service -->

    <service android:name="com.six30labs.cms.general.NotificationService"
        android:exported="false" >
        <intent-filter>
            <action android:name="com.google.android.c2dm.intent.RECEIVE" />
        </intent-filter>
    </service>

</application>

服务器端脚本

public class GCMNotification
{
    private CMSEntities db = new CMSEntities();
    static string gcmid = "AIzaSyB7HSIF1RIvkyCnpP6KtYiy6wQ-s6YBscY";

    public void AssignEmpNotification(string employeeid)
    {
        long id = Convert.ToInt64(employeeid);
        PushBroker pushBroker = new PushBroker();
        pushBroker.RegisterGcmService(new GcmPushChannelSettings(gcmid));
        pushBroker.QueueNotification(new GcmNotification().ForDeviceRegistrationId("APA91bGElkVodLyubuMM90TEnfUMab0Fs6JudsjXcgIUrTrT8Zk3GezKYWc9w2gGs6pzLLq_nPSZCXU30M5iYKdRJcKZnkafWuwhnihZQ88vcwUrKhiQn6eWSqGrLCeHFblVT09IR7jy")
           .WithJson(@"{""message"":""Hi Hello" + "wsfdasd" + @""",""title"":""title" + "vendorBids" + @""",""Bidsid"":""" + "1" + @""",""Eventdate"":""" + "2/2/2016" + @""",""vendorname"":""" + "name" + @"""}"));

        pushBroker.StopAllServices();
    }

}

2 个答案:

答案 0 :(得分:1)

  1. 服务器需要发送http post请求 到&#34; https://android.googleapis.com/gcm/send&#34;以及列表 注册ID和消息作为正文数据。

    身体数据是以下组合:    一个。注册ID(这是一个数组列表)    湾消息

    标题是以下组合:    一个。内容类型    湾授权(关键:项目ID)

    1. List regIds = new ArrayList(); //将regIds添加到此列表:regIds.add(&#34; value&#34;); JSONObject data = new JSONObject(); data.put(&#34; registration_ids&#34;,regIds); data.put(&#34;消息&#34;,&#34;你好&#34;);

    2. ApiKey是我们在Google商店中创建的项目期间收到的值。 Map headers = new HashMap(); headers.put(&#34; Content-Type&#34;,&#34; application / json&#34;); header.put(&#34;授权&#34;&#34;键= ApiKey&#34);

    3. 发送http post请求后。谷歌gcm服务器将发送 向http中提到注册ID的所有用户发送的消息 请求。

    4. Android手机将收到来自gcm服务器的通知作为回复 这将由GCMBroadcastReceiver处理。 现在将调用NotificationService类来扩展 IntentService。 在这堂课上, @覆盖 protected void onHandleIntent(Intent intent){ Bundle extras = intent.getExtras(); GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this); String messageType = gcm.getMessageType(intent);

      if(!extras.isEmpty()&amp;&amp; GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE.equals(messageType)){     showNotification(intent.getStringExtra(&#34;消息&#34)); } GcmBroadcastReceiver.completeWakefulIntent(意向); }

    5. 此方法正在调用&#34; showNotification&#34;有字符串的方法 参数。 使用此消息并使用NotificationManager在通知中显示。

  2. 希望这会有所帮助:)

答案 1 :(得分:0)

在向Google服务器发送通知有效内容后,开始记录服务器获取的响应。如果设备令牌出现问题,您将收到“未注册”等详细错误。

如果令牌中没有问题,Google服务器会以成功和消息ID回复您。

一旦您确信设备令牌没有问题,我们就可以考虑设备代码中的问题。

我能想到的其他可能问题是,您在Google开发者控制台中添加的SHA哈希与您已为该应用签署的密钥库的SHA哈希不匹配。 添加debug.keystore的SHA哈希以及生产签名密钥库。