推送通知在Android中没有收到 [英] Push Notification not Received in android

查看:243
本文介绍了推送通知在Android中没有收到的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新来的推送通知,我试图发送一个推送通知,该通知已被登记到GCM服务特定的设备。我按照实现我的应用程序<一href="http://www.androidhive.info/2012/10/android-push-notifications-using-google-cloud-messaging-gcm-php-and-mysql/"相对=nofollow>这个例子 而在我的程序相应的修改。不过,我不能够接收推送通知的设备上。

下面是我的code:

 包com.markattendence.activites;

引入静态com.markattendence.activites.CommonUtilities.DISPLAY_MESSAGE_ACTION;
引入静态com.markattendence.activites.CommonUtilities.EXTRA_MESSAGE;
引入静态com.markattendence.activites.CommonUtilities.SENDER_ID;

进口org.apache.http.client.HttpClient;
进口org.apache.http.client.ResponseHandler;
进口org.apache.http.client.methods.HttpGet;
进口org.apache.http.impl.client.BasicResponseHandler;
进口org.apache.http.impl.client.DefaultHttpClient;
进口org.json.JSONException;
进口org.json.JSONObject;

进口android.app.Activity;
进口android.app.ProgressDialog;
进口android.content.BroadcastReceiver;
进口android.content.ComponentName;
进口android.content.Context;
进口android.content.Intent;
进口android.content.IntentFilter;
进口android.content.Shared preferences;
进口android.content.Shared preferences.Editor;
进口android.os.AsyncTask;
进口android.os.Bundle;
进口android.support.v4.content.WakefulBroadcastReceiver;
进口android.util.Log;
进口android.widget.TextView;
进口android.widget.Toast;

进口com.google.android.gcm.GCMRegistrar;
进口com.markattendence.activites.MainActivity.YourAsyncTaskLogin;
进口com.markattendence.markattendence.R;

公共类NotificationActivity延伸活动{
//标签显示GCM消息
TextView的lblMessage;

// Asyntask
AsyncTask的&LT;虚空,虚空,虚空&GT; mRegisterTask;

//警报对话框经理
AlertDialogManager警报=新AlertDialogManager();

//连接器
ConnectionDetector CD;

私人字符串userFName;

私人字符串纬度;

私人字符串经度;
私有静态字符串KEY_SUCCESS =成功;
私有静态字符串KEY_ERROR =错误;
私有静态字符串KEY_ERROR_MSG =ERROR_MSG;
私有静态字符串KEY_UID =UID;
私有静态字符串KEY_FNAME =FNAME;
私有静态字符串KEY_EMAIL =电子邮件;
私有静态字符串KEY_LNAME =LNAME;

UserFunctions userFunction;
私人的JSONObject JSON;

公共静态字符串名称;
公共静态字符串的电子邮件;

共享preferences preFS;
公共静态最后弦乐我的preFERENCES =我的preFS;

@覆盖
公共无效的onCreate(包savedInstanceState){
    super.onCreate(savedInstanceState);
    的setContentView(R.layout.activity_notification);

    CD =新ConnectionDetector(getApplicationContext());
    preFS = getShared preferences(我的preFERENCES,Context.MODE_PRIVATE);

    如果(prefs.contains(信息)){
        lblMessage.setText(prefs.getString(信息,));

    }

    //检查网络present
    如果(!cd.isConnectingToInternet()){
        // Internet连接没有present
        alert.showAlertDialog(NotificationActivity.this,
                Internet连接错误,
                请连接到Internet连接,假);
        //停止执行返回code
        返回;
    }

    //获取来自意图的姓名,电子邮件
    意图I = getIntent();

    NAME = i.getStringExtra(uFName);
    userFName = i.getStringExtra(uFName);
    电子邮件= i.getStringExtra(电子邮件);
    纬度= i.getStringExtra(纬度);
    经度= i.getStringExtra(经度);

    //确保设备具有适当的依赖关系。
    GCMRegistrar.checkDevice(本);

    //确保清单中正确设置 - 这一行注释掉
    //而开发的应用程序,然后去掉它时,它已经准备好。
    GCMRegistrar.checkManifest(本);

    lblMessage =(TextView中)findViewById(R.id.lblMessage);

    registerReceiver(mHandleMessageReceiver,新的IntentFilter(
            DISPLAY_MESSAGE_ACTION));

    //获取GCM注册ID
    最后弦乐REGID = GCMRegistrar.getRegistrationId(本);

    //检查REGID已经presents
    如果(regId.equals()){
        //注册是不是present,与GCM现在注册
        GCMRegistrar.register(这一点,SENDER_ID);
    } 其他 {
        //设备已经在GCM注册
        如果(GCMRegistrar.isRegisteredOnServer(本)){
            //跳过注册。
            Toast.makeText(getApplicationContext(),
                    已经与GCM注册,Toast.LENGTH_LONG)
                    。显示();
        } 其他 {
            //尝试重新注册,而不是在UI线程。
            //这也是必要取消线程的onDestroy()
            //因此使用原纱的AsyncTask代替。
            最终的上下文语境=这一点;
            mRegisterTask =新的AsyncTask&LT;虚空,虚空,虚空&GT;(){

                @覆盖
                保护无效doInBackground(虚空...... PARAMS){
                    //注册我们的服务器上
                    //在服务器上创建一个新用户
                    ServerUtilities.register(上下文,姓名,电子邮件,REGID);
                    返回null;
                }

                @覆盖
                保护无效onPostExecute(无效的结果){
                    mRegisterTask = NULL;
                }

            };
            mRegisterTask.execute(NULL,NULL,NULL);
        }
    }
    如果(名字!= NULL){
    userFunction =新UserFunctions();
    新YourAsyncTaskLogin()执行();
    }
}

/ **
 *接收推送消息
 * * /
私人最终WakefulBroadcastReceiver mHandleMessageReceiver =新WakefulBroadcastReceiver(){
    @覆盖
    公共无效的onReceive(上下文的背景下,意图意图){
        组件名补偿=新的组件名(context.getPackageName()
                GCMIntentService.class.getName());
        //启动服务,保持设备时推出清醒。
        startWakefulService(上下文,(intent.setComponent(化合物)));
        的setResult code(Activity.RESULT_OK);

        字符串NewMessage作为= intent.getExtras()的getString(EXTRA_MESSAGE)。
        //醒来移动,如果它是睡
        WakeLocker.acquire(getApplicationContext());

        / **
         *采取这一消息采取适当的行动,这取决于你的应用程序
         *要求现在我只是在屏幕上显示出来
         * * /

        //显示接收到的消息
        lblMessage.append(NewMessage作为+\ N);
        Toast.makeText(getApplicationContext(),
                新邮件:ASD+ NewMessage作为,Toast.LENGTH_LONG).show();

        preFS = context.getShared preferences(我的preFERENCES,
                Context.MODE_PRIVATE);
        编辑EDITOR = prefs.edit();
        editor.putString(消息,lblMessage.getText()的toString());
        editor.commit();
        //释放唤醒锁
        WakeLocker.release();
    }
};

@覆盖
保护无效的onDestroy(){
    如果(mRegisterTask!= NULL){
        mRegisterTask.cancel(真正的);
    }
    尝试 {
        unregisterReceiver(mHandleMessageReceiver);
        GCMRegistrar.onDestroy(本);
    }赶上(例外五){
        Log.e(注销接收器错误,&gt;中+ e.getMessage());
    }
    super.onDestroy();
}

类YourAsyncTaskLogin扩展的AsyncTask&LT;虚空,虚空,虚空&GT; {

    私人ProgressDialog _ProgressDialog;
    私人字符串userid;

    @覆盖
    在preExecute保护无效(){
        //在这里展示您的对话框

        _ProgressDialog = ProgressDialog.show(NotificationActivity.this,
                ,加载,真正的);

    }

    @覆盖
    保护无效doInBackground(虚空...... PARAMS){

        尝试 {

            JSON = userFunction.sendMessage(userFName,
                    也标志着勤,签入,纬度,
                    经度);
            / *
             * HttpClient的客户端=新DefaultHttpClient();串
             * SetServerString =;
             *
             * //创建请求的服务器,并得到回应
             *
             * HTTPGET HTTPGET =新HTTPGET(
             *http://wibman.com/pnt/send_message.php?message=+姓名+
             *检入和放大器;纬度=+纬度+&放大器;经度=+
             * 经度); ResponseHandler的&LT;字符串&GT; ResponseHandler的=新
             * BasicResponseHandler(); SetServerString =
             * Client.execute(HTTPGET,ResponseHandler所);
             * /

            //显示响应上的活动

            // content.setText(SetServerString);
        }赶上(例外前){
            ex.printStackTrace();
            // content.setText(失败!);
        }
        返回null;
    }

    保护无效onPostExecute(无效的结果){

        尝试 {
            Log.e(aaaaaaaaaaaaaaaaaaaaaaaaaaa
                    json.getString(KEY_SUCCESS));
            如果(json.getString(KEY_SUCCESS)!= NULL){
                // loginErrorMsg.setText();
                字符串解析度= json.getString(KEY_SUCCESS);

                如果(的Integer.parseInt(RES)== 1){
                    / *用户id = json.getString(KEY_UID);
                    userFName = json.getString(KEY_FNAME);

                    userFName.replace(\,);

                    userId.replace(\,);

                    Log.e(UID = AAA,用户id);
                    Log.e(nameuser,userFName); * /

                    仪表盘意图=新的意图(getApplicationContext()
                            MainActivity.class);

                    //关闭所有视图启动前
                    //仪表板
                    startActivity(仪表盘);

                    //关闭登录屏幕
                    完();

                } 其他 {
                    //在登录错误
                    // loginErrorMsg.setText(不正确的用户名/密码);

                    _ProgressDialog.cancel();

                    alert.showAlertDialog(NotificationActivity.this,
                            考勤失败。,
                            马克考勤失败,假);
                    // loginStatusTxtView.setText(不正确的用户名/密码);
                }

            } 其他 {
                //在登录错误
                // loginErrorMsg.setText(不正确的用户名/密码);

                _ProgressDialog.cancel();

                alert.showAlertDialog(NotificationActivity.this,
                        考勤失败。,马克考勤失败。
                        假);
                // loginStatusTxtView.setText(不正确的用户名/密码);
            }
        }赶上(JSONException E){
            e.printStackTrace();
            Log.e(错误,e.getMessage());
        }

        _ProgressDialog.dismiss();

    }
}

 }
 

的Manifest.xml

 &LT; XML版本=1.0编码=UTF-8&GT?;
&LT;舱单的xmlns:机器人=htt​​p://schemas.android.com/apk/res/android
包=com.markattendence.markattendence
安卓版code =1
机器人:VERSIONNAME =1.0&GT;

&LT;用途-SDK
    安卓的minSdkVersion =10
    机器人:targetSdkVersion =18/&GT;

&LT;使用-权限的Andr​​oid:名称=android.permission.CAMERA/&GT;
&LT;使用-权限的Andr​​oid:名称=android.permission.INTERNET对/&GT;
&LT;使用-权限的Andr​​oid:名称=android.permission.ACCESS_FINE_LOCATION/&GT;
&LT;使用-权限的Andr​​oid:名称=android.permission.INTERNET对/&GT;
&LT;使用-权限的Andr​​oid:名称=android.permission.ACCESS_NETWORK_STATE/&GT;
&LT;使用-权限的Andr​​oid:名称=android.permission.ACCESS_NETWORK_STATE/&GT;

&LT;! -  GCM需要一个谷歌帐户。 - &GT;
&LT;使用-权限的Andr​​oid:名称=android.permission.GET_ACCOUNTS/&GT;

&LT;! - 进入休眠状态保持处理器接收到消息时。 - &GT;
&LT;使用-权限的Andr​​oid:名称=android.permission.WAKE_LOCK/&GT;

&LT;! - 创建一个自定义权限所以只有这个程序可以接收它的消息。 - &GT;
&LT;许可
    机器人:名称=com.markattendence.markattendence.permission.C2D_MESSAGE
    安卓的ProtectionLevel =签名/&GT;

&LT;使用-权限的Andr​​oid:名称=com.markattendence.markattendence.permission.C2D_MESSAGE/&GT;
&LT;使用-权限的Andr​​oid:名称=com.markattendence.activites.permission.C2D_MESSAGE/&GT;

&LT;  - !此应用程序有权限注册并接收数据信息。 - &GT;
&LT;使用-权限的Andr​​oid:名称=com.google.android.c2dm.permission.RECEIVE/&GT;

&LT;! - 网络状态的权限来检测网络状态 - &GT;
&LT;使用-权限的Andr​​oid:名称=android.permission.ACCESS_NETWORK_STATE/&GT;

&LT;! - 权限振动 - &GT;
&LT;使用-权限的Andr​​oid:名称=android.permission.VIBRATE/&GT;

&LT;使用特征的android:NAME =android.hardware.camera/&GT;
&LT;用途特征
    机器人:名称=android.hardware.camera.front
    机器人:要求=FALSE/&GT;
&LT;使用特征的android:NAME =android.hardware.camera.autofocus/&GT;

&LT;使用-权限的Andr​​oid:名称=android.permission.WRITE_EXTERNAL_STORAG​​E/&GT;

&lt;应用
    机器人:allowBackup =真
    机器人:图标=@可绘制/ mmes_logo
    机器人:标签=@字符串/ APP_NAME
    机器人:主题=@风格/ AppTheme&GT;
    &LT;活动
        机器人:名称=com.markattendence.markattendence.MainActivity
        机器人:标签=@字符串/ APP_NAME&GT;
        &LT;意向滤光器&gt;
            &lt;作用机器人:名称=android.intent.action.MAIN/&GT;

            &LT;类机器人:名称=android.intent.category.LAUNCHER/&GT;
        &所述; /意图滤光器&gt;
    &LT; /活性GT;
    &LT;活动机器人:名称=com.markattendence.markattendence.MarkAttendenceActivity&GT;
    &LT; /活性GT;
    &LT;活动机器人:名称=com.markattendence.markattendence.NotificationActivity&GT;
    &LT; /活性GT;

    &LT;接收器
        机器人:名称=com.google.android.gcm.GCMBroadcastReceiver
        机器人:权限=com.google.android.c2dm.permission.SEND&GT;
        &LT;意向滤光器&gt;

            &LT;  - !接收的实际消息。 - &GT;
            &lt;作用机器人:名称=com.google.android.c2dm.intent.RECEIVE/&GT;
            &所述;! - 接收的注册ID。 - &GT;
            &lt;作用机器人:名称=com.google.android.c2dm.intent.REGISTRATION/&GT;

            &LT;类机器人:名称=com.markattendence.markattendence/&GT;
        &所述; /意图滤光器&gt;
    &LT; /接收器&GT;

    &LT;服务机器人:名称=com.markattendence.markattendence.GCMIntentService/&GT;
&LT; /用途&gt;
 

我在接到通知有问题。服务器端code正常工作。

我的日志猫说:

<$p$p><$c$c>{"multicast_id":5884981605957538237,"success":1,"failure":0,"canonical_ids":0,"results":[{"message_id":"0:1393495991926450%978fee92f9fd7ecd"}]}

的主要问题是,如果设备具有示例应用程序就得到通知,在该应用程序,而不是我的定制应用程序。如果我删除应用程序,我没有得到任何通知。所以我很困惑的通知,在我的应用程序要接收而不是androidhive应用程序,但推送通知的显示在androidhive应用。请帮我解决这个问题。在此先感谢。

解决方案

您的清单一些错误,只能导致对旧的Andr​​oid版本的问题:

您packagge名为 com.markattendence.markattendence

因此​​,你应该改变这样的:

 &LT;允许机器人:名称=com.markattendence.markattendence.permission.C2D_MESSAGE
    安卓的ProtectionLevel =签名/&GT;
&LT;使用-权限的Andr​​oid:名称=com.example.gcm.permission.C2D_MESSAGE/&GT;
 

要这样:

 &LT;允许机器人:名称=com.markattendence.markattendence.permission.C2D_MESSAGE
    安卓的ProtectionLevel =签名/&GT;
&LT;使用-权限的Andr​​oid:名称=com.markattendence.markattendence.permission.C2D_MESSAGE/&GT;
 

和这样的:

 &LT;接收器
    机器人:名称=com.google.android.gcm.GCMBroadcastReceiver
    机器人:权限=com.google.android.c2dm.permission.SEND&GT;
    &LT;意向滤光器&gt;

        &LT;  - !接收的实际消息。 - &GT;
        &lt;作用机器人:名称=com.google.android.c2dm.intent.RECEIVE/&GT;
        &所述;! - 接收的注册ID。 - &GT;
        &lt;作用机器人:名称=com.google.android.c2dm.intent.REGISTRATION/&GT;

        &LT;类机器人:名称=com.markattendence.activites/&GT;
    &所述; /意图滤光器&gt;
&LT; /接收器&GT;
 

要这样:

 &LT;接收器
    机器人:名称=com.google.android.gcm.GCMBroadcastReceiver
    机器人:权限=com.google.android.c2dm.permission.SEND&GT;
    &LT;意向滤光器&gt;

        &LT;  - !接收的实际消息。 - &GT;
        &lt;作用机器人:名称=com.google.android.c2dm.intent.RECEIVE/&GT;
        &所述;! - 接收的注册ID。 - &GT;
        &lt;作用机器人:名称=com.google.android.c2dm.intent.REGISTRATION/&GT;

        &LT;类机器人:名称=com.markattendence.markattendence/&GT;
    &所述; /意图滤光器&gt;
&LT; /接收器&GT;
 

I am new to push notifications and I'm trying to send a push notification to a particular device which has already been registered to GCM service. I implemented my app according to this example and modified accordingly in my program. However, I am not able to receive push notifications on the device.

Here is my code:

package com.markattendence.activites;

import static com.markattendence.activites.CommonUtilities.DISPLAY_MESSAGE_ACTION;
import static com.markattendence.activites.CommonUtilities.EXTRA_MESSAGE;
import static com.markattendence.activites.CommonUtilities.SENDER_ID;

import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.content.WakefulBroadcastReceiver;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gcm.GCMRegistrar;
import com.markattendence.activites.MainActivity.YourAsyncTaskLogin;
import com.markattendence.markattendence.R;

public class NotificationActivity extends Activity {
// label to display gcm messages
TextView lblMessage;

// Asyntask
AsyncTask<Void, Void, Void> mRegisterTask;

// Alert dialog manager
AlertDialogManager alert = new AlertDialogManager();

// Connection detector
ConnectionDetector cd;

private String userFName;

private String latitude;

private String longitude;
private static String KEY_SUCCESS = "success";
private static String KEY_ERROR = "error";
private static String KEY_ERROR_MSG = "error_msg";
private static String KEY_UID = "uid";
private static String KEY_FNAME = "fname";
private static String KEY_EMAIL = "email";
private static String KEY_LNAME = "lname";

UserFunctions userFunction;
private JSONObject json;

public static String name;
public static String email;

SharedPreferences prefs;
public static final String MyPREFERENCES = "MyPrefs";

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_notification);

    cd = new ConnectionDetector(getApplicationContext());
    prefs = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);

    if (prefs.contains("message")) {
        lblMessage.setText(prefs.getString("message", ""));

    }

    // Check if Internet present
    if (!cd.isConnectingToInternet()) {
        // Internet Connection is not present
        alert.showAlertDialog(NotificationActivity.this,
                "Internet Connection Error",
                "Please connect to working Internet connection", false);
        // stop executing code by return
        return;
    }

    // Getting name, email from intent
    Intent i = getIntent();

    name = i.getStringExtra("uFName");
    userFName = i.getStringExtra("uFName");
    email = i.getStringExtra("email");
    latitude = i.getStringExtra("latitude");
    longitude = i.getStringExtra("longitude");

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

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

    lblMessage = (TextView) findViewById(R.id.lblMessage);

    registerReceiver(mHandleMessageReceiver, new IntentFilter(
            DISPLAY_MESSAGE_ACTION));

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

    // Check if regid already presents
    if (regId.equals("")) {
        // Registration is not present, register now with GCM
        GCMRegistrar.register(this, SENDER_ID);
    } else {
        // Device is already registered on GCM
        if (GCMRegistrar.isRegisteredOnServer(this)) {
            // Skips registration.
            Toast.makeText(getApplicationContext(),
                    "Already registered with GCM", Toast.LENGTH_LONG)
                    .show();
        } else {
            // Try to register again, but not in the UI thread.
            // It's also necessary to cancel the thread onDestroy(),
            // hence the use of AsyncTask instead of a raw thread.
            final Context context = this;
            mRegisterTask = new AsyncTask<Void, Void, Void>() {

                @Override
                protected Void doInBackground(Void... params) {
                    // Register on our server
                    // On server creates a new user
                    ServerUtilities.register(context, name, email, regId);
                    return null;
                }

                @Override
                protected void onPostExecute(Void result) {
                    mRegisterTask = null;
                }

            };
            mRegisterTask.execute(null, null, null);
        }
    }
    if(name != null){
    userFunction = new UserFunctions();
    new YourAsyncTaskLogin().execute();
    }
}

/**
 * Receiving push messages
 * */
private final WakefulBroadcastReceiver mHandleMessageReceiver = new WakefulBroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        ComponentName comp = new ComponentName(context.getPackageName(),
                GCMIntentService.class.getName());
        // Start the service, keeping the device awake while it is launching.
        startWakefulService(context, (intent.setComponent(comp)));
        setResultCode(Activity.RESULT_OK);

        String newMessage = intent.getExtras().getString(EXTRA_MESSAGE);
        // Waking up mobile if it is sleeping
        WakeLocker.acquire(getApplicationContext());

        /**
         * Take appropriate action on this message depending upon your app
         * requirement For now i am just displaying it on the screen
         * */

        // Showing received message
        lblMessage.append(newMessage + "\n");
        Toast.makeText(getApplicationContext(),
                "New Message: asd" + newMessage, Toast.LENGTH_LONG).show();

        prefs = context.getSharedPreferences(MyPREFERENCES,
                Context.MODE_PRIVATE);
        Editor editor = prefs.edit();
        editor.putString("message", lblMessage.getText().toString());
        editor.commit();
        // Releasing wake lock
        WakeLocker.release();
    }
};

@Override
protected void onDestroy() {
    if (mRegisterTask != null) {
        mRegisterTask.cancel(true);
    }
    try {
        unregisterReceiver(mHandleMessageReceiver);
        GCMRegistrar.onDestroy(this);
    } catch (Exception e) {
        Log.e("UnRegister Receiver Error", "> " + e.getMessage());
    }
    super.onDestroy();
}

class YourAsyncTaskLogin extends AsyncTask<Void, Void, Void> {

    private ProgressDialog _ProgressDialog;
    private String userId;

    @Override
    protected void onPreExecute() {
        // show your dialog here

        _ProgressDialog = ProgressDialog.show(NotificationActivity.this,
                "", "Loading", true);

    }

    @Override
    protected Void doInBackground(Void... params) {

        try {

            json = userFunction.sendMessage(userFName,
                    " has marked attendence of ", "CheckIN", latitude,
                    longitude);
            /*
             * HttpClient Client = new DefaultHttpClient(); String
             * SetServerString = "";
             * 
             * // Create Request to server and get response
             * 
             * HttpGet httpget = new HttpGet(
             * "http://wibman.com/pnt/send_message.php?message=" + name +
             * "checked in&Latitude=" + latitude + "&Longitude=" +
             * longitude); ResponseHandler<String> responseHandler = new
             * BasicResponseHandler(); SetServerString =
             * Client.execute(httpget, responseHandler);
             */

            // Show response on activity

            // content.setText(SetServerString);
        } catch (Exception ex) {
            ex.printStackTrace();
            // content.setText("Fail!");
        }
        return null;
    }

    protected void onPostExecute(Void result) {

        try {
            Log.e("aaaaaaaaaaaaaaaaaaaaaaaaaaa",
                    json.getString(KEY_SUCCESS));
            if (json.getString(KEY_SUCCESS) != null) {
                // loginErrorMsg.setText("");
                String res = json.getString(KEY_SUCCESS);

                if (Integer.parseInt(res) == 1) {
                    /*userId = json.getString(KEY_UID);
                    userFName = json.getString(KEY_FNAME);

                    userFName.replace("\"", "");

                    userId.replace("\"", "");

                    Log.e("uid=aaa", userId);
                    Log.e("nameuser", userFName);*/

                    Intent dashboard = new Intent(getApplicationContext(),
                            MainActivity.class);

                    // Close all views before launching
                    // Dashboard
                    startActivity(dashboard);

                    // Close Login Screen
                    finish();

                } else {
                    // Error in login
                    // loginErrorMsg.setText("Incorrect username/password");

                    _ProgressDialog.cancel();

                    alert.showAlertDialog(NotificationActivity.this,
                            "Attendence Failed..",
                            "Mark Attendence Failed.", false);
                    // loginStatusTxtView.setText("Incorrect username/password");
                }

            } else {
                // Error in login
                // loginErrorMsg.setText("Incorrect username/password");

                _ProgressDialog.cancel();

                alert.showAlertDialog(NotificationActivity.this,
                        "Attendence Failed..", "Mark Attendence Failed.",
                        false);
                // loginStatusTxtView.setText("Incorrect username/password");
            }
        } catch (JSONException e) {
            e.printStackTrace();
            Log.e("error", e.getMessage());
        }

        _ProgressDialog.dismiss();

    }
}

 }

Manifest.xml

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

<uses-sdk
    android:minSdkVersion="10"
    android:targetSdkVersion="18" />

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

<!-- GCM requires a Google account. -->
<uses-permission android:name="android.permission.GET_ACCOUNTS" />

<!-- Keeps the processor from sleeping when a message is received. -->
<uses-permission android:name="android.permission.WAKE_LOCK" />

<!-- Creates a custom permission so only this app can receive its messages. -->
<permission
    android:name="com.markattendence.markattendence.permission.C2D_MESSAGE"
    android:protectionLevel="signature" />

<uses-permission android:name="com.markattendence.markattendence.permission.C2D_MESSAGE" />
<uses-permission android:name="com.markattendence.activites.permission.C2D_MESSAGE" />

<!-- This app has permission to register and receive data message. -->
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />

<!-- Network State Permissions to detect Internet status -->
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

<!-- Permission to vibrate -->
<uses-permission android:name="android.permission.VIBRATE" />

<uses-feature android:name="android.hardware.camera" />
<uses-feature
    android:name="android.hardware.camera.front"
    android:required="false" />
<uses-feature android:name="android.hardware.camera.autofocus" />

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

<application
    android:allowBackup="true"
    android:icon="@drawable/mmes_logo"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name="com.markattendence.markattendence.MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity android:name="com.markattendence.markattendence.MarkAttendenceActivity" >
    </activity>
    <activity android:name="com.markattendence.markattendence.NotificationActivity" >
    </activity>

    <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="com.markattendence.markattendence" />
        </intent-filter>
    </receiver>

    <service android:name="com.markattendence.markattendence.GCMIntentService" />
</application>

I am having a problem in receiving the notification. Server side code is working correctly.

My log cat says:

{"multicast_id":5884981605957538237,"success":1,"failure":0,"canonical_ids":0,"results":[{"message_id":"0:1393495991926450%978fee92f9fd7ecd"}]}

The major problem is that, if device has the example app it get notification in that application rather than my customized application. And if I remove that application i don't get any notification. So i am confused that notification has to be received in my app rather than that of androidhive application but push notification is displayed in androidhive application. Please help me to solve this issue. Thanks in advance.

解决方案

You have some errors in your manifest that only cause problems on old Android versions :

Your packagge name is com.markattendence.markattendence.

Therefore you should change this :

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

To this:

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

And this:

<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="com.markattendence.activites" />
    </intent-filter>
</receiver>

To this:

<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="com.markattendence.markattendence" />
    </intent-filter>
</receiver>

这篇关于推送通知在Android中没有收到的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆