Android Service检查Wifi状态并用notification通知
2012-08-24 14:01
375 查看
今天一到公司被接到一个新需求说要做一个监测Wifi连接状况的功能,纳闷要这功能何为的时候,突然领悟到公司那弱弱的wifi。常常连不上不说,还会一直假连。感情是他们昨天下班后,拿这个软件测试,局域网连不上,数据库数据拿不到,导致程序直接崩溃了。
介于这个情况,我首先把请求服务的host错误给catch掉,提示“网络连接异常”,然后再来慢慢研究wifi,好歹在午睡后做出了雏形。废话不多数,贴上代码:
然后在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 Service检查Wifi状态并用notification通知
- android使用NotificationListenerService监听通知栏消息
- Android使用NotificationListenerService获取通知相关信息
- Android 通知使用权(NotificationListenerService)的使用
- 利用android的"通知Notification"来实现msn的登录状态
- 使用android push notification service 实现即时通知
- 【笔记】Android NotificationListenerService监听短信、来电、微信、QQ等通知消息
- android 在通话状态下,当有通知来时(如低电量提示、wifi 连接,等),没有通知音
- Android 检查更新版本(带有通知栏,进度条,Notification)
- 【Android】使用Notification实现状态通知栏的通知
- Android 开发 根据activity前台状态显示通知栏信息或对话框(推送/本地service)
- Android通知栏监听之NotificationListenerService
- Android入门(43)——第五章 使用Notification实现状态通知栏的通知
- android检查网络状态是wifi还是移动网络
- android后台服务service全解析(中)--IntentService与Notification前台通知
- Android-Notification (通知实现)
- 举例说明在android中用PhoneStateListener监听手机电话状态与用发送邮件来通知来电电话的号码
- Android--通知之Notification
- Android通知Notification入门小例子(一)
- Android Notification通知解析