在我正在设计的 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/