【问题标题】:Best way to stop a Service bind with a ServiceConnection in an Activity in Android?在 Android 的 Activity 中停止服务与 ServiceConnection 绑定的最佳方法是什么?
【发布时间】:2011-10-28 09:24:27
【问题描述】:

我有一个在我的 Activity 中与 ServiceConnection 绑定的服务。 该服务在创建 Activity 时启动,并在我的 BroadcastReceiver 类中停止并且效果很好。现在,我想在一段时间后停止服务。在我的服务类中尝试 TimerTask,但似乎无法正常工作。

任何建议或解决方案将不胜感激。

谢谢。

【问题讨论】:

    标签: android service android-activity broadcastreceiver android-intent


    【解决方案1】:

    计时器也被视为独立的线程。所以当您尝试停止服务时,可能会更改上下文。我的解决方案是获取当前服务的 Pid 并使用该 Pid 终止服务。 android:process 属性将在 androidmanifest.xml 中指定。

    进程进程 = Runtime.getRuntime().exec("kill pid"); InputStream 是 = process.getInputStream();

    这段代码运行良好。试一次

    【讨论】:

      【解决方案2】:

      在您的应用中声明一个静态变量:

      static Intent local_Intent;
      

      在创建应用时为服务分配一个新的 Intent 并绑定到 local_Intent:

      public void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.main);
          local_Intent = new Intent(this, yourAppService.class);
      }
      

      对 local_Intent 的赋值会被记住,因为 local_Intent 是静态的 当你想在你的 App 中启动服务时

       startService(local_Intent);
      

      当您想停止应用中的服务时

       stopService(local_Intent);
      

      【讨论】:

        猜你喜欢
        • 2021-07-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多