【问题标题】:Run long task when onDestroy() is called调用 onDestroy() 时运行长任务
【发布时间】:2016-04-27 15:19:12
【问题描述】:

我想从片段的 onDestroy() 运行一个长操作任务。我的目标是调用网络调用来删除一些数据,以防用户通过从最近的应用程序中滑动来关闭应用程序。我希望在调用 onDestroy() 时启动一个意图。

目前,每当我尝试启动意图时,我都会在有机会操作调用之前失去上下文,因为 onDestroy() 已经杀死了我的应用程序。

我不想使用这个选项:Performing long running operation in onDestroy,因为这样运行线程不是正确的方法,而且看起来像是一种危险的黑客攻击。

从 Activity 的 onDestroy() 调用操作导致同样的错误。

当然,我不希望在 ui 线程上进行任何工作并“推迟” onDestroy() 直到我的操作完成。

只是为了清除,虽然 getContext() 不为空,但当我到达 SomeService 类时,上下文已经为空,因为发送意图是一个异步操作。

@Override
    public void onDestroy() {
         Intent intent = new Intent(getContext(), SomeService.class);
         getContext().startService(intent);
         super.onDestroy();
    }

【问题讨论】:

    标签: android android-lifecycle android-ondestroy


    【解决方案1】:

    我建议在 onCreate()Activity 期间启动和绑定服务,然后绑定服务,您可以轻松启动放置在 Service 中的清理实用程序,即您应该划分服务启动和清理启动.

    喜欢:

    //somewhere in onCreate()
    myServiceIntent = new Intent(this.getApplicationContext(), MyService.class);
    context.startService(myServiceIntent);
    context.bindService(myServiceIntent, serviceConnection, Context.BIND_AUTO_CREATE);
    

    然后在onDestroy()

    public void onDestroy() {
         myService.cleanup();
         super.onDestroy();
    }
    

    阅读更多关于service binding

    【讨论】:

      【解决方案2】:

      注意onDestroy() 不能保证被调用。

      使用应用程序上下文。

      只要绑定了任何组件,绑定服务就会一直存在,因此您的已启动服务的变体更好,只是不要忘记在作业完成后使用 stopSelf() 。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-08-13
        • 2022-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多