Android Service检查Wifi状态并用notification通知

今天一到公司被接到一个新需求说要做一个监测Wifi连接状况的功能,纳闷要这功能何为的时候,突然领悟到公司那弱弱的wifi。常常连不上不说,还会一直假连。感情是他们昨天下班后,拿这个软件测试,局域网连不上,数据库数据拿不到,导致程序直接崩溃了。

介于这个情况,我首先把请求服务的host错误给catch掉,提示“网络连接异常”,然后再来慢慢研究wifi,好歹在午睡后做出了雏形。废话不多数,贴上代码:

public class CheckWifi extends Service {  
    private boolean quit = false;  
    private WifiManager wifiM;  
  
    @Override  
    public IBinder onBind(Intent arg0) {  
        return null;  
    }  
  
    @Override  
    public void onCreate() {  
        super.onCreate();  
        Context context = getApplicationContext();  
        final NotificationManager notificationManager = (NotificationManager) context  
                .getSystemService(NOTIFICATION_SERVICE);  
        int icon = R.drawable.stat_notify_chat; //图标随便用了个,美工没空T T  
        CharSequence cs = "Wifi连接中断";  
        long when = System.currentTimeMillis();  
        final Notification notification = new Notification(icon, cs, when);  
        CharSequence contentTitle = "CRM系统提示";  
        CharSequence contentText = "Wifi连接已中断,请检查网络";  
        Intent notificationIntent = new Intent();  
        PendingIntent contentIntent = PendingIntent.getActivity(this, 0,  
                notificationIntent, 0);  
        notification.setLatestEventInfo(context, contentTitle, contentText,  
                contentIntent);  
        new Thread() {  
            @Override  
            public void run() {  
                Looper.prepare();  
                while (!quit) {  
                    try {  
                        Thread.sleep(1000*60*5);    //每5分钟检查一次  
                    } catch (InterruptedException e) {  
                        e.printStackTrace();  
                    }  
                    wifiM = (WifiManager) getSystemService(WIFI_SERVICE);  
                    WifiInfo wifiInfo = wifiM.getConnectionInfo();  
                                        int ipAddress = wifiInfo == null ? 0 : wifiInfo.getIpAddress();  
                                        if (wifiM.isWifiEnabled() && ipAddress != 0) {  
  
                                        } else {  
                                            notificationManager.notify(1, notification);  
                                        }  
                }  
            }  
        }.start();  
    }  
}  

记得在AndroidManifest.xml配置Service

<service android:name=.CheckWifi">  
            <intent-filter>  
                <action android:name="com.fix.service.CHECKWIFI"/>  
            </intent-filter>  
        </service>  

然后在Activity启动Service

Intent intent = new Intent();  
intent.setAction("com.fix.service.CHECKWIFI");  
startService(intent);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

陈振阳

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值