Android 特别工作组关闭
任何人都知道为什么AsyncTask强制关闭当我尝试在后台解压文件时,它在不使用AsyncTask时工作,因此我不确定我做错了什么:Android 特别工作组关闭,android,android-asynctask,Android,Android Asynctask,任何人都知道为什么AsyncTask强制关闭当我尝试在后台解压文件时,它在不使用AsyncTask时工作,因此我不确定我做错了什么: public class UnzipFile extends AsyncTask<Void, Integer, String> { String zipFile = Environment.getExternalStorageDirector
public class UnzipFile extends AsyncTask<Void, Integer, String> {
String zipFile = Environment.getExternalStorageDirectory() + "/download/" + mixtapefilename;
String unzipLocation = Environment.getExternalStorageDirectory() + "/download/";
@Override
protected void onPreExecute() {
Toast toast = Toast.makeText(getApplicationContext(), "Unzipping...", Toast.LENGTH_SHORT);
toast.show();
/* Intent intent = new Intent();
final PendingIntent pendingIntent = PendingIntent.getActivity(Download.this, 0, intent, 0);
// configure the notification
notification = new Notification(R.drawable.zipicon, "Unzipping...", System
.currentTimeMillis());
notification.flags = notification.flags | Notification.FLAG_ONGOING_EVENT;
notification.setLatestEventInfo(getApplicationContext(), "Please Wait", "Unzipping...", pendingIntent);
notificationManager2.notify(1, notification);*/
}
@Override
protected String doInBackground(Void... params) {
Decompress d = new Decompress(zipFile, unzipLocation);
d.unzip();
return "success";}
@Override
protected void onPostExecute(String result) {
Toast toast = Toast.makeText(getApplicationContext(), "Download Complete", Toast.LENGTH_SHORT);
toast.show();
File oldzip = new File(zipFile);
boolean deleted = oldzip.delete();
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://"+ Environment.getExternalStorageDirectory())));
/*notificationManager2.cancel(1);*/
}
}
由于您使用的是AsynTask,因此无法与doInBackground()内的主UI线程通信(即显示toast消息) AsynTask期间与主UI线程通信的唯一方法是使用
onPreExcute()
或onPostExcute()
所以只要去掉这一行:
Toast toast = Toast.makeText(getApplicationContext(),"Download Complete", Toast.LENGTH_LONG);
很抱歉,我不同意,但是有几种方法可以从另一个线程在UI线程中执行代码: Activity.runOnUiThread(可运行) View.post(可运行) View.postDelayed(可运行,长)
您可以使用其中一个来发布将由UI线程执行的内容,而不管您当前在哪个线程中。但是,是的,你可以把它们拿走,用Log.d(String,String)代替(例如)UI线程是非线程安全的。所以在其他线程中访问UI线程是非常危险的。您必须通过
View.post()
method将您的消息发布到UI消息队列中,logcat出现了什么异常?谢谢,我在点击post后就发现了。很抱歉问了这个毫无意义的问题。
Toast toast = Toast.makeText(getApplicationContext(),"Download Complete", Toast.LENGTH_LONG);