首先判斷是否獲取root權限,如果機器已root,則申請root權限,然後打開adb。
private void runAsRooter(){
if(new File("/system/bin/su").exists()||new File("/system/xbin/su").exists())
{
Toast.makeText(this,"已獲取root權限",Toast.LENGTH_SHORT).show();
return;
}
try {
Process process = Runtime.getRuntime().exec("su");
process.waitFor();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private void startAdb()
{
//成功打開adb
try {
exec("setprop service.adb.tcp.port 5555\nstop adbd\nstart adbd");
Toast.makeText(this,"ip地址爲: "+ NetworkUtil.getIP(this),Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(this,e.getMessage(),Toast.LENGTH_LONG).show();;
}
}
private void exec(String s) {
Process process = null;
DataOutputStream dos = null;
try {
process = Runtime.getRuntime().exec("su");
dos = new DataOutputStream(process.getOutputStream());
dos.writeBytes(s+"\n");
dos.writeBytes("exit\n");
dos.flush();
process.waitFor();
return;
} catch(Exception e) {
e.printStackTrace();
}
}
NetworkUtil的代碼:
package com.jxd.jxdtest.commonutil;
import android.content.Context;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.util.Log;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
import static android.content.Context.WIFI_SERVICE;
public class NetworkUtil {
/**
* 獲取的是外網ip地址
* @return
*/
public static String getHostIP() {
String hostIp = null;
try {
Enumeration nis = NetworkInterface.getNetworkInterfaces();
InetAddress ia = null;
while (nis.hasMoreElements()) {
NetworkInterface ni = (NetworkInterface) nis.nextElement();
Enumeration<InetAddress> ias = ni.getInetAddresses();
while (ias.hasMoreElements()) {
ia = ias.nextElement();
if (ia instanceof Inet6Address) {
continue;// skip ipv6
}
String ip = ia.getHostAddress();
if (!"127.0.0.1".equals(ip)) {
hostIp = ia.getHostAddress();
break;
}
}
}
} catch (SocketException e) {
Log.i("yao", "SocketException");
e.printStackTrace();
}
return hostIp;
}
public static String getIP(Context context) {
//獲取內網IP
WifiManager wifiService = (WifiManager) context.getSystemService(WIFI_SERVICE);
WifiInfo wifiinfo = wifiService.getConnectionInfo();
return intToIp(wifiinfo.getIpAddress());
}
private static String intToIp(int i) {
return (i & 0xFF) + "." + ((i >> 8) & 0xFF) + "." + ((i >> 16) & 0xFF)
+ "." + (i >> 24 & 0xFF);
}
}