使用 AsyncTask 显示进度时下载文件时出错

Posted

技术标签:

【中文标题】使用 AsyncTask 显示进度时下载文件时出错【英文标题】:Error when downloading a file while using AsyncTask to show progress 【发布时间】:2017-04-29 07:29:11 【问题描述】:

我用这个Answer 开发了一个安卓应用程序来从互联网服务器下载文件。

但它给出了以下错误。

错误:预期

错误:类型的非法开始

任务“:app:compileDebugJavaWithJavac”执行失败。

编译失败;有关详细信息,请参阅编译器错误输出。

这个错误是针对代码行的,

downloadTask.execute("the url to the file you want to download");//execute method
//is highlighted in red in android studio and it says "Cannot resolve symbol execute"

这个答案被认为是正确的。我按照它所说的进行了操作,但仍然出现上述错误。我对这个环境很陌生,请帮助我。

 package com.kalusudu.dp.smarthike;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.PowerManager;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class RecentStories extends AppCompatActivity 

    @Override
    protected void onCreate(Bundle savedInstanceState) 
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_recent_stories);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() 
            @Override
            public void onClick(View view) 
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            
        );

        TextView text1 = (TextView) findViewById(R.id.TextView01);
        text1.setText("Knuckles mountain range is a part of the Hill Country of Sri Lanka which is also about 3000 Ft or 915 Mts. from sea level and covers an area of about 90 Sq. Milles or 234 Sq. Km of land extent.");

        TextView text2 = (TextView) findViewById(R.id.TextView02);
        text2.setText("Knuckles mountain range is a part of the Hill Country of Sri Lanka which is also about 3000 Ft or 915 Mts. from sea level and covers an area of about 90 Sq. Milles or 234 Sq. Km of land extent.");


        ImageView imageviewOne = (ImageView) findViewById(R.id.imageView01);
        imageviewOne.setOnClickListener(new View.OnClickListener() 
            public void onClick(View v) 
                Intent intent = new Intent(RecentStories.this,Cloud.class);
                //intent.setAction(Intent.ACTION_VIEW);
                //intent.addCategory(Intent.CATEGORY_BROWSABLE);
                //intent.setData(Uri.parse("http://m.facebook.com"));
                startActivity(intent);
            
        );
    

    @Override
    public boolean onCreateOptionsMenu(Menu menu) 
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_recent_stories, menu);
        return true;
    

    @Override
    public boolean onOptionsItemSelected(MenuItem item) 
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) 
            return true;
        

        return super.onOptionsItemSelected(item);
    

    // execute this when the downloader must be fired
    final DownloadTask downloadTask = new DownloadTask(RecentStories.this);
    downloadTask.execute("URL");//execute method
//is highlighted in red in android studio and it says "Cannot resolve symbol execute"




// usually, subclasses of AsyncTask are declared inside the activity class.
// that way, you can easily modify the UI thread from here
private class DownloadTask extends AsyncTask<String, Integer, String> 

    private Context context;
    private PowerManager.WakeLock mWakeLock;

    public DownloadTask(Context context) 
        this.context = context;
    

    @Override
    protected String doInBackground(String... sUrl) 
        InputStream input = null;
        OutputStream output = null;
        HttpURLConnection connection = null;
        try 
            URL url = new URL(sUrl[0]);
            connection = (HttpURLConnection) url.openConnection();
            connection.connect();

            // expect HTTP 200 OK, so we don't mistakenly save error report
            // instead of the file
            if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) 
                return "Server returned HTTP " + connection.getResponseCode()
                        + " " + connection.getResponseMessage();
            

            // this will be useful to display download percentage
            // might be -1: server did not report the length
            int fileLength = connection.getContentLength();

            // download the file
            input = connection.getInputStream();
            output = new FileOutputStream("/sdcard/file_name.extension");

            byte data[] = new byte[4096];
            long total = 0;
            int count;
            while ((count = input.read(data)) != -1) 
                // allow canceling with back button
                if (isCancelled()) 
                    input.close();
                    return null;
                
                total += count;
                // publishing the progress....
                if (fileLength > 0) // only if total length is known
                    publishProgress((int) (total * 100 / fileLength));
                output.write(data, 0, count);
            
         catch (Exception e) 
            return e.toString();
         finally 
            try 
                if (output != null)
                    output.close();
                if (input != null)
                    input.close();
             catch (IOException ignored) 
            

            if (connection != null)
                connection.disconnect();
        
        return null;
    

    @Override
    protected void onPreExecute() 
        super.onPreExecute();
        // take CPU lock to prevent CPU from going off if the user
        // presses the power button during download
        PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
        mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
                getClass().getName());
        mWakeLock.acquire();
    

    @Override
    protected void onProgressUpdate(Integer... progress) 
    

    @Override
    protected void onPostExecute(String result) 
        mWakeLock.release();
        if (result != null)
            Toast.makeText(context,"Download error: "+result, Toast.LENGTH_LONG).show();
        else
            Toast.makeText(context,"File downloaded", Toast.LENGTH_SHORT).show();
    

【问题讨论】:

把整个代码放在这里.... 好的,我会说的。 您之前的行中是否缺少; 或其他什么?检查你的代码,这是一个语法错误 没有上面的代码是可以的。 在上下文中使用弱引用,否则您将收到内存泄漏 【参考方案1】:

您添加了您的网址 - 还是仅添加了文本???

downloadTask.execute("the url to the file you want to download");

例如

downloadTask.execute("https://maps.awesome.com/maps/api/geocode/json");

【讨论】:

是的,我认为只要检查代码就足够了

以上是关于使用 AsyncTask 显示进度时下载文件时出错的主要内容,如果未能解决你的问题,请参考以下文章

水平进度条不适用于 Asynctask Android 下载文件?

带有 ListView Asynctask 的多下载器

如何让用户在生成文件时下载文件

在从服务调用的 asyncTask 中显示 alertDialog 时出错?

如何使用 DialogFragment 显示 AsyncTask 的进度 - 不使用 ProgressDialog

在 swift 3 中下载文件时,alamo fire 中的进度视图不会更新