常见的系统服务:
常用系统服务常见系统服务
- 取得xml定义的View
LayoutInflater inflater=(LayoutInflater)(MainActivity.this).getSystemService(LAYOUT_INFLATER_SERVICE);
View view=inflater.inflate(R.layout.activity_main,null);
setContent(view);
- 判断网络是否连接
1.编写一方法
public boolean isNetworkConnected(Context context){
if(context!=null){
ConnectivityManager mConnectivityManager=(ConnectivityManager)context.getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo mNetworkInfo=mConnectivityManager.getActiveNetworkInfo();
if(mNetworkInfo!=null){
return mNetworkInfo.isAvaiable();
}
}
return false;
}
2.实现这方法
if(isNetworkConnected(MainActivity.this)==true){
Toast.makeText(MainActivity.this,"网络已连接",Toast.LENGET_LONG).show();
}else{
Toast.makeText(MainActivity.this,"网络未连接",Toast.LENGET_LONG).show();
}
3.注册其权限
在AndroidManifest中manifest标签中
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
- 判断wifi是否连接并实现其关闭
1.主方法中
WifiManager wifiManager=(WifiManager)(MainActivity.this).getSystemService(WIFI_SERVICE);
if(wifiManager.isWifiEnable){
wifiManager.setWifiEnable(false);
Toast.makeText(MainActivity.this,"Wifi已经关闭",Toast.LENGTH_SHORT).show();
}else{
wifiManager.setWifiEnable(true);
Toast.makeText(MainActivity.this,"Wifi已经打开",Toast.LENGTH_SHORT).show();
}
2.注册其权限,在manifest中注册
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
- 实现音量增加和减少
AudioManager audioManager=(AudioManager)(MainActivity.this).getSystemService(AUDIO_SERVICE);
int max=audioManager.getStreamMaxVolume(AudioManager.STREAM_SYSTEM);
int current=audioManager.getStreamVolume(AudioManager.STREAM_RING);
Toast.makeText(MainActivity.this,"最大音量为:"+max+",当前音量:"+current,Toast.LENGTH_SHORT).show();
- 获取当前程序包名
1.在主方法中
ActivityManager activityManager=(ActivityManager)(MainActivity.this).getSystemService(ACTIVITY_SERVICE);
String packageName=activityManager.getRunningTask(0).get(0).topActivity.getPackageName();
Toast.makeText(MainActivity.this,"当前程序包名为:"+packageName,Toast.LENGTH_SHORT).show();
2.注册权限,在manifest中注册
<uses-permission android:name="android.permission.GET_TASKS"/>
网友评论