0

我需要在完成从 url 下载图像后开始我的意图,而不需要应用程序本身的用户采取任何行动。

这是我的活动,它首先会下载图像,然后会启动意图。

    //download image then start decod intent
public  void download(View v)
{
   //first download image 
    new MyAsnyc().execute();

      //then start this intent
      final Handler handler=new Handler();
     final Runnable r = new Runnable()
     {
         public void run() 
         {
             { 
                 Intent intent1 = new Intent(Test_PROJECTActivity.this, DecodeActivity.class);
                File path = Environment
                        .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
                File file = new File(path, "DemoPictureX.png");
                Log.d("file", file.getAbsolutePath());
                intent1.putExtra("file", file.getAbsolutePath());
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                startActivity(intent1);
                }
         }
     };
 handler.postDelayed(r, 5000);
  }

MyAsnyc 做得很好并且可以正确下载图像,但是代码的第二部分在下载图像时启动了意图,因此图像将被损坏,从而导致异常。

一旦图像准备好并完成下载,如何使意图开始?

4

3 回答 3

1

我认为您应该使用具有onPostExecuteonPreExecute等功能的AsyncTask。您可以在下载前后轻松控制内容。

于 2012-07-25T13:41:10.013 回答
1
 public class YourClassName extends AsyncTask<String, Void, String > {

       protected void onPreExecute() { }

       protected String doInBackground(String... params) {}

       protected void onPostExecute(String result) {}
}

在方法中完成所有下载内容并从方法doInBackground开始一个新的,如下所示:IntentonPostExecute

Intent i = new Intent(ClassName.this, TheClassToStart.class);
context.startActivity(i); 

如果您想将图像放入新活动中,请执行以下操作:

i.putExtras(...)

希望这有帮助!

关于没有封闭实例的问题

如果您从另一个活动启动 AsyncTask,请将此活动传递contextAsyncTask类。

public class YourClassName extends AsyncTask<String, Void, String > {
    Context mContext;

    public YourClassName(Context mContext) {
      this.mContext = mContext;
    }

    //other methods
}

从你的第一个Activity,调用以AsyncTask这种方式扩展的类:

new YourClassName(getApplicationContext()).execute(""); 
于 2012-07-25T14:06:12.333 回答
0

您应该将Intent起始代码放在AsyncTask'sonPostExecute()方法中。这将确保代码在正确的时间执行,并使异常处理更容易。希望这可以帮助。

于 2012-07-25T13:41:27.410 回答