直接上代码
public void onReceive(Context context, Intent intent) {
mContext =context;
mTelephonyManager = TelephonyManager.from(context);
Log.e("ShellSettingsBroadcastReceiver","232action: "+intent.getAction());
if (intent.getAction().equals(DATA_ENABLE)) {
// String dataabel = execByRuntime("svc data enable");
// Log.e("ShellSettingsBroadcastReceiver","dataabel: "+dataabel);
setMobileDataEnabled(true);
}else if(intent.getAction().equals(DATA_DISABLE)){
// String datadisable = execByRuntime("svc data disable");
// Log.e("ShellSettingsBroadcastReceiver","datadisable: "+datadisable);
setMobileDataEnabled(false);
}else if(intent.getAction().equals(GPS_ENABLE)){
// String gpsabel = execByRuntime("settings put secure location_providers_allowed +gps");
// Log.e("ShellSettingsBroadcastReceiver","gpsabel: "+gpsabel);
Settings.Secure.putInt(context.getContentResolver(), Settings.Secure.LOCATION_MODE, Settings.Secure.LOCATION_MODE_HIGH_ACCURACY);
}else if(intent.getAction().equals(GPS_DISABLE)){
// String gpsdisale = execByRuntime("settings put secure location_providers_allowed -gps");
Log.e("ShellSettingsBroadcastReceiver","gpsdisale: ");
Settings.Secure.putInt(context.getContentResolver(), Settings.Secure.LOCATION_MODE, android.provider.Settings.Secure.LOCATION_MODE_OFF);
}
}
public void setMobileDataEnabled(boolean enabled) {
Log.d(TAG, "setMobileDataEnabled: enabled=" + enabled);
try {
mTelephonyManager.setDataEnabled(enabled);
}catch (Exception e){
e.printStackTrace();
Log.w("ssssett","setDataEnabled exception");
}
}
/**
* 执行shell 命令, 命令中不必再带 adb shell
* @param cmd
* @return Sting 命令执行在控制台输出的结果
*/
public static String execByRuntime(String cmd) {
Process process = null;
BufferedReader bufferedReader = null;
InputStreamReader inputStreamReader = null;
try {
process = Runtime.getRuntime().exec(cmd);
inputStreamReader = new InputStreamReader(process.getInputStream());
bufferedReader = new BufferedReader(inputStreamReader);
int read;
char[] buffer = new char[4096];
StringBuilder output = new StringBuilder();
while ((read = bufferedReader.read(buffer)) > 0) {
output.append(buffer, 0, read);
}
return output.toString();
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
if (null != inputStreamReader) {
try {
inputStreamReader.close();
} catch (Throwable t) {
}
}
if (null != bufferedReader) {
try {
bufferedReader.close();
} catch (Throwable t) {
}
}
if (null != process) {
try {
process.destroy();
} catch (Throwable t) {
}
}
}
}
}