在UI膨胀之前,服务冻结活动

问题描述 投票:1回答:1

我有一个长期运行的服务,它被绑定到一个加载屏幕上。我知道这是次优的,但AsyncTask对我来说并不奏效,因为它一直在运行(数据泄露),即使在Activity被强行结束后也是如此。不管怎样,想了解这里发生了什么。基本的布局永远不会出现(黑屏),但服务却能如期运行。当然,一个(绑定的)服务在Activity线程上生存和运行。但是,为什么它不会膨胀UI 第一onCreate会在bindService之前被调用,而且正如日志所确认的那样。

 ServiceConnection _connection = new ServiceConnection() {
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            _service = myService.Stub.asInterface(iBinder);
            runStuff();
        }

        public void onServiceDisconnected(ComponentName componentName) {
            _service = null;
        }

@Override
    protected void onStart() {
        super.onStart();
        Intent serviceIntent = new Intent();
        serviceIntent.setPackage(myService.class.getPackage().getName());
        serviceIntent.setAction(myService.class.getName() + ".ACTION_BIND");
        bindService(serviceIntent, _connection, BIND_AUTO_CREATE);
    }
 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_loadingscreen);
        findViewsById();
        setDefaultVisibility();
    [...]

编辑:作为额外的信息,即使使用AsyncTask,显示加载屏幕(非常简单)也需要很长的时间。但即使是那个奇怪的延迟也应该没有关系,因为在那之前服务不应该被绑定。我错过了什么?

编辑2:我添加了时间戳。服务会立即启动。如果服务在AsyncTask中,UI仍然需要同样的时间来加载。从上一个活动的按钮点击到onPostCreate需要大约400ms,而不是我在UI上看到的3-4秒。AsyncTask确实按照预期更新了UI,但除了onProgressUpdate,在onCreate之后或任何服务调用之前,没有任何与UI相关的内容。是什么原因导致了这样的延迟?我甚至没有在同一个应用程序中对DB和GUI要求很高的活动上出现这种情况。

android android-service-binding
1个回答
0
投票

把你的代码放在一个单独的方法中,我不知道这样做是否可行,但我有过这样的成功案例。

private void start(){
 Intent serviceIntent = new Intent();
        serviceIntent.setPackage(myService.class.getPackage().getName());
        serviceIntent.setAction(myService.class.getName() + ".ACTION_BIND");
        bindService(serviceIntent, _connection, BIND_AUTO_CREATE);
}

然后在您的oncreate中启动该方法,服务将在创建后启动,如

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

            setContentView(R.layout.activity_loadingscreen);
            findViewsById();
            setDefaultVisibility();
start();
        [...]
© www.soinside.com 2019 - 2024. All rights reserved.