Android:根据WiFi状态停止/启动服务?

23
在我设计的安卓应用中,我的服务只需要在设备通过路由器连接到WiFi时运行。 我对安卓开发非常陌生,到目前为止,我做了很长时间才实现了一部分,因此我真的希望能得到一些指导。
我的服务已经设置为随着手机的启动而启动。当Activity被启动时,它会检查服务是否正在运行 - 如果没有,则会启动服务。 我想知道如何编写代码来使服务在WiFi状态丢失时关闭,并在WiFi重新连接后启动服务。
谢谢! :)
4个回答

28
你可以创建一个BroadcastReceiver来处理wifi连接的变化。
更准确地说,你需要创建一个类,比如说NetWatcher:
public class NetWatcher extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        //here, check that the network connection is available. If yes, start your service. If not, stop your service.
       ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
       NetworkInfo info = cm.getActiveNetworkInfo();
       if (info != null) {
           if (info.isConnected()) {
               //start service
               Intent intent = new Intent(context, MyService.class);
               context.startService(intent);
           }
           else {
               //stop service
               Intent intent = new Intent(context, MyService.class);
               context.stopService(intent);
           }
       }
    }
}

(将MyService更改为您的服务名称)。

此外,在您的AndroidManifest中,您需要添加以下行:

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

(将com.example.android更改为您的软件包名称)。


2
谢谢!这是我的解决方案的基础。NetWatcher类正是我所需要的 - 但是这个解决方案会在移动数据连接打开时报告true(服务只需要在WiFi处于活动状态时运行,而不是移动数据)。 解决方案:WifiManager wifiManager = (WifiManager) this.getSystemService(Context.WIFI_SERVICE); if(wifiManager.isWifiEnabled()){ //启动服务 } else { //停止服务 } - user873578
应该是 Intent intent = new Intent(context, MyService.class);BroadcastReceiver 中,将 this 作为参数传递给 Intent 构造函数是无效的。同时应该使用 context.startService(intent) - faizal
@faizal 感谢您的清理建议。我已经编辑了这篇文章并加入了它们。 - Phil

7

正如@Phil所述,你应该扩展BroadcastReceiver,在onReceive方法中启动或停止服务。类似下面这样:

class ConnectionChangeReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        ConnectivityManager connectivityManager = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();
        if (activeNetInfo != null && activeNetInfo.getType() == ConnectivityManager.TYPE_WIFI) {
            //start service
        } else {
            //stop service
        }
    }
}

你可以将这个类设为你的activity的私有类,在activity创建时注册接收器,在activity销毁时取消注册。

2

1

在支持者Wifi状态正常/异常时启动/停止您的服务:

  • 注册一个广播接收器以接收WIFI状态更改广播意图
  • 在您的BroadcastReceiver内部检查意图的有效性,然后启动您的服务

因此,请注册您的广播接收器以接收 WifiManager.SUPPLICANT_CONNECTION_CHANGE_ACTION。 添加权限android.permission.CHANGE_WIFI_STATEandroid.permission.ACCESS_NETWORK_STATE。我不确定是否必须。

然后,示例广播接收器代码可能如下:

public class MyWifiStatereceiver extends BroadcastReceiver {
    //Other stuff here 

    @Override
    public void onReceive(Context context, Intent intent) {
       Intent srvIntent = new Intent();
       srvIntent.setClass(MyService.class);
       boolean bWifiStateOk = false;

       if (WifiManager.SUPPLICANT_CONNECTION_CHANGE_ACTION.equals(intent.getAction()) {
           //check intents and service to know if all is ok then set bWifiStateOk accordingly
           bWifiStateOk = ... 
       } else {
           return ; // do nothing ... we're not in good intent context doh !
       }

       if (bWifiStateOk) {
           context.startService(srvIntent);
       } else {
           context.stopService(srvIntent);
       }
    }

}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接