天天看点

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();  
    }  
}        
<service android:name=.CheckWifi">  
            <intent-filter>  
                <action android:name="com.fix.service.CHECKWIFI"/>  
            </intent-filter>  
        </service>        
Intent intent = new Intent();  
intent.setAction("com.fix.service.CHECKWIFI");  
startService(intent);