|
Adroid開發(fā)中,我們有時會遇到一些特殊功能的實現(xiàn),有些功能并沒有太高技術難度,但是如果之前沒有接觸過就需要花好多時間去研究解決。 今天,總結介紹一下 獲取Root權限之后的靜默安裝和進門卸載功能的實現(xiàn)。 眾所周知,Android的手機在獲取Root權限之后幾乎可以進行你想要的任何操作,而靜默安裝便是其中比較常見的一個需求: 豌豆莢、360手機助手等應用下載軟件一般都有一個應用一鍵自動更新功能,一鍵批量卸載軟件,他們是如何實現(xiàn)的呢? 一般這類軟件,實現(xiàn)自動更新功能都需要請求root權限,在被授予了root權限后便可批量安裝卸載軟件,其實,這個并沒有太高難度,其過程就是一個獲取了Root權限之后的靜默安裝和卸載: 下面直接上代碼: 注: 靜默安裝和卸載的shell 命令格式分別為:
private String cmd_install = "pm install -r +安裝apk包路徑";//靜默安裝命令 程序代碼: 01.import java.io.DataOutputStream;02.import java.io.OutputStream;03. 04.import android.app.Activity;05.import android.os.Bundle;06.import android.os.Environment;07.import android.view.Menu;08.import android.view.View;09.import android.widget.EditText;10./**11.*
靜默安裝 卸載 Demo12.*13.*
@author blj14.*15.*/16.public class MainActivity extends Activity
{17. 18.private EditText
et_packagename;19.private String
cmd_install = "pm
install -r ";20.private String
cmd_uninstall = "pm
uninstall ";21.String
apkLocation = Environment.getExternalStorageDirectory().toString()22.+ "/";23. 24.@Override25.protected void onCreate(Bundle
savedInstanceState) {26.super.onCreate(savedInstanceState);27.setContentView(R.layout.activity_main);28.et_packagename
= (EditText) findViewById(R.id.et_packagename);29.}30. 31.@Override32.public boolean onCreateOptionsMenu(Menu
menu) {33.//
Inflate the menu; this adds items to the action bar if it is present.34.getMenuInflater().inflate(R.menu.main,
menu);35.return true;36.}37. 38.public void onClick_install(View
view) {39.String
cmd = cmd_install + apkLocation40.+
et_packagename.getText().toString().trim();41.System.out.println("靜默安裝命令:" +
cmd);42.excuteSuCMD(cmd);43.}44. 45.public void onClick_uninstall(View
view) {46.String
cmd = cmd_uninstall + et_packagename.getText().toString().trim();47.//
String cmd = cmd_uninstall + "com.kingsoft.website";48.System.out.println("靜默卸載命令:" +
cmd);49.excuteSuCMD(cmd);50.}51.//執(zhí)行shell命令52.protected int excuteSuCMD(String
cmd) {53.try {54.Process
process = Runtime.getRuntime().exec("su");55.DataOutputStream
dos = new DataOutputStream(56.(OutputStream)
process.getOutputStream());57.//
部分手機Root之后Library path 丟失,導入library path可解決該問題58.dos.writeBytes((String)
"export LD_LIBRARY_PATH=/vendor/lib:/system/lib59.");60.cmd
= String.valueOf(cmd);61.dos.writeBytes((String)
(cmd + "62."));63.dos.flush();64.dos.writeBytes("exit65.");66.dos.flush();67.process.waitFor();68.int result
= process.exitValue();69.return (Integer)
result;70.} catch (Exception
localException) {71.localException.printStackTrace();72.return -1;73.}74.}75. 76.}軟件運行截圖:(以金山網址大全為例) 靜默安裝截圖: 其中king.apk為安裝apk文件名,安裝其他apk時在框中輸入相應文件名即可。 點擊靜默安裝即可靜默安裝應用。
靜默卸載截圖: 其中com.kingsoft.website為金山網址大全程序的包名, 點擊靜默卸載,即可靜默卸載應用。
本文介紹了靜默安裝的代碼實現(xiàn),回到豌豆莢和360一鍵安裝、卸載軟件,他們的實現(xiàn)方式 也就是監(jiān)測apk安裝包下載完成后執(zhí)行上面介紹的靜默安裝命令,一鍵卸載應該就是將要卸載的程序的包名放到for循環(huán)依次執(zhí)行中自動卸載。 http://www./uploadfile/files/2014/0222/SilentInstallDemo.rar |
|
|