【问题标题】:How to implement a service that runs only when the app is running?如何实现仅在应用程序运行时运行的服务?
【发布时间】:2013-08-31 01:26:56
【问题描述】:

该应用有一项服务,该服务必须检测应用运行的分钟数,并据此启动其他操作。

实现这一点的正确方法是什么?

我如何才能确保服务仅在应用程序在用户面前运行时才运行?

启动服务似乎很容易 - 只需在初始加载时启动它。但更难的部分是结束它。当用户在最后一个屏幕上按下返回按钮时,我不能结束它。当用户按下主屏幕或其他一些应用程序(如电话、viber 弹出窗口或...)占据屏幕时如何处理?

我尝试从其他主题 (How to start a android service from one activity and stop service in another activity?) 中获取建议,但这无法处理主页按钮或其他应用程序接管屏幕的情况。

该应用总共有大约 10 个活动。将此服务绑定到所有 10 个活动是否正确,当所有活动都关闭时,该服务会自行关闭?

【问题讨论】:

    标签: android service


    【解决方案1】:

    为您的所有活动创建一个 BaseActivity。在 BaseActivity 中,执行以下操作:

    public class MyActivity extends Activity implements ServiceConnection {
    
        //you may add @override, it's optional
        protected void onStart() {
            super.onStart();
            Intent intent = new Intent(this, MyService.class);
            bindService(intent, this, 0);
        }
    
        //you may add @override, it's optional
        protected void onStop() {
            super.onStop();
            unbindService(this);
        }
    
        public void onServiceConnected(ComponentName name, IBinder binder) {};
        public void onServiceDisconnected(ComponentName name) {};
    
        /* lots of other stuff ... */
    }
    

    您的 BaseActivity 将需要实现 ServiceConnection 接口(或者您可以使用匿名内部类),但您可以将这些方法留空。

    在您的Service 类中,您需要实现onBind(Intent) 方法并返回一个IBinder。最简单的方法是这样的:

    public class MyService extends Service {
        private final IBinder localBinder = new LocalBinder();
    
        public void onCreate() {
            super.onCreate();
            // first time the service is bound, it will be created
            // you can start up your timed-operations here
        }
    
        public IBinder onBind(Intent intent) {
            return localBinder;
        }
    
        public void onUnbind(Intent intent) {
            // called when the last Activity is unbound from this service
            // stop your timed operations here
        }
    
        public class LocalBinder extends Binder {
    
            MyService getService() {
                return MyService.this;
            }
        }
    }
    

    【讨论】:

    • 感谢您为所有活动使用 Base 类,然后从每个活动中扩展它。
    • 嘿,unbindService(intent) 正在报告错误。此方法不接受Intent 作为参数,而是接受ServiceConnection。有什么想法吗?
    • 对不起,我的错。如果您的活动实现了 ServiceConnection,请改为传递它:unbindService(this);
    • 是的,我做到了:)。你能解释一下你的代码的最后一部分吗? getService() 返回的 LocalService 是什么?这也是一个错误吗?应该说MyService getService() 还是这是另一个自定义类?
    • 最后一条评论:你忘了把@Override放在onStartonStop上面吗?
    【解决方案2】:

    Bound Service是专门为这个目的而定义的,你可以给它绑定Activity,当所有的Activity都消失时,它也会被停止。该链接应包含足够的详细信息供您实施。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-06-17
      • 1970-01-01
      • 2021-10-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多