Android 如何为我的加载活动添加超时

Android 如何为我的加载活动添加超时,android,performance,Android,Performance,启动时,我的android应用程序使用异步任务从远程服务器加载一些图像。有时,当连接太弱时,需要很长时间才能加载,而且不是很好。 如何将超时添加到此任务,以便如果活动在10秒后无法加载图像,例如,用户将收到错误消息使用异步任务,然后显示进度条10秒。如果超过10秒,则显示日志消息 你可以试试这样的东西 private static final int MAX_ATTEMPTS = 5; static class Task extends AsyncTask<String,

启动时,我的android应用程序使用异步任务从远程服务器加载一些图像。有时,当连接太弱时,需要很长时间才能加载,而且不是很好。
如何将超时添加到此任务,以便如果活动在10秒后无法加载图像,例如,用户将收到错误消息

使用
异步任务
,然后显示进度条10秒。如果超过10秒,则显示日志消息


你可以试试这样的东西

    private static final int MAX_ATTEMPTS = 5;

    static class Task extends AsyncTask<String, Integer, Integer> {
        protected Integer doInBackground(String... vals) {
            try {
                long backoff = BACKOFF_MILLI_SECONDS + random.nextInt(1000);
                for (int i = 1; i <= MAX_ATTEMPTS; i++) {
                    Log.d(TAG, "Attempt #" + i + " to server connection");
                    try {
                        //DO STUFF
                    } catch (IOException e) {
                        if (i == MAX_ATTEMPTS) {
                            break;
                        }
                        try {
                            Log.d(TAG, "Sleeping for " + backoff + " ms before retry");
                            Thread.sleep(backoff);
                        } catch (InterruptedException e1) {
                            Log.d(TAG, "Thread interrupted: abort remaining retries!");
                            Thread.currentThread().interrupt();
                            return 400;
                        }
                        // increase backoff exponentially
                        backoff *= 2;
                    }
                }

            } catch (Exception e) {
                Log.e(TAG, "ERROR", e);
            }
            return 400;
        }

        protected void onPostExecute(Integer success) {

        }
    }
private static final int MAX_尝试次数=5;
静态类任务扩展了异步任务{
受保护的整数doInBackground(字符串…VAL){
试一试{
长退避=退避毫秒+随机.nextInt(1000);

对于(int i=1;i如果您使用.net web服务从服务器获取数据,请使用以下命令:

HttpTransportSE aht1 = new HttpTransportSE(URL, 60000);
其中,URL是您的Web服务连接URL。在这里,它等待1分钟以获取响应。之后,它抛出超时错误