经过大量咨询Stackoverflow后,我发现了这个解决方案: https://stackoverflow.com/a/11401196/2440358
现在我已经在使用IntentService处理与服务器的通信了,我已经实现了一个寻找当前连接状态的BroadcastReceiver。
IntentService:
public class CommunicationService extends IntentService {
public CommunicationService() {
super(CommunicationService.class.getName());
}
@Override
protected void onHandleIntent(Intent intent) {
String kind = intent.getExtras().getString("kind");
if ("LocationUpdate".equals(kind)) {
// send current Location to the server
}
}
广播接收器:
public class NetworkChangeReceiver extends BroadcastReceiver {
@Override
public void onReceive(final Context context, final Intent intent) {
checkConnectionState(context);
}
public static boolean checkConnectionState(final Context context) {
final ConnectivityManager connectivityManager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager
.getActiveNetworkInfo();
Intent intent = new Intent(context, CommunicationService.class);
intent.putExtra("kind", "");
if (activeNetworkInfo != null && activeNetworkInfo.isConnected()) {
// start service
context.startService(intent);
return true;
} else {
// stop service
context.stopService(intent);
return false;
}
}
}
这一切都像魅力一样,但我不知道如何将这两者结合在一起,如上面的链接所述。我真的想在没有。
的情况下使用上面提到的IntentService自动排队是否有一种简单的方法可以利用IntentServices队列并使其排队,直到连接恢复为止?
提前感谢您的帮助:)
编辑:现在我在一个肮脏的黑客中解决了它。应用程序本身现在有一个队列,其中添加意图以防它们出错(执行期间的互联网连接丢失)或根本没有互联网连接。当互联网连接可用时,该队列中的意图将在广播接收者onReceive()中再次启动。我希望它可以帮助某人;)