【问题标题】:Start service when internet is active in android当互联网在android中处于活动状态时启动服务
【发布时间】:2015-01-26 00:47:23
【问题描述】:

启用互联网后如何启动服务? 当互联网处于活动状态时,我需要启动服务。我有一个应用程序在互联网存在时与网络应用程序通信,即使离线手机也需要通信,它会在互联网激活时被服务器知道。

【问题讨论】:

    标签: android android-service


    【解决方案1】:

    答案就在您的问题中。只需创建一个 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
                }
            }
        }}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-18
      • 2020-07-26
      相关资源
      最近更新 更多