• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

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

用户头像
it1352
帮助1

问题说明

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

谢谢!:)

正确答案

#1

您可以创建一个 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).

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /reply/detail/tanhcfjace
系列文章
更多 icon
同类精品
更多 icon
继续加载