Android getSystemService()

使用getSystemService()获取系统服务,需要注意的是,总是使用上下文

context.getSystemService

来调用该方法,如获取网络状态的服务

ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
State mobile = manager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState();
State wifi = manager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState();

// 如果3G、WIFI、2G等网络状态是连接的,则退出,否则显示提示信息进入网络设置界面
if (mobile == State.CONNECTED || mobile == State.CONNECTING)
  return true;
if (wifi == State.CONNECTED || wifi == State.CONNECTING)
  return true;

 

文档解释:

Note: System services obtained via this API may be closely associated with the Context in which they are obtained from. 
In general, do not share the service objects between various different contexts (Activities, Applications, Services, Providers, etc.)

  

posted @ 2013-11-22 18:33  observer & executive  阅读(244)  评论(0编辑  收藏  举报