所以我有一个小应用程序可以从网上下载非常少量的数据。其他一切工作正常并正常下载,但当连接发生变化时(我失去了 wifi 范围)下载将无法完成并且用户无法获取他们的数据。
我知道如何处理这个问题。我在与 IntentService 通信的主 Activity 上设置了一个 BroadcastReceiver。当 IntentService 完成下载时,我会注销接收器。最重要的是,我设置了一个 Broadcastreceiver 来监听连接变化,如果连接可用,如果有连接,主 Activity 发送一个 Intent 来开始下载。看这里:
主要 Activity :
public class Sample extends Activity {
private BroadcastReceiver connectivityReceiver;
private ResponseReceiver receiver;
protected void onCreate(Bundle sis){
super.onCreate(sis);
IntentFilter intentFilter = new IntentFilter(
"android.net.conn.CONNECTIVITY_CHANGE");
registerReceiver(new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
if (Network.isOnline()) {
fireUpDownloadingIntent();
}
}
}, intentFilter);
}
public class ResponseReceiver extends BroadcastReceiver {
public static final String ACTION_RESP = "com.irough.intent.action.URL_LOADED";
@Override
public void onReceive(Context context, Intent intent) {
if(intent.getBooleanExtra(DLService.DOWNLOAD_COMPLETE, false) {
unRegisterReceiver(connectivityReceiver);
}
}
}
}
DLService.java:
public class DLService extends IntentService {
public static final String DOWNLOAD_COMPLETE = "dlc";
public DLService() {
super("DLService");
}
@Override
protected void onHandleIntent(Intent intent) {
Intent broadcastIntent = new Intent();
broadcastIntent.setAction(ResponseReceiver.ACTION_RESP);
broadcastIntent.addCategory(Intent.CATEGORY_DEFAULT);
broadcastIntent.putExtra(DOWNLOAD_COMPLETE, true);
sendBroadcast(broadcastIntent);
}
}
about 的代码应该可以正常工作,但是有没有更简单或更好的方法呢?不必在服务上完成,当连接断开时,Asynctask 强制关闭我,这就是将下载操作放到服务上的原因。
最佳答案
如果您在下载过程中失去连接,我想您的下载会抛出某种异常。如果是,我会简单地通知用户(使用 android notification api ),并让他们选择尝试重新下载数据。
但最好(与我之前在类似问题中的帖子相反),您可以在 android 中使用我最喜欢的新类 AsyncTaskLoader .听起来它完全符合您想在这里做的事情。基本上,如果下载出错,只需让您的加载程序返回 null。然后在你的 Activity 中的 onLoaderFinished Hook 中,做任何你需要做的关于通知用户的事情。请注意,此类仅适用于 API 级别 3 及更高级别,但仍可通过 android compatibility package 由较低的 API 级别访问。 .
关于android - 使用 IntentService 加载数据时处理连接更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7827631/