Android Service检查Wifi状态并用notification通知
2015-07-07 23:39
579 查看
今天一到公司被接到一个新需求说要做一个监测Wifi连接状况的功能,纳闷要这功能何为的时候,突然领悟到公司那弱弱的wifi。常常连不上不说,还会一直假连。感情是他们昨天下班后,拿这个软件测试,局域网连不上,数据库数据拿不到,导致程序直接崩溃了。
介于这个情况,我首先把请求服务的host错误给catch掉,提示“网络连接异常”,然后再来慢慢研究wifi,好歹在午睡后做出了雏形。废话不多数,贴上代码:
记得在AndroidManifest.xml配置Service
然后在Activity启动Service
介于这个情况,我首先把请求服务的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);
相关文章推荐
- android虚拟机adb不能启动情况汇总
- [Android] PorterDuff使用实例----实现新浪微博图片下载效果
- viewPager控制滑动速度和时间:利用反射机制实现
- android 记录
- Introduction into Android Development
- Android应用代码混淆,打包发布
- android sqlite 数据类型
- 【android Studio】零git知识、零脚本命令,即刻体验git版本管理魅力!
- something about Android activity
- something about Android activity
- android 新交互方式
- Android开发之 android:windowSoftInputMode属性详解
- Android中URI的解释
- Android TextView内容过长加省略号
- Android控件之ViewStub的使用技巧
- 导入Android项目出现invalid project description问题
- android中Invalidate和postInvalidate的区别
- Android设备开机动画的原理和修改方式
- android基础_数据库的创建
- Android 中View的绘制机制源码分析 一