gpt4 book ai didi

android - 在 doInBackground 中运行的异步任务 2 函数

转载 作者:太空狗 更新时间:2023-10-29 16:23:01 25 4
gpt4 key购买 nike

你好,我想使用异步任务,这是我的骨架代码:

public class MyActivity extends Activity {
private ProgressDialog pd = null;
private Object data = null;

public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

// Show the ProgressDialog on this thread
this.pd = ProgressDialog.show(this, "Working..", "Downloading Data...", true, false);

// Start a new thread that will download all the data
new DownloadTask().execute("Any parameters my download task needs here");
}

private class DownloadTask extends AsyncTask<String, Void, Object> {
protected Object doInBackground(String... args) {
Log.i("MyApp", "Background thread starting");

// This is where you would do all the work of downloading your data

return "replace this with your data object";
}

protected void onPostExecute(Object result) {
// Pass the result data back to the main activity
MyActivity.this.data = result;

if (MyActivity.this.pd != null) {
MyActivity.this.pd.dismiss();
}
}
}

我的问题是,如果我的 InBackground 函数同时返回字符串数组和位图,那么 AsyncTask 中的第三个参数应该是什么?有什么帮助吗?

最佳答案

您可以使用 Bundle(参见 http://developer.android.com/reference/android/os/Bundle.html)。所以你的 AsyncTask 看起来像......

public class MyTask extends AsyncTask<Void, Void, Bundle> 
{
@Override
protected Bundle doInBackground(Void... arg)
{
Bundle bundle = new Bundle();
bundle.putParcelable("Bitmap", bitmap);
bundle.putString("String", string);

return bundle;
}
protected void onPostExecute(Bundle bundle)
{
Bitmap bitmap = bundle.getParcelable("Bitmap");
String string = bundle.getString("String");
}
}

位图是可打包的,但除了最小的位图,您很可能会遇到运行时错误。所以你可能需要把它变成一个字节数组然后再变回去,就像这样……

ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
byte[] bytes = baos.toByteArray();
Bundle bundle = new Bundle();
bundle.putByteArray("Bytes", bytes);

还有这个……

byte[] bytes = bundle.getByteArray("Bytes");
Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length, new BitmapFactory.Options());

关于android - 在 doInBackground 中运行的异步任务 2 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9708416/

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