从通知栏的GCM通知消息将不会在活动中显示,如果该应用程序尚未启动 [英] The GCM Notification message from the Notification Bar will not be shown in the activity if the app isn't started already

查看:282
本文介绍了从通知栏的GCM通知消息将不会在活动中显示,如果该应用程序尚未启动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用本教程推送通知<一个href=\"http://www.androidhive.info/2012/10/android-push-notifications-using-google-cloud-messaging-gcm-php-and-mysql/\" rel=\"nofollow\">http://www.androidhive.info/2012/10/android-push-notifications-using-google-cloud-messaging-gcm-php-and-mysql/

它工作正常,但是当我在状态栏上点击查看收到的消息,它不会在它开始在MainActivity显示。问题是什么?

MainActivity接收该消息

  @覆盖
    保护无效的onCreate(捆绑savedInstanceState){
        super.onCreate(savedInstanceState);
        的setContentView(R.layout.activity_main);
        Log.v(TAG的onCreate?);
        CD =新ConnectionDetector(getApplicationContext());        //检查网络present
        如果(!cd.isConnectingToInternet()){
            //没有Internet连接present
            alert.showAlertDialog(MainActivity.this,
                    网络连接错误
                    请连接的Internet连接,FALSE);
            //停止执行回code
            返回;
        }        //从意图获取名称
        意向I = getIntent();        名称= i.getStringExtra(名称);
        PID = i.getStringExtra(PID);
        //确保设备具有适当的依赖关系。
        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()){
            //Toast.makeText(getApplicationContext(),没有注册,关键是空的,Toast.LENGTH_LONG).show();
            //注册是不是present,与GCM现在就注册
            GCMRegistrar.register(这一点,SENDER_ID);        }其他{
            //Toast.makeText(getApplicationContext(),其他键不空,Toast.LENGTH_LONG).show();
            //设备已登记在GCM
            如果(GCMRegistrar.isRegisteredOnServer(本)){
                //跳过注册。                //Toast.makeText(getApplicationContext(),与GCM已经注册,Toast.LENGTH_LONG).show();
            }其他{                //尝试再次注册,但不是在UI线程。
                //这也是必要取消线程的onDestroy()
                //因此,使用AsyncTask的,而不是一个原始的线程。
                最后上下文的背景下=这;
                mRegisterTask =新的AsyncTask&LT;太虚,太虚,太虚&GT;(){                    @覆盖
                    保护无效doInBackground(虚空...... PARAMS){
                        //注册我们的服务器上
                        //在服务器上创建一个新用户
                        ServerUtilities.register(上下文,姓名,电子邮件,REGID,平,管理,虚拟);
                        返回null;
                    }                    @覆盖
                    保护无效onPostExecute(虚空结果){
                        mRegisterTask = NULL;
                    }                };
                mRegisterTask.execute(NULL,NULL,NULL);
            }        }
        //从SQLite数据库信息
        数据库处理器分贝=新数据库处理器(getApplicationContext());
        // TextView的textview1 =(的TextView)findViewById(R.id.textView1);
        HashMap的&LT;字符串,字符串&GT;地图=新的HashMap&LT;字符串,字符串&GT;();
        地图= db.getUserDetails();
        字符串username = map.get(电子邮件);
        如果(用户名== NULL){
            A =名称;            电影=新的ArrayList&LT;&HashMap的LT;字符串,字符串&GT;&GT;();
            新GetDaPid()执行();            //关闭仪表盘屏幕
            //完();
        }其他{        B =用户名;        }
        电影=新的ArrayList&LT;&HashMap的LT;字符串,字符串&GT;&GT;();
        如果(REPID == NULL){            新GetDaPid()执行();
        }其他{
            新GetDaComments()执行();
        }
    }
    类GetDaComments扩展的AsyncTask&LT;字符串,字符串,字符串&GT; {           @覆盖
           在preExecute保护无效(){
                    super.on preExecute();
           }
            @覆盖
            保护字符串doInBackground(字符串参数... args){            }              保护无效onPostExecute(字符串变焦){
                  zpDialog.dismiss();                  MainActivity.this.runOnUiThread(新的Runnable(){
                    公共无效的run(){
                        ListAdapter适配器=新SimpleAdapter(MainActivity.this,电影,
                               R.layout.stickymessages,新的String [] {意见},
                               新的INT [] {R.id.textView1});                           setListAdapter(适配器);
                          ListView控件LV = getListView();
                         lv.setOnItemClickListener(新OnItemClickListener(){                                @覆盖
                                公共无效onItemClick(适配器视图&LT;&GT;母公司,观景,INT位置,
                                        长ID){                          }
                            lv.setOnTouchListener(新ListView.OnTouchListener(){
                                @覆盖
                                公共布尔onTouch(视图V,MotionEvent事件){
                                    INT行动= event.getAction();
                                    开关(动作){
                                    案例MotionEvent.ACTION_DOWN:
                                        //不允许滚动型拦截触摸事件。
                                        。v.getParent()requestDisallowInterceptTouchEvent(真);
                                        打破;                                    案例MotionEvent.ACTION_UP:
                                        //允许滚动型拦截触摸事件。
                                        。v.getParent()requestDisallowInterceptTouchEvent(假);
                                        打破;
                                    }                                    //处理ListView控件触摸事件。
                                    v.onTouchEvent(事件);
                                    返回true;
                                }
                            });
                    }
                });
            }        }
    类GetDaPid扩展的AsyncTask&LT;字符串,字符串,字符串&GT; {           @覆盖
           在preExecute保护无效(){           }
            @覆盖
            保护字符串doInBackground(字符串参数... args){            }              保护无效onPostExecute(字符串变焦){
                  MainActivity.this.runOnUiThread(新的Runnable(){
                        公共无效的run(){                            新GetDaComments()执行();
                        }
                    });
            }        }    / **
     *接收推送消息
     * * /
    私人最终的BroadcastReceiver mHandleMessageReceiver =新的广播接收器(){
        @覆盖
        公共无效的onReceive(上下文的背景下,意图意图){
        // Log.e(广播,MainActivity.name);
            字符串NewMessage作为= intent.getExtras()的getString(EXTRA_MESSAGE)。
            //醒来移动,如果它是睡觉
            WakeLocker.acquire(getApplicationContext());
            Log.v(TAGE播出?);
            / **
             *采取适当的行动对这个消息
             *根据您的应用需求
             *现在我只是显示在屏幕上
             * * /            //显示接收到的消息
            lblMessage.append(新邮件+ NewMessage作为+\\ n);
            Toast.makeText(getApplicationContext(),新邮件+ NewMessage作为,Toast.LENGTH_LONG).show();            //释放锁唤醒
            WakeLocker.release();
        }
    };    @覆盖
    保护无效的onDestroy(){
        如果(mRegisterTask!= NULL){
            mRegisterTask.cancel(真);
        }
        尝试{
            unregisterReceiver(mHandleMessageReceiver);
            GCMRegistrar.onDestroy(本);
        }赶上(例外五){
            Log.e(注销接收器错误,&gt;中+ e.getMessage());
        }
        super.onDestroy();
    }}

GCM

 公共类GCMIntentService扩展GCMBaseIntentService {    私有静态最后弦乐TAG =GCMIntentService;    公共GCMIntentService(){
        超(SENDER_ID);
    }    / **
     注册*呼吁装置的方法
     ** /
    @覆盖
    保护无效onRegistered(上下文的背景下,字符串registrationId){
        //Log.i(TAG,设备注册:REGID =+ registrationId);
       displayMessage(背景下,您的设备与registred GCM);
       // Log.d(NAME,MainActivity.name);
        ServerUtilities.register(背景下,MainActivity.name,MainActivity.email,registrationId,MainActivity.flat,MainActivity.admin,MainActivity.dummy);
    }    / **
     *呼吁联合国设备的方法registred
     * * /
    @覆盖
    保护无效onUnregistered(上下文的背景下,字符串registrationId){
        Log.i(TAG,设备未注册);
        displayMessage(上下文,的getString(R.string.gcm_unregistered));
        ServerUtilities.unregister(背景下,registrationId);
    }    / **
     *呼吁收到新的消息的方法
     * * /
    @覆盖
    保护无效的onMessage(上下文的背景下,意图意图){
        Log.i(TAG,收到消息);
        字符串消息= intent.getExtras()的getString(价格)。        displayMessage(背景下,消息);
        //通知用户
        generateNotification(背景下,消息);
    }    / **
     *呼吁接收已删除的留言方法
     * * /
    @覆盖
    保护无效onDeletedMessages(上下文的背景下,诠释总计){
        Log.i(TAG,收到的已删除邮件的通知);
        字符串消息=的getString(R.string.gcm_deleted,总数);
        displayMessage(背景下,消息);
        //通知用户
        generateNotification(背景下,消息);
    }    / **
     *呼吁错误方法
     * * /
    @覆盖
    公共无效onerror的(上下文的背景下,字符串ErrorID中){
        Log.i(TAG,收到的错误:+ ErrorID中);
        displayMessage(上下文,的getString(R.string.gcm_error,ErrorID中));
    }    @覆盖
    保护布尔onRecoverableError(上下文的背景下,字符串ErrorID中){
        //日志消息
        Log.i(TAG获得恢复的错误:+ ErrorID中);
        displayMessage(背景下,的getString(R.string.gcm_recoverable_error,
                ErrorID中));
        返回super.onRecoverableError(背景下,ErrorID中);
    }    / **
     *问题的通知,通知服务器发送邮件的用户。
     * /
    私有静态无效generateNotification(上下文的背景下,字符串消息){
        INT图标= R.drawable.ic_launcher;
        时长= System.currentTimeMillis的();
        NotificationManager notificationManager =(NotificationManager)
                context.getSystemService(Context.NOTIFICATION_SERVICE);
        通知通知=新的通知(图标,消息,时);        字符串title = context.getString(R.string.app_name);        意图notificationIntent =新意图(背景下,MainActivity.class);
        //设置的意图,因此它不会启动新活动
        notificationIntent.putExtra(消息,消息);        的PendingIntent意图= PendingIntent.getActivity(上下文,0,notificationIntent,PendingIntent.FLAG_UPDATE_CURRENT);        notification.setLatestEventInfo(上下文,标题,邮件,意图);
        notification.flags | = Notification.FLAG_AUTO_CANCEL;        //播放默认通知声音
        notification.defaults | = Notification.DEFAULT_SOUND;        //notification.sound = Uri.parse(android.resource://+ context.getPackageName()+your_sound_file_name.mp3);        //如果振动启用震动
        notification.defaults | = Notification.DEFAULT_VIBRATE;
        notificationManager.notify(0,通知);    }}

清单

 &LT;?XML版本=1.0编码=UTF-8&GT?;
&LT;清单的xmlns:机器人=htt​​p://schemas.android.com/apk/res/android
    包=com.tromto.flat
    安卓版code =1
    机器人:=的versionName1.0&GT;    &LT;用途-SDK
        安卓的minSdkVersion =8
        机器人:targetSdkVersion =19/&GT;
    &LT;! - GCM连接到Internet服务。 - &GT;
    &LT;使用许可权的android:NAME =android.permission.INTERNET对/&GT;    &LT;! - GCM需要一个谷歌帐户。 - &GT;
    &LT;使用许可权的android:NAME =android.permission.GET_ACCOUNTS/&GT;    &LT;! - 从睡眠收到消息时保持处理器。 - &GT;
    &LT;使用许可权的android:NAME =android.permission.WAKE_LOCK/&GT;    &LT;! - 创建一个自定义权限所以只有这个程序可以接收它的消息。 - &GT;
    &LT;许可
        机器人:名字=com.tromto.flat.permission.C2D_MESSAGE
        安卓的ProtectionLevel =签名/&GT;    &LT;使用许可权的android:NAME =com.tromto.flat.permission.C2D_MESSAGE/&GT;    &LT;! - 这个程序有权限注册和接收数据信息。 - &GT;
    &LT;使用许可权的android:NAME =com.google.android.c2dm.permission.RECEIVE/&GT;    &LT;! - 网络状态的权限来检测网络状态 - &GT;
    &LT;使用许可权的android:NAME =android.permission.ACCESS_NETWORK_STATE/&GT;    &LT;! - 许可振动 - &GT;
    &LT;使用许可权的android:NAME =android.permission.VIBRATE/&GT;    &lt;应用
        机器人:allowBackup =真
        机器人:图标=@绘制/ ic_launcher
        机器人:标签=@字符串/ APP_NAME
        机器人:主题=@风格/ AppTheme&GT;
        &LT;活动
            机器人:名字=。RegisterActivity
            机器人:标签=@字符串/ APP_NAME&GT;
            &所述;意图滤光器&gt;
                &lt;作用机器人:名字=android.intent.action.MAIN/&GT;                &LT;类机器人:名字=android.intent.category.LAUNCHER/&GT;
            &所述; /意图滤光器&gt;
        &LT; /活性GT;
        &LT;活动
            机器人:名字=。MainActivity            机器人:configChanges =方向|屏幕尺寸
            机器人:标签=@字符串/ APP_NAME&GT;
        &LT; /活性GT;
        &LT;! - 登录活动 - &GT;
        &LT;活动
            机器人:名字=。LoginActivity
            机器人:标签=登录帐户&GT;
        &LT; /活性GT;
        &LT;活动
            机器人:名字=。SearchableActivity
            机器人:标签=@字符串/ title_activity_searchable
            机器人:configChanges =方向|屏幕尺寸&GT;
        &LT; /活性GT;
        &LT;活动
            机器人:名字=。FlatListActivity
            机器人:标签=@字符串/ title_activity_flat_list
            机器人:configChanges =方向|屏幕尺寸&GT;
        &LT; /活性GT;        &lt;接收
            机器人:名字=com.google.android.gcm.GCMBroadcastReceiver
            机器人:权限=com.google.android.c2dm.permission.SEND&GT;
            &所述;意图滤光器&gt;                &LT;! - 收到实际的消息。 - &GT;
                &lt;作用机器人:名字=com.google.android.c2dm.intent.RECEIVE/&GT;
                &LT;! - 收到的注册ID。 - &GT;
                &lt;作用机器人:名字=com.google.android.c2dm.intent.REGISTRATION/&GT;                &LT;类机器人:名字=com.tromto.flat/&GT;
            &所述; /意图滤光器&gt;
        &LT; /接收器&GT;        &LT;服务机器人。GCMIntentServiceNAME = /&GT;        &LT;活动
            机器人:名字=。MsgToflatActivity
            机器人:标签=@字符串/ title_activity_msg_toflat
            机器人:configChanges =方向|屏幕尺寸&GT;
        &LT; /活性GT;
        &LT;活动
            机器人:名字=。RegisteradminActivity
            机器人:标签=@字符串/ title_activity_registeradmin&GT;
        &LT; /活性GT;
    &LT; /用途&gt;&LT; /清单&GT;


解决方案

更​​新TextView的初始化后,

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

当你正在通知并把该值与键消息,所以你需要检索值虽然相同的密钥消息

  lblMessage.append(新邮件+ i.getStringExtra(信息)+\\ n);

I am using this tutorial for push notifications http://www.androidhive.info/2012/10/android-push-notifications-using-google-cloud-messaging-gcm-php-and-mysql/

It works fine but when I click on the status bar to see the received message, it doesn't show in the MainActivity which it starts. What is the issue?

MainActivity which receives the message

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


        setContentView(R.layout.activity_main);
        Log.v(TAG, "onCreate?");
        cd = new ConnectionDetector(getApplicationContext());

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



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

        name = i.getStringExtra("name");
        pid= i.getStringExtra("pid");


        // 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("")) {
            //Toast.makeText(getApplicationContext(), "not registered, key is empty ", Toast.LENGTH_LONG).show();
            // Registration is not present, register now with GCM           
            GCMRegistrar.register(this, SENDER_ID);

        } else {
            //Toast.makeText(getApplicationContext(), "else key is not empty ", Toast.LENGTH_LONG).show();
            // 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, flat, admin, dummy);
                        return null;
                    }

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

                };
                mRegisterTask.execute(null, null, null);
            }

        }
        //get info from sqlite database
        DatabaseHandler db = new DatabaseHandler(getApplicationContext());
        //TextView textview1 = (TextView)findViewById(R.id.textView1);
        HashMap<String, String> map = new HashMap<String, String>();
        map = db.getUserDetails();
        String username = map.get("email");


        if (username == null){
            a=name;

            movies = new ArrayList<HashMap<String, String>>();
            new GetDaPid().execute();

            // Closing dashboard screen
            //finish();
        }else{

        b=username;

        }
        movies = new ArrayList<HashMap<String, String>>();
        if (repid==null){

            new GetDaPid().execute();
        }else{
            new GetDaComments().execute();
        }




    }   
    class GetDaComments extends AsyncTask<String, String, String>{

           @Override
           protected void onPreExecute() {
                    super.onPreExecute();
           }


            @Override
            protected String doInBackground(String... args) {

            }

              protected void onPostExecute(String zoom){
                  zpDialog.dismiss();

                  MainActivity.this.runOnUiThread(new Runnable() {
                    public void run() {


                        ListAdapter adapter = new SimpleAdapter(MainActivity.this, movies,
                               R.layout.stickymessages, new String[] {"comments"}, 
                               new int[]{R.id.textView1});

                           setListAdapter(adapter);
                          ListView lv = getListView();


                         lv.setOnItemClickListener(new OnItemClickListener(){

                                @Override
                                public void onItemClick(AdapterView<?> parent, View view, int position,
                                        long id) {



                          }
                            lv.setOnTouchListener(new ListView.OnTouchListener() {
                                @Override
                                public boolean onTouch(View v, MotionEvent event) {
                                    int action = event.getAction();
                                    switch (action) {
                                    case MotionEvent.ACTION_DOWN:
                                        // Disallow ScrollView to intercept touch events.
                                        v.getParent().requestDisallowInterceptTouchEvent(true);
                                        break;

                                    case MotionEvent.ACTION_UP:
                                        // Allow ScrollView to intercept touch events.
                                        v.getParent().requestDisallowInterceptTouchEvent(false);
                                        break;
                                    }

                                    // Handle ListView touch events.
                                    v.onTouchEvent(event);
                                    return true;
                                }
                            });




                    }
                });
            }

        }
    class GetDaPid extends AsyncTask<String, String, String>{

           @Override
           protected void onPreExecute() {

           }


            @Override
            protected String doInBackground(String... args) {

            }

              protected void onPostExecute(String zoom){
                  MainActivity.this.runOnUiThread(new Runnable() {
                        public void run() {

                            new GetDaComments().execute();
                        }
                    });
            }

        }

    /**
     * Receiving push messages
     * */
    private final BroadcastReceiver mHandleMessageReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
        //  Log.e("broadcast", MainActivity.name);
            String newMessage = intent.getExtras().getString(EXTRA_MESSAGE);
            // Waking up mobile if it is sleeping
            WakeLocker.acquire(getApplicationContext());
            Log.v(TAGE, "broadcast?");
            /**
             * 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("New Message: "+ newMessage + "\n");          
            Toast.makeText(getApplicationContext(), "New Message: " + newMessage, Toast.LENGTH_LONG).show();

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

}

GCM

public class GCMIntentService extends GCMBaseIntentService {

    private static final String TAG = "GCMIntentService";

    public GCMIntentService() {
        super(SENDER_ID);
    }

    /**
     * Method called on device registered
     **/
    @Override
    protected void onRegistered(Context context, String registrationId) {
        //Log.i(TAG, "Device registered: regId = " + registrationId);
       displayMessage(context, "Your device registred with GCM");
       // Log.d("NAME", MainActivity.name);
        ServerUtilities.register(context, MainActivity.name, MainActivity.email, registrationId, MainActivity.flat, MainActivity.admin, MainActivity.dummy);
    }

    /**
     * Method called on device un registred
     * */
    @Override
    protected void onUnregistered(Context context, String registrationId) {
        Log.i(TAG, "Device unregistered");
        displayMessage(context, getString(R.string.gcm_unregistered));
        ServerUtilities.unregister(context, registrationId);
    }

    /**
     * Method called on Receiving a new message
     * */
    @Override
    protected void onMessage(Context context, Intent intent) {
        Log.i(TAG, "Received message");
        String message = intent.getExtras().getString("price");

        displayMessage(context, message);
        // notifies user
        generateNotification(context, message);
    }

    /**
     * Method called on receiving a deleted message
     * */
    @Override
    protected void onDeletedMessages(Context context, int total) {
        Log.i(TAG, "Received deleted messages notification");
        String message = getString(R.string.gcm_deleted, total);
        displayMessage(context, message);
        // notifies user
        generateNotification(context, message);
    }

    /**
     * Method called on Error
     * */
    @Override
    public void onError(Context context, String errorId) {
        Log.i(TAG, "Received error: " + errorId);
        displayMessage(context, getString(R.string.gcm_error, errorId));
    }

    @Override
    protected boolean onRecoverableError(Context context, String errorId) {
        // log message
        Log.i(TAG, "Received recoverable error: " + errorId);
        displayMessage(context, getString(R.string.gcm_recoverable_error,
                errorId));
        return super.onRecoverableError(context, errorId);
    }

    /**
     * Issues a notification to inform the user that server has sent a message.
     */
    private static void generateNotification(Context context, String message) {
        int icon = R.drawable.ic_launcher;
        long when = System.currentTimeMillis();
        NotificationManager notificationManager = (NotificationManager)
                context.getSystemService(Context.NOTIFICATION_SERVICE);
        Notification notification = new Notification(icon, message, when);

        String title = context.getString(R.string.app_name);

        Intent notificationIntent = new Intent(context, MainActivity.class);
        // set intent so it does not start a new activity
        notificationIntent.putExtra("message", message);

        PendingIntent intent = PendingIntent.getActivity(context, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT );

        notification.setLatestEventInfo(context, title, message, intent);
        notification.flags |= Notification.FLAG_AUTO_CANCEL;

        // Play default notification sound
        notification.defaults |= Notification.DEFAULT_SOUND;

        //notification.sound = Uri.parse("android.resource://" + context.getPackageName() + "your_sound_file_name.mp3");

        // Vibrate if vibrate is enabled
        notification.defaults |= Notification.DEFAULT_VIBRATE;
        notificationManager.notify(0, notification);      

    }

}

Manifest

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

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="19" />
    <!-- GCM connects to Internet Services. -->
    <uses-permission android:name="android.permission.INTERNET" />

    <!-- 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.tromto.flat.permission.C2D_MESSAGE"
        android:protectionLevel="signature" />

    <uses-permission android:name="com.tromto.flat.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" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".RegisterActivity"
            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=".MainActivity"

            android:configChanges="orientation|screenSize"
            android:label="@string/app_name" >
        </activity>
        <!-- Login Activity -->
        <activity
            android:name=".LoginActivity"
            android:label="Login Account" >
        </activity>
        <activity
            android:name=".SearchableActivity"
            android:label="@string/title_activity_searchable"
            android:configChanges="orientation|screenSize" >
        </activity>
        <activity
            android:name=".FlatListActivity"
            android:label="@string/title_activity_flat_list"
            android:configChanges="orientation|screenSize" >
        </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.tromto.flat" />
            </intent-filter>
        </receiver>

        <service android:name=".GCMIntentService" />

        <activity
            android:name=".MsgToflatActivity"
            android:label="@string/title_activity_msg_toflat"
            android:configChanges="orientation|screenSize" >
        </activity>
        <activity
            android:name=".RegisteradminActivity"
            android:label="@string/title_activity_registeradmin" >
        </activity>
    </application>

</manifest>

解决方案

Update the TextView after you initialize it

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

As you are making notification and putting the value with the key "message", so you need to retrieve the value though the same key "message"

lblMessage.append("New Message: "+ i.getStringExtra("message") + "\n"); 

这篇关于从通知栏的GCM通知消息将不会在活动中显示,如果该应用程序尚未启动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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