要求:软件启动后,显示手机的网络状态情况,当程序切换到后台时,后台要求使用Service检查网络状态,并且每隔 20 - 30 s 发送通知消息,当点击通知消息,切换软件到前台。在前台时不进行消息提醒。
// 程序分析:
{ 1.手机网络状态
功能点: { 2.程序运行在前台还是后台
{ 3.后台启动Service检查网络状态
{ 4.Notification消息通知类
两个工具类方法:
/** * 判断当前应用程序处于前台还是后台 */ public static boolean isApplicationBroughtToBackground(final Context context) { ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE); List<ActivityManager.RunningTaskInfo> tasks = am.getRunningTasks(1); if (!tasks.isEmpty()) { ComponentName topActivity = tasks.get(0).topActivity; if (!topActivity.getPackageName().equals(context.getPackageName())) { return true; } } return false; }
<uses-permission android:name="android.permission.GET_TASKS" />
/** * 检测当的网络(WLAN、3G/2G)状态 * * @param context Context * @return true 表示网络可用 */ public static int getNetType(Context context) { ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); if (connectivity != null) { NetworkInfo info = connectivity.getActiveNetworkInfo(); if (info != null && info.isConnected()) { // 当前网络是连接的 if (info.getState() == NetworkInfo.State.CONNECTED) { // 当前所连接的网络可用 if (info.getType() == ConnectivityManager.TYPE_WIFI) { return WIFI; } else if (info.getType() == ConnectivityManager.TYPE_MOBILE && info.getSubtype() == TelephonyManager.NETWORK_TYPE_GPRS && info.getSubtype() == TelephonyManager.NETWORK_TYPE_EDGE && info.getSubtype() == TelephonyManager.NETWORK_TYPE_CDMA) { return GG; } else { return GGG; } } } return NOCONNETED; } return -1; }
<uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
其实,有一个实时检测网络变化的系统广播:
filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
注册这个广播可以监听网络变化。
按照分析判断应用程序是在前台还是在后台:
根据Activity的生命周期:退到后台会调用onStop()方法,程序返回前台会调用onResume()方法。定义一个父Activity,让应用程序的所有Activity,全部继承自BaseActivity。
当程序进入后台时:
@Override protected void onStop() { super.onStop(); Intent intent = new Intent(this, MyService.class); startService(intent); final NotificationCompat.Builder builder = new NotificationCompat.Builder(MainActivity.this); Intent intent2 = new Intent(this, SecondActivity.class); //延迟意图 PendingIntent pendingIntent = PendingIntent.getActivity(MainActivity.this, 1, intent2, PendingIntent.FLAG_UPDATE_CURRENT); builder.setContentIntent(pendingIntent); //通过服务 获取管理者对象 timer = new Timer(); if (MyApplication.isApplicationBroughtToBackground(this)) { Toast.makeText(this, "进入后台", Toast.LENGTH_SHORT).show(); timer.schedule(new TimerTask() { @Override public void run() { id++; builder.setSmallIcon(R.mipmap.ic_launcher); builder.setContentTitle("标题"); builder.setContentText("balalala...."); builder.setWhen(System.currentTimeMillis());//发送当前通知的时间 //通过管理者对象发送消息 第一个参数:消息的id 唯一标识 第二个对象是消息的对象 manager.notify(id, builder.build()); } }, 30000, 30000); } }
开一个服务去检查网络状态,然后开广播,在需要的地方接收,计时器Timer,30s发一个消息。
进入前台:
@Override protected void onResume() { super.onResume(); if (timer != null) { timer.cancel(); Toast.makeText(this, "进入前台", Toast.LENGTH_SHORT).show(); } }
把Timer Cancel掉,不发送通知。
服务中:监听到网络变化以后,发送广播
private BroadcastReceiver myReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { int type = MyApplication.getNetType(getApplicationContext()); Intent netIntent = new Intent(MainActivity.NetCHANGE); switch (type) { case MyApplication.WIFI: netIntent.putExtra("type", MyApplication.WIFI); sendBroadcast(netIntent); break; case MyApplication.GG: netIntent.putExtra("type", MyApplication.GG); sendBroadcast(netIntent); break; case MyApplication.GGG: netIntent.putExtra("type", MyApplication.GGG); sendBroadcast(netIntent); break; case MyApplication.NOCONNETED: netIntent.putExtra("type", MyApplication.NOCONNETED); sendBroadcast(netIntent); break; } } };
指定位置接收显示:
private BroadcastReceiver mReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { int type = intent.getIntExtra("type", 0); switch (type) { case MyApplication.NOCONNETED: textView.setText("无网络连接"); break; case MyApplication.GG: textView.setText("2G 连接"); break; case MyApplication.GGG: textView.setText("3G 连接"); break; case MyApplication.WIFI: textView.setText("WIFI 连接"); break; } } };
销毁时:
@Override protected void onDestroy() { super.onDestroy(); unregisterReceiver(mReceiver); if (timer != null) { timer.cancel(); Toast.makeText(this, "应用程序销毁", Toast.LENGTH_SHORT).show(); manager.cancelAll(); } }
sendActivity:
@Override protected void onResume() { super.onResume(); NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); manager.cancelAll(); }
,不完全符合需求,有一部分是自己的想法。