静默安装前 手机 必须 root
以下是代码 、
package com.test.root.install;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.xml.sax.InputSource;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
public class RootInstallApkActivity extends Activity implements OnClickListener {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
findViewById(R.id.install).setOnClickListener(this);
}
private Handler handler = new Handler() {
public void handleMessage(android.os.Message msg) {
switch (msg.what) {
case 0:
findViewById(R.id.install).setEnabled(true);
break;
case 1:
findViewById(R.id.install).setEnabled(false);
break;
default:
break;
}
}
};
public void install() {
new Thread() {
public void run() {
try {
handler.sendEmptyMessage(1);
Process process = Runtime.getRuntime().exec("su"); // 得到root 权限
OutputStream out = process.getOutputStream();
// 向进程里 写入命令
out.write(("cp /sdcard/CNApp/test.apk /data/local/tmp" + "\n").getBytes()); // 先把sdcard里的apk copy到这里目录
out.write(("pm install -r /data/local/tmp/test.apk" + "\n").getBytes());// 调用安装
out.flush();
out.close();
InputStream in = process.getInputStream();
int len = 0;
byte[] bs = new byte[256];
while (-1 != (len = in.read(bs))) {
System.out.println(new String(bs, 0, len));
}
in.close();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
handler.sendEmptyMessage(0);
}
}
}.start();
}
/**
* (non-Javadoc)
*
* @see android.view.View.OnClickListener#onClick(android.view.View)
*/
@Override
public void onClick(View v) {
install();
}
}