简体   繁体   English

如何将我的服务转换为与AsyncTask一起运行?

[英]How do I convert my service to run with AsyncTask?

I'm trying to convert the things executed in my service to AsyncTask to make it better. 我试图将服务中执行的内容转换为AsyncTask,以使其更好。 However, I'm new to this concept and I've been having trouble setting it up (not knowing what to put where). 但是,我是这个概念的新手,在设置它时遇到了麻烦(不知道放在哪里)。 This service is executed on onHandleIntent once a button from MainActivity is pressed. 按下MainActivity的按钮后,将在onHandleIntent上执行此服务。

the part that should run in doInBackground() (collectData() gets the data usage info about apps in the phone): 应该在doInBackground()中运行的部分(collectData()获取有关手机中应用程序的数据使用情况信息):

    Utils.d("On Handle Inent Called -- Will collect Data");
    newStartTime = intent.getLongExtra("startTime",0);
    newEndTime = intent.getLongExtra("endTime",0);
    dataUsage = collectData();

the part that runs onPostExecute() (starts a new activity that lists the apps and their data usage): 运行onPostExecute()的部分(启动一个列出应用程序及其数据使用情况的新活动):

    isWifi = intent.getBooleanExtra("isWifi",true);
    Intent intentActivity = new Intent(this, DataDisplayActivity.class);
    intentActivity.putExtra("dataUsage",dataUsage.toString());
    intentActivity.putExtra("isWifi",isWifi);
    startActivity(intentActivity);

Can anyone help? 有人可以帮忙吗?

        new AsyncTask<Void, Void, Void>() {

            @Override
            protected Void> doInBackground(Void... params) {
                Utils.d("On Handle Inent Called -- Will collect Data");
                newStartTime = intent.getLongExtra("startTime",0);
               newEndTime = intent.getLongExtra("endTime",0);
               dataUsage = collectData();
               return null;
            }

            @Override
            protected void onPostExecute(Void void) {
                super.onPostExecute(showsForBucket);
                isWifi = intent.getBooleanExtra("isWifi",true);
                Intent intentActivity = new Intent(this, DataDisplayActivity.class);
                intentActivity.putExtra("dataUsage",dataUsage.toString());
                intentActivity.putExtra("isWifi",isWifi);
                startActivity(intentActivity);
            }
        }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM