Android 基于连接的暂停意向服务(队列意向)
在咨询Stackoverflow很多之后,我发现了这个解决方案: 现在我已经在使用一个IntentService来处理与服务器的通信,并且我已经实现了一个BroadcastReceiver来查找当前的连接状态 IntentService:Android 基于连接的暂停意向服务(队列意向),android,broadcastreceiver,intentservice,internet-connection,Android,Broadcastreceiver,Intentservice,Internet Connection,在咨询Stackoverflow很多之后,我发现了这个解决方案: 现在我已经在使用一个IntentService来处理与服务器的通信,并且我已经实现了一个BroadcastReceiver来查找当前的连接状态 IntentService: public class CommunicationService extends IntentService { public CommunicationService() { super(CommunicationService.class.g
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;
}
}
}
广播接收器:
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排队,并让它排队等待一切,直到连接恢复
提前感谢您的帮助:)
编辑:现在我用一种肮脏的方法解决了它。应用程序本身现在有了一个队列,在那里可以添加意图,以防它们出错(在执行过程中丢失internet连接)或根本没有internet连接。当internet连接可用时,该队列的意图将在BroadcastReceives onReceive()中再次启动。我希望它能帮助别人;)