如果未完成AsyncTask,如何设置固定时间

时间:2018-01-05 17:41:31

标签: android android-asynctask

我有一个asynctask,如果异步花费太长时间,我正在寻找等待,我下载数据库的一些数据,但我不想让用户围绕progressdialog循环,我想设置一个固定的时间,让我说我下载文件但是要永远,所以我告诉用户,"嘿,检查你的网络连接,然后再试一次"我想用计时器做这件事,但我有点卡住了,这就是我做asynctask的地方

private class DownloadFilesTask extends AsyncTask<Void, Void, Void> {
             String s;
             public DownloadFilesTask(String s){
                 this.s = s;
             }

             @Override
             protected Void doInBackground(Void... voids) {
                 DownloadMethod(s);
                 return null;
             }
         }

所以,让我说我想要执行下载方法一段固定的时间,10或20秒,如果当时没有下载文件,我会向用户回复一条消息说他需要检查hes互联网。

5 个答案:

答案 0 :(得分:1)

您可以使用BroadcastReceiver收听您的互联网连接。这是一个例子:

public class NetworkControl extends BroadcastReceiver {

static boolean isConnected = false;

@Override
public void onReceive(final Context context, final Intent intent) {
    isNetworkAvailable(context);
}

private boolean isNetworkAvailable(Context context) {
    ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    if (connectivity != null) {
        NetworkInfo[] info = connectivity.getAllNetworkInfo();
        if (info != null) {
            for (int i = 0; i < info.length; i++) {
                if (info[i].getState() == NetworkInfo.State.CONNECTED) {
                    if(!isConnected){
                        isConnected = true;
                        Toast.makeText(context, "You're online!!", Toast.LENGTH_LONG).show();
                    }
                    return true;
                }
            }
        }
    }
    isConnected = false;
    Toast.makeText(context, "Connection interrupted.", Toast.LENGTH_LONG).show();
    return false;
}
}

您还需要AndroidManifest.xml

中的一些权限
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />

然后在您的活动中启动该服务。

    IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
    receiver = new NetworkControl();
    registerReceiver(receiver, filter);

答案 1 :(得分:1)

如果您使用HttpURLConnection下载文件,那么您可以执行以下操作:

private class DownloadFilesTask extends AsyncTask<String, Integer, Integer> {


    @Override
    protected Integer doInBackground(String... ulr) {
        URL url = null;
        try {
            url = new URL(ulr[0]);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setConnectTimeout(2000); //Timeout
            //...Other codes for downloading
            return 101;
        } catch (java.net.SocketTimeoutException e) {
            return 102;
        } catch (MalformedURLException e) {
            return 103;
        } catch (IOException e) {
            return 104;
        }
    }

    @Override
    protected void onPostExecute(Integer result) {
        if(result == 102) {
            Toast.makeText(getApplicationContext(), "Connection Timeout.", Toast.LENGTH_LONG).show();
        }
    }
}

答案 2 :(得分:1)

首先我要说的是,在运行下载任务时,向check your internet connectionno internet connection用户发送消息并不是一个好习惯。 YourBackgroundTask task = new YourBackgroundTask(); task.execute(); new Handler().postDelayed(new Runnable() { @Override public void run() { if (task.getStatus == AsyncTask.Status.RUNNING){ Toast.makeText(this, "Please wait...", Toast.LENGTH_SHORT).show(); } } },20000); // time in milisecond 。因为在这种情况下,如果用户关闭然后在网络连接上关闭,那么您的下载任务将再次重新启动并重新开始。所以,避免这类消息。

现在关于解决方案,执行后台任务后,您可以检查您的任务是否正在运行或已完成。如果花费太多时间 然后显示一条消息。例如,

<div class="row">
    <div class="col-md-6">
        <div class="form-group form-group-default">
            <label class="label-black">@Html.LabelFor(g => g.Street)</label>
            <input asp-for="Street" class="form-control" />
        </div>
    </div>
</div>

如果你想重复这个,你可以轻松地重新运行处理程序。

答案 3 :(得分:1)

如果有效,可以试试这个基本想法

private class DownloadFilesTask extends AsyncTask<Void, Integer, Void> implements TimerTask{
    String s;
    Timer timer;
    Object objectResult;

    public DownloadFilesTask(String s){
        this.s = s;
        timer = new Timer();
    }

    @Override
    protected Void doInBackground(Void... voids) {
        objectResult = DownloadMethod();
        return null;
    }

    private Object DownloadMethod() {
        //here implement the download logic and return the object
        return null;
    }

    @Override
    protected void onProgressUpdate(Integer... progress) {
        // your code to update progress
    }

    public void checkProgress(){
       timer.schedule(this,2000);
    }

    @Override
    public void run() {
        if (objectResult!=null){
            //download completed 
        }else{
            //show dialog here and schedule a task again
            timer.schedule(this,2000);
        }
    }
}

答案 4 :(得分:1)

您可以使用处理程序在一定时间后运行并维护一个布尔标志,您可以在异步任务的postExecute函数中更新。

在您的活动/片段类中:

new Handler().postDelayed(new Runnable(){
          public void run(){
                   //Check whether the flag has been updated or not
             },1000)