在互联网处于活动状态时启动服务

时间:2014-06-18 09:25:38

标签: android android-service

启用互联网后如何启动服务? 我需要在互联网处于活动状态时启动服务。我有应用程序,当互联网存在时与Web应用程序通信,甚至离线移动需要通信,它将在互联网活动时由服务器知道。

1 个答案:

答案 0 :(得分:0)

答案在你的问题中。只需创建一个BroadcastReceiver来监听网络状态,当互联网正常时,像往常一样启动服务器。

public class NetworkBroadcastReceiver extends BroadcastReceiver {

   @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (ConnectivityManager.CONNECTIVITY_ACTION.equals(action)) {
            ConnectivityManager mgr = (ConnectivityManager)
                context.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo networkInfo = mgr.getActiveNetworkInfo();
            if(networkInfo != null && networkInfo.isConnected()){
                isNetworkConnected = true;
                //do your work here
            }
        }
    }}