root权限后实现静默安装

package com.example.installtest;

import java.io.DataOutputStream;
import java.io.IOException;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Toast;

public class MainActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}
	
	public void install(View v){
		rootCommand("pm install /storage/sdcard1/snowman_japan.apk");
		Toast.makeText(this, "安装成功", Toast.LENGTH_SHORT).show();
	}
	
	public void uninstall(View v){
		rootCommand("pm uninstall com.yshow.snowman");
		Toast.makeText(this, "卸载成功", Toast.LENGTH_SHORT).show();
	}
	
	public boolean rootCommand(String command) {
        Process process = null;
        DataOutputStream os = null;
        try {  
                process = Runtime.getRuntime().exec("su");  
                os = new DataOutputStream(process.getOutputStream());  
                os.writeBytes(command + "\n");  
                os.writeBytes("exit\n");  
                os.flush();  
                process.waitFor();  
        } catch (Exception e) {  
                Log.d("*** DEBUG ***", "ROOT REE"  
                                + e.getMessage());  
                return false;
        } finally {  
                try {  
                        if (os != null) {  
                                os.close();  
                        }  
                        process.destroy();  
                } catch (Exception e) {  
                        // nothing  
                }  
        }  
          
        Log.d("*** DEBUG ***", "Root SUC ");  
        return true;  

}

}
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="@string/hello_world" />
    <Button 
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="安装"
        android:onClick="install"
        />
    <Button 
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:text="卸载"
        android:onClick="uninstall"
        />

</RelativeLayout>



   

你可能感兴趣的:(root权限后实现静默安装)