【问题标题】:How to finish the activity in IntentService in android?如何在 android 中完成 IntentService 中的活动?
【发布时间】:2015-12-26 14:35:53
【问题描述】:

我正在使用 GCMIntentService 类扩展 IntentService 来获取通知,同时单击通知我可以启动我的活动。它工作,但我无法完成我的活动,所以我面临着后退按钮按下问题。

* 下面的代码 *

Intent resultIntent = new Intent(this, MainActivity.class);
        resultPendingIntent = PendingIntent.getActivity(this, 0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        // Set pending intent
        mNotifyBuilder.setContentIntent(resultPendingIntent);

在此代码中,在启动 MainActivity 并按两次后退按钮时,只有它存在于应用程序中,因为我无法在通知点击中完成活动。所以请帮助我如何完成 GCMIntentService 类中的活动。

【问题讨论】:

  • 我想到的第一件事,我并不是说这是最好的解决方案,在您的活动中注册广播接收器(仅由您的活动确认的自定义接收器),然后从您的服务(以及每当想要关闭您的活动时)使用此自定义意图进行广播。并在收到此意图后关闭您的活动。
  • 请给出任何想法和参考。
  • 我要在这里添加一个代码作为答案,我现在要把它从我的项目中拿出来。
  • 当我修改它以满足您的要求时,请务必再次检查我的答案

标签: android google-cloud-messaging android-intentservice


【解决方案1】:

所以请帮助我如何完成 GCMIntentService 类中的活动。

这不是正确的答案。您想要的是确保任务对用户有意义,就后台堆栈而言。根据您应用的导航,这可能涉及将以下一组标志添加到您的resultIntent

  • Intent.FLAG_ACTIVITY_REORDER_TO_FRONT(如果要将其他活动保留在后台堆栈中,但要确保只有一个 MainActivity 实例)

  • Intent.FLAG_ACTIVITY_CLEAR_TASK Intent.FLAG_ACTIVITY_NEW_TASK(如果你想有一个单独的专用任务来处理这个Notification,不理会任何现有任务;这也需要android:taskAffinity="" in清单中的<activity> 元素)

【讨论】:

    【解决方案2】:

    在您的活动创建中或任何时候,您都将注册您的自定义广播接收器:

    registerReceiver(closeMyActivity, new IntentFilter("ex.my_app_name.my_custom_broadcast"));
    

    您将在此处接收自定义广播以结束您的活动。

    private final BroadcastReceiver closeMyActivity = new BroadcastReceiver() 
                {
                    @Override
                    public void onReceive(Context context, Intent intent) 
                    {
                        if (null != intent && intent.hasExtra("aCloseActivity")) {
                            if(intent.getBooleanExtra("aCloseActivity", false)){
                             // Here you can close your activity                                 
                             }
                         }
                    }
                };
    

    当广播接收器被销毁时,不要忘记在你的 Activity 中注销它:

    unregisterReceiver(closeMyActivity);
    

    然后从您的服务发送广播:

    getApplicationContext().sendBroadcast(new Intent("ex.my_app_name.my_custom_broadcast").putExtra("aCloseActivity", true));
    

    希望对你有帮助,但也等着看其他回复,或许有更好的解决方案。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-04
      • 1970-01-01
      相关资源
      最近更新 更多