Android 将GCM推送通知包括到我的应用程序中

Android 将GCM推送通知包括到我的应用程序中,android,google-cloud-messaging,Android,Google Cloud Messaging,我希望在分配任务时(即单击按钮)向用户发送通知。当任务分配给用户时,我会更改服务器中的一些值(即,我正在执行post方法),我想知道如何实现这一点。 在用户登录到我的应用程序之前,我一直在注册用户&我正在将用户令牌id存储到我的服务器中。我还通过了《谷歌开发者指南》,注册了我的应用程序,并获得了senderid和serverapikey。我会将代码发布到我到达的地方,请帮助我如何继续 物流活动 private void checkUserRegistrationToken() { St

我希望在分配任务时(即单击按钮)向用户发送通知。当任务分配给用户时,我会更改服务器中的一些值(即,我正在执行post方法),我想知道如何实现这一点。 在用户登录到我的应用程序之前,我一直在注册用户&我正在将用户令牌id存储到我的服务器中。我还通过了《谷歌开发者指南》,注册了我的应用程序,并获得了senderid和serverapikey。我会将代码发布到我到达的地方,请帮助我如何继续

物流活动

 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();
}
}

我还创建了一个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());
}
}

问题是,即使在Manifeat中添加了权限,当从服务器发出的调用onMessageReceived从未执行时,请帮助我。 我还将发布Manifeat文件

 <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>

将通知负载发送到google服务器后,开始记录服务器收到的响应。如果设备令牌有问题,您将得到一个详细错误,如“未注册”

如果令牌中没有问题,谷歌服务器将用success和消息id响应您

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

我能想到的另一个可能的问题是,您在google开发者控制台中添加的SHA哈希与您为应用程序签名的密钥库的SHA哈希不匹配。 添加debug.keystore的SHA哈希以及生产签名密钥库

  • 服务器需要发送http post请求 将“”与 注册ID和消息作为正文数据

    正文数据是以下各项的组合: A.注册ID(数组列表) B信息

    标题是以下内容的组合: A.内容类型 B授权(密钥:项目id)

  • List regIds=new ArrayList(); //将regIds添加到此列表:regIds.add(“值”); JSONObject数据=新的JSONObject(); data.put(“注册ID”,regIds); data.put(“Message”、“Hello”)

  • ApiKey是我们在google store中创建项目期间获得的价值。 Map headers=newhashmap(); headers.put(“内容类型”、“应用程序/json”); header.put(“授权”,“key=ApiKey”)

  • 在发送http post请求之后。google gcm服务器将发送 发送给http中提到其注册id的所有用户的消息 请求

  • android手机将收到来自gcm服务器的通知作为响应 这将由GCMBroadcastReceiver处理。 现在将调用NotificationService类,该类将扩展 意向服务。 在这个班上,, @凌驾 受保护的手部内容无效(意图){ Bundle extras=intent.getExtras(); GoogleCloudMessaging gcm=GoogleCloudMessaging.getInstance(this); 字符串messageType=gcm.getMessageType(intent)

    如果(!extras.isEmpty()&& GoogleCloudMessaging.MESSAGE\u TYPE\u MESSAGE.equals(messageType)){ showNotification(intent.getStringExtra(“消息”)); } GcmBroadcastReceiver.completeWakefulIntent(intent); }

  • 此方法正在调用具有字符串的“showNotification”方法 参数 使用NotificationManager使用此消息并在通知中显示


  • 希望这有帮助:)

    我只想对令牌id进行硬编码,一旦我实现了这一点,我就会向我的手机发送通知,然后在必须在服务器端发送通知时进行编码。发布服务器端代码,因为这将负责通过谷歌云发送gcm。先生,我们正在使用GCMNotification.cs…如何确认GCM服务器是否已收到从我的服务器发送的消息?我在我的服务器上得到了一个成功的输出,但我怀疑GCM服务器是否收到了它…如果响应有成功、失败和结果。这意味着服务器响应了请求。“成功”列显示收到消息的ID数,而“失败”列显示无法收到消息的ID数。请粘贴来自GCMServer的响应。要检查更多信息,可以使用curl请求发送GCMNotification。在命令提示符下,使用curl请求作为:curl--header“Authorization:key=API\u key”--header内容类型:“application/json”-d“{\”data\”:{\”Message\”:\“Welcome To push notifications\”}“registration\u ids\”:[\”regId\“]}“您好,先生,我尝试记录响应,但服务器的响应失败,它给出的响应为[GCM mismatchSenderId],尽管我使用了正确的发件人id,我还尝试在google developer console上重新创建另一个项目,并注册了我的手机,获得了一个新的密钥[token],但仍然显示相同的错误消息。。请帮助我,RakeshHello先生,我尝试记录响应,但是服务器的响应失败了,它给出了[GCM mismatchSenderId],尽管我使用了正确的发件人id,我还尝试在google开发者控制台上重新创建另一个项目,注册了我的手机并获得了一个新密钥[token]但它仍然显示相同的错误消息。。请帮忙,拉凯什
     <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();
        }
    
    }