我正在使用意向服务将多个图像上传到服务器。一切正常。 但如果没有网络连接,我如何确保服务保持活动状态,直到网络恢复为止。
public class PostPropertyIntentService extends IntentService {
// TODO: Rename actions, choose action names that describe tasks that this
// IntentService can perform, e.g. ACTION_FETCH_NEW_ITEMS
private static final String ACTION_FOO = "pacakagename.action.FOO";
private static final String EXTRA_PARAM1 = "PARAM1";
private static final String EXTRA_PARAM2 = "PARAM2";
public static void startActionFoo(Context context, String param1, String param2) {
Intent intent = new Intent(context, PostIntentService.class);
intent.setAction(ACTION_FOO);
intent.putExtra(EXTRA_PARAM1, param1);
intent.putExtra(EXTRA_PARAM2, param2);
context.startService(intent);
}
public PostIntentService() {
super("PostIntentService");
}
@Override
protected void onHandleIntent(Intent intent) {
if (intent != null) {
final String action = intent.getAction();
if (ACTION_FOO.equals(action)) {
final String param1 = intent.getStringExtra(EXTRA_PARAM1);
final String param2 = intent.getStringExtra(EXTRA_PARAM2);
handleActionFoo(param1, param2);
}
}
}
private void handleActionFoo(Property mProperty, ArrayList<String> mPicUrls) {
// TODO: Handle action Foo
NetworkActions na = new NetworkActions();
String response = na.uploadProperty(mProperty, mPicUrls);
Intent resultBroadCastIntent = new Intent();
resultBroadCastIntent.setAction("pacakgename.mybroadcast");
resultBroadCastIntent.putExtra(OUTPUT_TEXT, response );
sendBroadcast(resultBroadCastIntent);
}
}
答案 0 :(得分:0)
public class ConnectivityDetector_Receiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = cm.getActiveNetworkInfo();
if (info != null) {
if (info.isConnected()) {
// you got a connection! tell your user!
Log.i("Post", "Connected");
Intent intent_service=new Intent(context, Background_Syn_Service.class);
context.startService(intent_service);
}
}
}
**使用此接收器,网络返回时会通知您
<receiver android:name="yourpackageName.ConnectivityDetector_Receiver" >
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
</intent-filter>
</receiver>