0

我正在使用意图服务将多个图像上传到服务器。一切正常。但是如果没有网络连接,我如何确保服务在网络恢复之前保持活动状态。

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);
    }


}
4

1 回答 1

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>
于 2014-11-24T07:00:22.353 回答