How to make call to service from receiver depends on Internet connected or not?

廉价感情. 提交于 2019-12-10 07:07:55

问题


I know how to checking if internet is available or not in the activity, my requirement is, actually i am storing some values in DB when the device in offline ( no internet), when it comes to online have to pass DB values to the server with out user interactivity. how can i achieve this. i got this example How to check the Internet Connection periodically in whole application? but it's working only for one activity , how to make it as global.


回答1:


Use this in your receiver

<receiver android:name=".UpdateReceiver" >
        <intent-filter>
            <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
        </intent-filter>
    </receiver>

Your UpdateRecieiver

 public class UpdateReceiver extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {


      ConnectivityManager connectivityManager = (ConnectivityManager) 
                                   context.getSystemService(Context.CONNECTIVITY_SERVICE );
      NetworkInfo activeNetInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
      boolean isConnected = activeNetInfo != null && activeNetInfo.isConnectedOrConnecting();   
      if (isConnected)       
          Log.i("NET", "connecte" +isConnected);   
      else Log.i("NET", "not connecte" +isConnected);
    }
}



回答2:


try out this function

public static boolean isInternetAvailable(Context context) {
            ConnectivityManager cm =
                (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo netInfo = cm.getActiveNetworkInfo();
            if (netInfo != null && netInfo.isConnectedOrConnecting()) {
                return true;
            }
            return false;
        }

and in the manifest

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

enjoy..




回答3:


U need to implement the concept of services in your app . This service will run in background and will pass data to server according to need Check this link for your reference http://developer.android.com/guide/topics/fundamentals/services.html



来源:https://stackoverflow.com/questions/10545822/how-to-make-call-to-service-from-receiver-depends-on-internet-connected-or-not

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!