Android:根据 WiFi 状态停止/启动服务? [英] Android: Stop/Start service depending on WiFi state?

查看:19
本文介绍了Android:根据 WiFi 状态停止/启动服务?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In the android application that I'm designing, my service only needs to be running when the device is connected to the router (via WiFi obviously). I'm really new to android, and what I've got so far has taken me forever to Achieve, so I'm really hoping for some pointers.

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

My service is set to start up when the phone starts up. Also when the Activity is launched it checks whether the service is running - and if not it starts it. I'm just wondering what code I can put into my service to make it turn off if the WiFi state is lost - and what code I need to make the service start once a WiFi connection becomes active?

谢谢!:)

推荐答案

您可以创建一个 BroadcastReceiver 处理 wifi 连接更改.

You can create a BroadcastReceiver that handles wifi connection changes.

更准确地说,您需要创建一个类 - 比如 NetWatcher:

To be more precise, you will want to create a class - say 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 更改为您的服务名称).

(changing MyService to the name of your service).

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

Also, in your AndroidManifest, you need to add the following lines:

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

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

(changing com.example.android to the name of your package).

这篇关于Android:根据 WiFi 状态停止/启动服务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆