安卓:停止/取决于无线网络状态,启动服务?无线网络、状态

2023-09-03 17:50:59 作者:倾城汨﹌隔世傷

在我设计的Andr​​oid应用程序,我的服务只需要运行在设备(显然通过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.

我的服务被设置为当手机启动时启动。此外,当活动启动它检查服务是否正在运行 - 如果不是启动它。 我只是想知道什么code,我可以把我的服务,使之关闭如果WiFi状态丢失 - ?什么code我需要的服务一旦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.

要更precise,你将要创建一个类 - 比方说网络守望者:

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 您包的名称)。