android应用的一些接口方法

1.提供一些安卓应用的底层接口方法调用。大部分是需要签名之后才能实现的。

签名的命令:

找到路径:cd C:\Users\chenwei\Desktop\jar包\系统签名
Java -jar signapk.jar platform.x509.pem platform.pk8  后面是in.apk和out.apk



2设置-》安全,屏幕锁定-》无            张波




需要禁止锁屏
frameworks\base\core\java\com\android\internal\widget\LockPatternUtils.java


mLockPatternUtils = new LockPatternUtils(context);
mLockPatternUtils.setLockScreenDisabled(true/false);


//锁屏和密码取消设置锁屏,保证屏幕不锁屏
setLockState();
执行这个方法:
//锁屏和密码取消设置锁屏,保证屏幕不锁屏
private void setLockState()
   {
       try
       {
           String className = "com.android.internal.widget.LockPatternUtils";
           Class clazz = Class.forName(className);
           Method method = clazz.getMethod("setLockScreenDisabled", boolean.class);
           Constructor constructor = clazz.getConstructor(Context.class);
           Object object = constructor.newInstance(MainActivity.this);
           method.invoke(object, true);
       }
       catch(Exception e)
       {
           e.printStackTrace();
       }
   }


3设置-取消勾选未知来源                


      打开未知来源开关:
      private void setInstallingUnknownAppsAllowed() {
           Settings.Global.putInt(getContentResolver(), Settings.Global.INSTALL_NON_MARKET_APPS,1 );
      }
      关闭未知来源开关:
      private void setInstallingUnknownAppsDisable() {
           Settings.Global.putInt(getContentResolver(), Settings.Global.INSTALL_NON_MARKET_APPS,0 );
      }
注意:需要将apk预置到system/priv-app下面才能正常使用以上两个接口,否则apk权限不够不能使用。






4设置-显示:设置永不灭屏,勾选屏幕旋转
永不灭屏:
Settings.System.putInt(contentResolver, Settings.System.SCREEN_OFF_TIMEOUT, Integer.MAX_VALUE);
勾选屏幕旋转:
 RotationPolicy.setRotationLock(context, false);
//4设置-显示:设置永不灭屏,勾选屏幕旋转  调用系统自带的屏幕旋转功能,0为关闭 1为开启
Settings.System.putInt(getContentResolver(),
Settings.System.ACCELEROMETER_ROTATION, 1);




5设置-日期和时间,取消勾选24小时格式   杨涛
取消勾选24小时格式接口:
Settings.System.putString(getContentResolver(),Settings.System.TIME_12_24,12);


6设置-》数据业务打开                   侯佳


4.4和5.1的接口不一样:4.4只有一个数据开关;但是5.0开始,每个卡槽都有自己对应的数据开关。


4.4:    ConnectivityManager cm = (ConnectivityManager)mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
         cm.setMobileDataEnabled(true);//false为关闭


5.1:    TelephonyManager = (TelephonyManager)mContext.getSystemService(Context.TELEPHONY_SERVICE);
         mTelephonyManager.setDataEnabled(SubscriptionManager.getDefaultDataSubId(), true);//第一个参数为卡槽的subID,第二个参数true表示打开,false表示关闭




7设置-》键盘-》将默认输入法设置为Android Keyboard
Settings.Secure.putString(contentResolver, Settings.Secure.DEFAULT_INPUT_METHOD, "com.android.inputmethod.latin/.LatinIME");


8,取消自动确定时间和日期
Settings.System.putString(getContentResolver(),def_auto_time,false)
取消自动确定时区
Settings.System.putString(getContentResolver(),def_auto_time_zone,false)
设置时区为洛杉矶
AlarmManager timeZone= (AlarmManager)MainActivity.this.getSystemService(ALARM_SERVICE);
timeZone.setTimeZone("America/Los_Angeles");




9设置-》 开发者选项,勾选不锁定屏幕(Stay awake),打开USB调试(USB debugging),勾选允许模拟位置(Allow mock locations)
勾选不锁定屏幕:
Settings.Global.putInt(contentResolver, Settings.Global.STAY_ON_WHILE_PLUGGED_IN,
                    BatteryManager.BATTERY_PLUGGED_AC | BatteryManager.BATTERY_PLUGGED_USB);
打开USB调试:
Settings.Global.putInt(contentResolver,  Settings.Global.ADB_ENABLED, 1);
允许模拟位置:
Settings.Secure.putInt(contentResolver, Settings.Secure.ALLOW_MOCK_LOCATION, 1);




10.情景模式设置静音;
情景模式:
AudioManager mAudioManager=(AudioManager)getSystemService(Context.AUDIO_SERVICE);
mAudioManager.setRingerMode(AudioManager.RINGER_MODE_SILENT);//设置静音
mAudioManager.setRingerMode(AudioManager.RINGER_MODE_VIBRATE);//设置振动
mAudioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);//设置为正常模式


11.去除日历提示框


去除日历提示框       --安娜 咨询


android.os.SystemProperties.getBoolean("ro.config.hw_coop_hidecalsub",false);如果没有值会默认返回false
android.os.SystemProperties.set("ro.config.hw_coop_hidecalsub","true");这个是设置为true的方法


   检查系统属性ro.config.hw_coop_hidecalsub 为true 表示去除日历提示框,没有值 或 为false表示显示日历提示框


12.开启aplog(拨号盘输入:####7878# ->选择打开)
开启aplog(拨号盘输入:####7878# ->选择打开)    --于洋
开启的接口是 设置属性persist.sys.debug.getaplog 为1  
关闭的接口是 设置属性persist.sys.debug.getaplog 为0  
android.os.SystemProperties.set("persist.sys.debug.getaplog","1")  打开aplog
android.os.SystemProperties.set("persist.sys.debug.getaplog","0")  关闭aplog


13.辅助机跟测试机需要配对蓝牙,设置成永不超时
mAdapter.setScanMode(BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE, 0);


14.e. 语言切换为英文,输入法默认为当前输入法(触宝)
Settings.Secure.putString(contentResolver, Settings.Secure.DEFAULT_INPUT_METHOD, "com.android.inputmethod.latin/.LatinIME");


15.//隐藏手机键盘
Settings.Secure.putString(getContentResolver(), Settings.Secure.DEFAULT_INPUT_METHOD, "com.cootek.smartinputv5/com.cootek.smartinputv5.TouchPalXIME");


16.//显示调节亮度0-255之间
Settings.System.putInt(getContentResolver(),Settings.System.SCREEN_BRIGHTNESS,0);
//显示亮度调节,0代表取消自动,1或者-1代表自动
Settings.System.putInt(getContentResolver(),Settings.System.SCREEN_BRIGHTNESS_MODE,0);


17.//1代表日期时间同步当前时间
Settings.Global.putLong(getContentResolver(),Settings.Global.AUTO_TIME,1);


18.开启或者关闭wifi热点


WifiManager mWifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
开启
mWifiManager.setWifiApEnabled(mWifiManager.getWifiApConfiguration();, true);
关闭
mWifiManager.setWifiApEnabled(null, false);


19.开启与关闭照相机
package="com.huawei.camera"包名
android:targetActivity="com.huawei.camera.controller.CameraActivity"主类名


使用如上就可以发生intent去打开相机,关闭相机时建议finish栈中activity。


20.录像
进入相机的录像界面可以参考,短信录制的代码
package/yepapp/YepMms/Src/com/android/mms/ui中的recordVideo函数去启动录像


public static void recordVideo(Activity activity, int requestCode, long sizeLimit) {
        sizeLimit *= .95F;
        int durationLimit = getVideoCaptureDurationLimit(sizeLimit);


            log("recordVideo: durationLimit: " + durationLimit +
                    " sizeLimit: " + sizeLimit);


        Intent intent = 


new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
        intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 0);
        intent.putExtra("android.intent.extra.sizeLimit", sizeLimit);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, TempFileProvider.SCRAP_CONTENT_URI);
        activity.startActivityForResult(intent, requestCode);
    从系统现有的相机应用中获取拍摄的视频,与获取拍摄的图片过程大致相同,但是它除了可以通过putExtra()设置MediaStore.EXTRA_OUTPUT输出路径外,还可以设置其它值,这里简单介绍一下:


MediaStore.EXTRA_OUTPUT:设置媒体文件的保存路径。
MediaStore.EXTRA_VIDEO_QUALITY:设置视频录制的质量,0为低质量,1为高质量。
MediaStore.EXTRA_DURATION_LIMIT:设置视频最大允许录制的时长,单位为毫秒。
MediaStore.EXTRA_SIZE_LIMIT:指定视频最大允许的尺寸,单位为byte。


21.蓝牙热点共享 接口信息
接口是BluetoothPan的setBluetoothTethering()
具体使用方法请参考packages\apps\Settings\src\com\android\settings\TetherSettings.java


22 CPU&GPU文件的路径
CPU:/sys/devices/system/cpu/cpu0/cpufreq/scaling_cur_freq
GPU:/sys/class/kgsl/kgsl-3d0/devfreq/cur_freq


1.类1

package com.huaqin.sourcecode;


import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.util.Locale;
import java.util.Timer;
import java.util.TimerTask;


import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlarmManager;
import android.bluetooth.BluetoothAdapter;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.res.Configuration;
import android.location.LocationManager;
import android.media.AudioManager;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiManager;
import android.os.BatteryManager;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.widget.Toast;


public class SystemSettingsActivity extends Activity {


private static final String Tag = "SystemSettingsActivity";


private WifiManager wifiManager;
private Timer timer;
   private TimerTask airPlaneModeTask;
   private int version = 0;


   private ConnectivityManager mgr;
   private Class connectManager;
   private Class[] paramSet;
   private Method method;


   private static final String CLASS_NAME = "android.net.ConnectivityManager";

@SuppressLint("NewApi")
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.systemsettings);


// 打开WiFi/BlueTooth/数据流量/情景模式/GPS/旋转屏幕/飞行模式/wifi热点/亮度调节/语言修改/
// 1.获取触宝输入法的信息
String str = Settings.Secure.getString(getContentResolver(),
Settings.Secure.DEFAULT_INPUT_METHOD);
Log.i(Tag, str + "触宝输入法");


// 2. 情景模式设置静音
AudioManager mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
mAudioManager.setRingerMode(AudioManager.RINGER_MODE_SILENT);// 设置静音
// mAudioManager.setRingerMode(AudioManager.RINGER_MODE_VIBRATE);//设置振动
// mAudioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);//设置为正常模式


// 3. 显示调节亮度0-255之间
Settings.System.putInt(getContentResolver(),
Settings.System.SCREEN_BRIGHTNESS, 0);
// 显示亮度调节,0代表取消自动,1或者-1代表自动
Settings.System.putInt(getContentResolver(),
Settings.System.SCREEN_BRIGHTNESS_MODE, 0);


// 4.打开aplog;(输入暗码####7878#打开aplog)
// 5.USB调试——将样机的调试打开。
Settings.Global.putInt(getContentResolver(),
Settings.Global.ADB_ENABLED, 1);


// 6.勾选屏幕旋转 调用系统自带的屏幕旋转功能,0为关闭 1为开启
Settings.System.putInt(getContentResolver(),
Settings.System.ACCELEROMETER_ROTATION, 1);
// 7.显示——背光时长设置为永不熄灭,调用休眠为永不关不的接口,更改之后休眠方式为永不关闭
Settings.System.putInt(getContentResolver(),
Settings.System.SCREEN_OFF_TIMEOUT, Integer.MAX_VALUE);


// 8. 安全中勾选未知来源选项,1为勾选2位取消
Settings.Global.putInt(getContentResolver(),
Settings.Global.INSTALL_NON_MARKET_APPS, 1);
// 9.安全——在安全中设置锁屏方式为无,锁屏和密码取消设置锁屏,保证屏幕不锁屏
setLockState();


// 10.打开WiFi
WifiManager wm = (WifiManager) this
.getSystemService(Context.WIFI_SERVICE);
if (wm.getWifiState() != WifiManager.WIFI_STATE_ENABLED) {
wm.setWifiEnabled(true);
}
// 11.打开蓝牙
final BluetoothAdapter mBluetoothAdapter = BluetoothAdapter
.getDefaultAdapter();
if (mBluetoothAdapter == null) {
Toast.makeText(this, "本机没有找到蓝牙硬件或驱动!", Toast.LENGTH_SHORT).show();
finish();
}


mBluetoothAdapter.enable();


// 12.打开GPS
setGpsState();
// 13.修改语言为English(US)
updateLanguage(Locale.US);


// 14.语言切换为英文,输入法默认为当前输入法(触宝)
Settings.Secure.putString(getContentResolver(),
Settings.Secure.DEFAULT_INPUT_METHOD,
"com.cootek.smartinputv5/com.cootek.smartinput5.TouchPalIME");


// 15.设置-》键盘-》将默认输入法设置为Android Keyboard
Settings.Secure.putString(getContentResolver(),
Settings.Secure.DEFAULT_INPUT_METHOD,
"com.android.inputmethod.latin/.LatinIME");


// 16. 日期时间同步当前时间,时间格式选择24小时制
Settings.System.putLong(getContentResolver(),
Settings.System.TIME_12_24, 24);
// 17.代表日期时间同步当前时间
Settings.Global.putLong(getContentResolver(),
Settings.Global.AUTO_TIME, 1);
// 18.设置时区为北京
AlarmManager timeZone = (AlarmManager) SystemSettingsActivity.this
.getSystemService(ALARM_SERVICE);
timeZone.setTimeZone("GMT+08:00");


// 19.勾选不锁定屏幕:
Settings.Global.putInt(getContentResolver(),
Settings.Global.STAY_ON_WHILE_PLUGGED_IN,
BatteryManager.BATTERY_PLUGGED_AC
| BatteryManager.BATTERY_PLUGGED_USB);


// 20.允许模拟位置:
Settings.Secure.putInt(getContentResolver(),
Settings.Secure.ALLOW_MOCK_LOCATION, 1);


// 21.开发者选项中,勾选指针位置// public static final String POINTER_LOCATION =
// "pointer_location";
Settings.System.putInt(getContentResolver(), "pointer_location", 1);




//u. 开启数据流量,主测与辅测都用联通卡
//22.设置-》数据业务打开(插入SIM卡后,直接打开GPRS)
try {
version = Integer.valueOf(android.os.Build.VERSION.SDK);
} catch (NumberFormatException e) {
// Toast.makeText(this, version, Toast.LENGTH_LONG).show();
}
if (version >= 21) {
// TelephonyManager mTelephonyManager =
// (TelephonyManager)this.getSystemService(Context.TELEPHONY_SERVICE);
// 第一个参数为卡槽的subID,第二个参数true表示打开,false表示关闭
// mTelephonyManager.setDataEnabled(SubscriptionManager.getDefaultDataSubId(),
// true);
toggleMobileData123(this, true);
} else {
// ConnectivityManager cm =
// (ConnectivityManager)mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
// cm.setMobileDataEnabled(true);//false为关闭
toggleMobileData(this, true);
}




// 23. 进入联系人,选择添加联系人,选择保存到phone
      AddContacts();
      
   // 24.开启wifi热点
setWifiApEnabled(getWifiApConfiguration(), true);
//25.打开飞行模式
initEvents();
}



private void initEvents() {


        version = Integer.valueOf(Build.VERSION.SDK);
        if(version >= Build.VERSION_CODES.JELLY_BEAN_MR2)//版本在4.3以上
        {
            try
            {
                mgr = (ConnectivityManager) SystemSettingsActivity.this.getSystemService(Context.CONNECTIVITY_SERVICE);
                connectManager = Class.forName(CLASS_NAME);
                paramSet = new Class[1];
                paramSet[0] = boolean.class;
                method = connectManager.getMethod("setAirplaneMode", paramSet);
            }
            catch(ClassNotFoundException e)
            {
                e.printStackTrace();
            }
            catch(NoSuchMethodException e)
            {
                e.printStackTrace();
            }
            startTimer();
        }
        else
        {
            Toast.makeText(SystemSettingsActivity.this, "Android4.3以上的系统才有效!!", Toast.LENGTH_SHORT).show();
           //4.4版本一下就返回
            back();
        }
    
}


@Override
   public void onBackPressed()
   {
       super.onBackPressed();
   }



  public void back()
   {
       if(timer != null)
       {
           timer.cancel();
           timer = null;
       }
       if(airPlaneModeTask != null)
       {
           airPlaneModeTask.cancel();
           airPlaneModeTask = null;
       }
       finish();
   }



  private void startTimer()
   {
       timer = new Timer();
       airPlaneModeTask = new TimerTask()
       {
           @Override
           public void run()
           {
               new airPlaneModeThread().start();
           }
       };


       timer.schedule(airPlaneModeTask, 1000, 13 * 1000);
   }


   private class airPlaneModeThread extends Thread
   {
       public airPlaneModeThread()
       {


       }


       @Override
       public void run()
       {
           try
           {
               setAirPlaneModeEnable(true);
               sleep(5000);
               setAirPlaneModeEnable(false);
               sleep(2000);
           }
           catch(InterruptedException e)
           {
               e.printStackTrace();
           }
       }
   }


   private void setAirPlaneModeEnable(boolean enable)
   {
       try
       {
           method.invoke(mgr, enable);
       }
       catch(Exception e)
       {
           e.printStackTrace();
       }
       //mgr.setAirplaneMode(enabled);
   }


   
   
// 利用反射设置语言为英语
@SuppressLint("NewApi") 
private void updateLanguage(Locale locale) {
try {
Object objIActMag, objActMagNative;
Class clzIActMag = Class.forName("android.app.IActivityManager");
Class clzActMagNative = Class
.forName("android.app.ActivityManagerNative");
Method mtdActMagNative$getDefault = clzActMagNative
.getDeclaredMethod("getDefault");
// IActivityManager iActMag = ActivityManagerNative.getDefault();
objIActMag = mtdActMagNative$getDefault.invoke(clzActMagNative);
// Configuration config = iActMag.getConfiguration();
Method mtdIActMag$getConfiguration = clzIActMag
.getDeclaredMethod("getConfiguration");
Configuration config = (Configuration) mtdIActMag$getConfiguration
.invoke(objIActMag);

//这2个方法都能达到修改语言为英语
config.setLocale(locale);//机器重启后语言不改变,为英语
//config.locale = locale; //如果用这句的话,机器重启后就为中文(一开始是中文下)

// iActMag.updateConfiguration(config);
// 此处需要声明权限:android.permission.CHANGE_CONFIGURATION
// 会重新调用 onCreate();
Class[] clzParams = { Configuration.class };
Method mtdIActMag$updateConfiguration = clzIActMag
.getDeclaredMethod("updateConfiguration", clzParams);
mtdIActMag$updateConfiguration.invoke(objIActMag, config);
} catch (Exception e) {
e.printStackTrace();
}
}


// 锁屏和密码取消设置锁屏,保证屏幕不锁屏
private void setLockState() {
try {
String className = "com.android.internal.widget.LockPatternUtils";
Class clazz = Class.forName(className);
Method method = clazz.getMethod("setLockScreenDisabled",
boolean.class);
Constructor constructor = clazz.getConstructor(Context.class);
Object object = constructor
.newInstance(SystemSettingsActivity.this);
method.invoke(object, true);
} catch (Exception e) {
e.printStackTrace();
}
}




//开启数据流量
private void toggleMobileData123(Context context, boolean enabled) {


TelephonyManager mTelephonyManager = (TelephonyManager) context
.getSystemService(Context.TELEPHONY_SERVICE);


Method setMobileDataEnabl;


try {


setMobileDataEnabl = mTelephonyManager.getClass()
.getDeclaredMethod("setDataEnabled", boolean.class);


setMobileDataEnabl.invoke(mTelephonyManager, enabled);


} catch (Exception e) {


e.printStackTrace();


}


}


private void toggleMobileData(Context context, boolean enabled) {


ConnectivityManager connectivityManager =


(ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
Method setMobileDataEnabl;


try {


setMobileDataEnabl= connectivityManager.getClass()
.getDeclaredMethod("setMobileDataEnabled", boolean.class);


setMobileDataEnabl.invoke(connectivityManager, enabled);


} catch (Exception e) {


e.printStackTrace();


}


}



private void toggleWiFi(Context context, boolean enabled) {
WifiManager wm = (WifiManager) this
.getSystemService(Context.WIFI_SERVICE);
wm.setWifiEnabled(enabled);
}


// 打开GPS


public void setGpsState() {
// 打开GPS
Settings.Secure.setLocationProviderEnabled(getContentResolver(),
LocationManager.GPS_PROVIDER, true);
}



//往手机插入联系人
public void AddContacts(){  
       /* 往 raw_contacts 中添加数据,并获取添加的id号*/  
       Uri uri = Uri.parse("content://com.android.contacts/raw_contacts");  
       ContentResolver resolver = getContentResolver();  
       ContentValues values = new ContentValues();  
       long contactId = ContentUris.parseId(resolver.insert(uri, values));  
         
       /* 往 data 中添加数据(要根据前面获取的id号) */  
       // 添加姓名  
       uri = Uri.parse("content://com.android.contacts/data");  
       values.put("raw_contact_id", contactId);  
       values.put("mimetype", "vnd.android.cursor.item/name");  
       values.put("data2", "测试使用");  
       resolver.insert(uri, values);  
         
       // 添加电话  
       values.clear();  
       values.put("raw_contact_id", contactId);  
       values.put("mimetype", "vnd.android.cursor.item/phone_v2");  
       values.put("data2", "2");  
       values.put("data1", "12345678900");  
       resolver.insert(uri, values);  
         
       // 添加Email  
       values.clear();  
       values.put("raw_contact_id", contactId);  
       values.put("mimetype", "vnd.android.cursor.item/email_v2");  
       values.put("data2", "2");  
       values.put("data1", "[email protected]");  
       resolver.insert(uri, values);  
   }  


public boolean setWifiApEnabled(WifiConfiguration config, boolean enabled) {


try {
if (enabled) { // disable WiFi in any case
wifiManager.setWifiEnabled(false);
}


Method method = wifiManager.getClass().getMethod(
"setWifiApEnabled", WifiConfiguration.class, boolean.class);
return (Boolean) method.invoke(wifiManager, config, enabled);
} catch (Exception e) {
e.printStackTrace();
return false;
}
}


public WifiConfiguration getWifiApConfiguration() {
try {
Method method = wifiManager.getClass().getMethod(
"getWifiApConfiguration");
return (WifiConfiguration) method.invoke(wifiManager);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}


类2 :调用adb命令的工具类AdbShellUtil:

package com.huaqin.sourcecode;


import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;




/**
 * 
 * ִ��adb Shell�����һ��������
 * @author 101003258
 *
 */
public class AdbShellUtil
{
public static final String COMMAND_SU = "su";
public static final String COMMAND_SH = "sh";
public static final String COMMAND_EXIT = "exit\n";
public static final String COMMAND_LINE_END = "\n";
public static final String ECHO_ROOT = "echo root";


private AdbShellUtil()
{
throw new AssertionError();
}


/**
* check whether has root permission
* ����Ƿ���rootȨ��

* @return
*/
public static boolean checkRootPermission()
{
return execCommand(ECHO_ROOT, true, false).result == 0;
}


/**
* execute shell command, default return result msg
* ִ��shell���Ĭ�Ϸ���msg

* @param command
*            command
* @param isRoot
*            whether need to run with root
* @return
* @see AdbShellUtil#execCommand(String[], boolean, boolean)
*/
public static CommandResult execCommand(String command, boolean isRoot)
{
return execCommand(new String[] { command }, isRoot, true);
}


/**
* execute shell commands, default return result msg

* @param commands
*            command list
* @param isRoot
*            whether need to run with root
* @return
* @see AdbShellUtil#execCommand(String[], boolean, boolean)
*/
@SuppressWarnings("rawtypes")
public static CommandResult execCommand(List commands, boolean isRoot)
{
@SuppressWarnings("unchecked")
String[] array = (String[]) commands.toArray(new String[] {});
return execCommand(commands == null ? null : array, isRoot, true);
}


/**
* execute shell commands, default return result msg

* @param commands
*            command array
* @param isRoot
*            whether need to run with root
* @return
* @see AdbShellUtil#execCommand(String[], boolean, boolean)
*/
public static CommandResult execCommand(String[] commands, boolean isRoot)
{
return execCommand(commands, isRoot, true);
}


/**
* execute shell command

* @param command
*            command
* @param isRoot
*            whether need to run with root
* @param isNeedResultMsg
*            whether need result msg
* @return
* @see AdbShellUtil#execCommand(String[], boolean, boolean)
*/
public static CommandResult execCommand(String command, boolean isRoot, boolean isNeedResultMsg)
{
return execCommand(new String[] { command }, isRoot, isNeedResultMsg);
}


/**
* execute shell commands

* @param commands
*            command list
* @param isRoot
*            whether need to run with root
* @param isNeedResultMsg
*            whether need result msg
* @return
* @see AdbShellUtil#execCommand(String[], boolean, boolean)
*/
@SuppressWarnings("rawtypes")
public static CommandResult execCommand(List commands, boolean isRoot, boolean isNeedResultMsg)
{
@SuppressWarnings("unchecked")
String[] array = (String[]) commands.toArray(new String[] {});
return execCommand(commands == null ? null : array, isRoot, isNeedResultMsg);
}


/**
* execute shell commands

* @param commands
*            command array
* @param isRoot
*            whether need to run with root
* @param isNeedResultMsg
*            whether need result msg
* @return


*         if isNeedResultMsg is false, {@link CommandResult#successMsg} is
*         null and {@link CommandResult#errorMsg} is null.


*         if {@link CommandResult#result} is -1, there maybe some
*         excepiton.


*/
public static CommandResult execCommand(String[] commands, boolean isRoot, boolean isNeedResultMsg)
{
//��һ��
int result = -1;
if(commands == null || commands.length == 0)
{
return new CommandResult(result, null, null);
}

Runtime runtime = null;
Process process = null;
BufferedReader reader = null;
StringBuffer respondBuff = null;

BufferedReader successResult = null;
BufferedReader errorResult = null;
StringBuilder successMsg = null;
StringBuilder errorMsg = null;
StringBuilder currentCommand = null;
//DataOutputStream os = null;

try
{
currentCommand = new StringBuilder();
//currentCommand.append(isRoot ? COMMAND_SU : COMMAND_SH);
//currentCommand.append(COMMAND_LINE_END);
for(String command : commands)
{
if(command == null)
{
continue;
}
else
{
currentCommand.append(command);
currentCommand.append(COMMAND_LINE_END);
}
}
//currentCommand.append(COMMAND_EXIT);

runtime = Runtime.getRuntime();
process = runtime.exec(currentCommand.toString());
respondBuff = new StringBuffer();
reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
char[] buff = new char[1024];
int ch = 0;
while((ch = reader.read(buff)) != -1)
{
respondBuff.append(buff, 0, ch);
}

result = process.waitFor();
// get command result
if(isNeedResultMsg)
{
successMsg = new StringBuilder();
errorMsg = new StringBuilder();
successResult = new BufferedReader(new InputStreamReader(process.getInputStream()));
errorResult = new BufferedReader(new InputStreamReader(process.getErrorStream()));
String s;
while((s = successResult.readLine()) != null)
{
successMsg.append(s);
}
while((s = errorResult.readLine()) != null)
{
errorMsg.append(s);
}
}
}
catch(IOException e)
{
e.printStackTrace();
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
try
{
if(reader != null)
{
reader.close();
}
if(successResult != null)
{
successResult.close();
}
if(errorResult != null)
{
errorResult.close();
}
}
catch(IOException e)
{
e.printStackTrace();
}
if(process != null)
{
process.destroy();
}
}

return new CommandResult(result, successMsg == null ? null
: successMsg.toString(), errorMsg == null ? null
: errorMsg.toString());


//����(ÿ�ζ���rootȨ����ʾ���û����鲻�ã����Ƽ�)��
/*int result = -1;
if(commands == null || commands.length == 0)
{
return new CommandResult(result, null, null);
}

Process process = null;
BufferedReader successResult = null;
BufferedReader errorResult = null;
StringBuilder successMsg = null;
StringBuilder errorMsg = null;
DataOutputStream os = null;

try
{
process = Runtime.getRuntime().exec(isRoot ? COMMAND_SU : COMMAND_SH);
os = new DataOutputStream(process.getOutputStream());
for(String command : commands)
{
if(command == null)
{
continue;
}

// donnot use os.writeBytes(commmand), avoid chinese charset
// error
os.write(command.getBytes());
os.writeBytes(COMMAND_LINE_END);
os.flush();
}
//os.writeBytes(COMMAND_EXIT);
os.flush();

result = process.waitFor();
// get command result
if(isNeedResultMsg)
{
successMsg = new StringBuilder();
errorMsg = new StringBuilder();
successResult = new BufferedReader(new InputStreamReader(process.getInputStream()));
errorResult = new BufferedReader(new InputStreamReader(process.getErrorStream()));
String s;
while((s = successResult.readLine()) != null)
{
successMsg.append(s);
}
while((s = errorResult.readLine()) != null)
{
errorMsg.append(s);
}
}
}
catch(IOException e)
{
e.printStackTrace();
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
try
{
if(os != null)
{
os.close();
}
if(successResult != null)
{
successResult.close();
}
if(errorResult != null)
{
errorResult.close();
}
}
catch(IOException e)
{
e.printStackTrace();
}
if(process != null)
{
process.destroy();
}
}

return new CommandResult(result, successMsg == null ? null
: successMsg.toString(), errorMsg == null ? null
: errorMsg.toString());*/
}


/**
* result of command



* {@link CommandResult#result} means result of command, 0 means normal,
* else means error, same to excute in linux shell


* {@link CommandResult#successMsg} means success message of command result


* {@link CommandResult#errorMsg} means error message of command result




* @author Trinea 2013-5-16
*/
public static class CommandResult
{
/** result of command **/
public int result;
/** success message of command result **/
public String successMsg;
/** error message of command result **/
public String errorMsg;

public CommandResult(int result)
{
this.result = result;
}

public CommandResult(int result, String successMsg, String errorMsg)
{
this.result = result;
this.successMsg = successMsg;
this.errorMsg = errorMsg;
}
}




}












你可能感兴趣的:(开发过程中分享与解决)