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

标签 android service wifi

在我正在设计的 android 应用程序中,我的服务只需要在设备连接到路由器时运行(显然是通过 WiFi)。 我真的是 android 的新手,到目前为止我所拥有的东西已经让我永远实现了,所以我真的希望得到一些指点。

我的服务设置为在手机启动时启动。此外,当 Activity 启动时,它会检查服务是否正在运行 - 如果没有,它会启动它。 我只是想知道,如果 WiFi 状态丢失,我可以在我的服务中添加什么代码以使其关闭 - 以及一旦 WiFi 连接变为 Activity 状态,我需要什么代码来启动服务?

谢谢! :)

最佳答案

您可以创建 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 更改为您的包的名称)。

关于Android:根据 WiFi 状态停止/启动服务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7094606/

相关文章:

android - 在 Android 上检索用户数据 Firebase

java - 启动时启动服务 : why it doens't work?

javascript - 在javascript中使用kalman-filter接收RSSI和dbm过滤

java - 使用 java 连接到 adhoc wifi 或手动连接之间的区别

Android:带空格的 Json 字符串给出 "Unterminated object at"异常

java - 将 objective-c 面向 block 的 api 转换为 android

android - 将 Android 项目与 CircleCi 集成,仅使用 connectedAndroidTest 命令针对一种构建变体进行测试?

java - 启动动画服务 Activity

Python Windows 服务 pyinstaller 可执行文件错误 1053

ios - 有关 iOS 上网络状态变化的通知