gpt4 book ai didi

android - AsyncTask 不在 onCreate() 中执行

转载 作者:行者123 更新时间:2023-11-29 14:39:34 24 4
gpt4 key购买 nike

我希望如果我的应用程序第一次启动,它应该从网络下载图像并将该图像存储在 Device/Emulator 中,从 Device/Emulator 应该显示在 ImageView 。我试过这种方式:

ImageView myImgView;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

myImgView = (ImageView) findViewById(R.id.imageView1);

new MyAsnyc();
Log.d(MY_TAGT, "AsyncTask Executed.....");

}
private class MyAsnyc extends AsyncTask<Void, Void,Void>{
public File file ;
InputStream is;
private Bitmap bitmap;
protected void doInBackground() throws IOException{

File path = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES);
file = new File(path, "DemoPicture.jpg");
try{
// Make sure the Pictures directory exists.
path.mkdirs();

URL url = new URL(BASE_URL);
/* Open a connection to that URL. */
URLConnection ucon = url.openConnection();

/*
* Define InputStreams to read from the URLConnection.
*/
is = ucon.getInputStream();

OutputStream os = new FileOutputStream(file);
byte[] data = new byte[is.available()];
is.read(data);
Log.i(MY_TAGT, "Picture is readable........");
os.write(data);
Log.i(MY_TAGT, "Picture is Saved........");
is.close();
os.close();

}
catch (IOException e) {
Log.d("ImageManager", "Error: " + e);
}
}
@Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub

try {
doInBackground();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

return null;
}
protected void onPostExecute(){

try{
// Tell the media scanner about the new file so that it is
// immediately available to the user.

MediaScannerConnection.scanFile(null,
new String[] { file.toString() }, null,
new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
Log.i("ExternalStorage", "Scanned " + path + ":");
Log.i("ExternalStorage", "-> uri=" + uri);
}
});
}
catch (Exception e) {
// TODO: handle exception

}

/*Here I want to set this image in ImageView*/

bitmap = BitmapFactory.decodeFile(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).toString()+"/DemoPicture.jpg");
myImgView.setImageBitmap(bitmap);
}
}

但是这样MyAsync类没有被执行,请告知如何执行。

编辑这是我的日志

enter image description here

最佳答案

使用execute来调用它。

new MyAsnyc().execute();

关于android - AsyncTask 不在 onCreate() 中执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15271245/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com