1

我有一个在 Google Nexus(Android 4.2)中成功运行的代码。但是当我昨天在 android 2.3.5 的较低版本中尝试它时,它会抛出一个异常。

请帮我解决同样的问题。

细节。

我创建了一个类DownloadHelper,可以帮助我将文件从互联网下载到手机中的某个位置。这个类实习生调用一个子类DownloadFile extends AsyncTask。当我尝试创建它的对象时DownloadFile会引发异常。

下面是代码DownloadHeper

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;

import org.andengine.entity.text.Text;
import org.andengine.ui.activity.BaseGameActivity;

import com.gretrainer.gretrainer.StartingScreen;

import android.os.AsyncTask;
import android.os.Environment;
import android.util.Log;

public class DownloadHelper {
    public void loadFile(String url,Text loadingT,BaseGameActivity activity1,String _filename,int _tag){
        DownloadFile downloadFile;
        try {
            downloadFile = new DownloadFile();
            loadingText = loadingT;
            activity = activity1;
            downloadFile.execute(url);
            StartingPercent = 0;
            EndingPercent = 100;
            filename = _filename;
            tag = _tag;
        } catch (Exception e) {
            Log.d("exec",e.getLocalizedMessage());
        }



    }

    private int tag;
    private String filename;
    private float StartingPercent;
    private float EndingPercent;
    private BaseGameActivity activity;
    private Text loadingText;
    private class DownloadFile extends AsyncTask<String,Integer,String>{

        public DownloadFile(){

        }

        @Override
        protected String doInBackground(String... sUrl) {
            try {
                URL url = new URL(sUrl[0]);
                URLConnection connection = url.openConnection();
                connection.connect();
                // this will be useful so that you can show a typical 0-100% progress bar
                int fileLength = connection.getContentLength();

                // download the file
                InputStream input = new BufferedInputStream(url.openStream());
                OutputStream output = new FileOutputStream(Environment.getExternalStorageDirectory().toString().concat(File.separator + filename));


                byte data[] = new byte[1024];
                long total = 0;
                int count;
                while ((count = input.read(data)) != -1) {
                    total += count;
                    // publishing the progress....
                    publishProgress((int) (total * 100 / fileLength));
                    output.write(data, 0, count);
                }

                output.flush();
                output.close();
                input.close();
                StartingScreen act = (StartingScreen)activity;
                act.onLoadFileComplete(tag);
            } catch (Exception e) {
                String message = e.getLocalizedMessage();
                Log.d("hello",message);
            }
            return null;
        }

          @Override
            protected void onPreExecute() {
                super.onPreExecute();
            }

            @Override
            protected void onProgressUpdate(Integer... progress) {
                super.onProgressUpdate(progress);
                activity.runOnUiThread(new Runnable(){

                    @Override
                    public void run() {
                        // TODO Auto-generated method stub

                    }

                });
                //loadingText.setText(StartingPercent + ((EndingPercent - StartingPercent) / 100) * progress[0] + "%");
            }


    }
}

当它执行行时抛出异常 downloadFile = new DownloadFile();

Exception 的详细信息如下所示。

UpdateThread interrupted. Don't worry - this EngineDestroyedException is most likely expected!
org.andengine.engine.Engine$EngineDestroyedException

它回到最后一行onCreateScene。但应用程序被冻结。它在新的android os(4.2)中运行良好

请检查

从异常 04-07 17:46:42.498 开始的整个日志:W/dalvikvm(2552): Exception Ljava/lang/RuntimeException; 初始化 Landroid/os/AsyncTask 时抛出;04-07 17:47:06.891:E/AndEngine(2552):StartingScreen.onPopulateScene 失败。@(线程:'GLThread 11')04-07 17:47:06.891:E/AndEngine(2552):java.lang.ExceptionInInitializerError 04-07 17:47:06.891:E/AndEngine(2552):在 com.gretrainer .gretrainer.AppHelpers.DownloadHelper.loadFile(DownloadHelper.java:24) 04-07 17:47:06.891: E/AndEngine(2552): at com.gretrainer.gretrainer.StartingScreen.onPopulateScene(StartingScreen.java:102) 04- 07 17:47:06.891: E/AndEngine(2552): 在 org.andengine.ui.activity.BaseGameActivity$2.onCreateSceneFinished(BaseGameActivity.java:154) 04-07 17:47:06.891: E/AndEngine(2552):在 com.gretrainer.gretrainer.StartingScreen.onCreateScene(StartingScreen.java:

4

1 回答 1

4

这只是一个猜测,但有几个Exceptions导致您没有正确执行的结论AsyncTask(请参阅Can't create handler inside thread that has not called Looper.prepare()。我不是建议您Looper.prepare()自己调用,而是Asynctask在另一个线程上执行。所以而不是

downloadFile = new DownloadFile();
loadingText = loadingT;
activity = activity1;
downloadFile.execute(url);
StartingPercent = 0;
EndingPercent = 100;
filename = _filename;
tag = _tag;

尝试这样的事情(顺便说一句,您正在访问任务中的一些变量,应该更早地初始化):

loadingText = loadingT;
activity = activity1;   
StartingPercent = 0;
EndingPercent = 100;
filename = _filename;
tag = _tag; 
runOnUiThread(new Runnable() {
    @Override
    public void run() {
        new DownloadFile().execute(url);
    }
});

我对AsyncTasks 的经验是,它们不应该在 normal 上运行Update Thread,因为该线程仅用于刷新屏幕,因此请尝试在 s 上运行它UIThread(因为您没有直接从任务中显示数据)。

于 2013-04-08T01:28:02.613 回答