我正在使用Asynctask在我的Android应用程序中下载文件。由于文件通常很大,因此我在后台开始下载文件。没有进度条或显示的任何内容,因此用户可以在下载过程中访问应用程序的其他部分。
文件下载完成后,我想通知用户他的文件已成功下载。
使用onPostexecute()方法会产生问题,因为下载过程开始时用户不再处于同一活动上。结果,由于上下文存在问题,因此无法使用onPostExecute()的“警报”对话框和通知。
我已经在我的Asynctask的代码下面粘贴了。因此,请提出一种解决此问题的方法。
class DownloadProcess extends AsyncTask<Void,Void,Void>{
Context cxt;
public DownloadProcess(Context context) {
cxt=context;
}
@Override
protected Void doInBackground(Void... arg0) {
try {
String fileurl="http://www.bigfiles/" + filenm;
URL url = new URL(fileurl);
HttpURLConnection c = (HttpURLConnection) url.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
Path = Environment.getExternalStorageDirectory() + "/download/";
File pth=new File(Path);
File file = new File(pth,filenm);
FileOutputStream fos = new FileOutputStream(file);
InputStream is = c.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = is.read(buffer)) != -1) {
fos.write(buffer, 0, len1);
}
fos.close();
is.close();
} catch (IOException e) {
Log.d("amit", "Error: " + e);
}
return null;
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (((Activity) AppDet.this).isFinishing() == false) {
AlertDialog.Builder builder = new AlertDialog.Builder(AppDet.this);
builder.setMessage("The app download is complete. Please check " +Path+ " on your device and open the " + filenm+ " file downloaded");
builder.setCancelable(true);
builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
MediaPlayer md=MediaPlayer.create(AppDet.this, R.raw.ding);
md.start();
}
else {
//Not sure what to do here
}
}
最佳答案
如@QAMAR所指出的,将通知(不是警报弹出窗口,这是糟糕的UX)与应用程序上下文一起使用。
但是,在我们的应用程序中,我们显示了来自android.app.Service
的通知,该通知管理着一部分任务(我们不会直接从AsyncTask向UI添加结果-当您的活动生命周期即将结束时,它们很容易被杀死。 ,则服务可以更明确地控制该服务及其子任务何时可以终止)
final NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
.setContentIntent(pendingIntent)
.setSmallIcon(<some drawable>)
.setWhen(System.currentTimeMillis())
.setAutoCancel(true)
.setContentTitle(<some internationalised message>)
.setContentText(<some internationalised subtitle>);
// Send the notification.
((NotificationManager) getSystemService(NOTIFICATION_SERVICE)).notify(<notification id>, builder.getNotification());
如果您需要异步任务的结果来影响您正在使用的活动,那么就需要绑定服务。我今天将要深入研究这些内容,因此会将我的任何见解发回。