android中執行java命令的方法大家都曉得嗎,下面一段內容給大家帶來了具體解析。
android的程序基于java開發,當我們接上調試器,執行adb shell,就可以執行linux命令,但是卻并不能執行java命令。
那么在android的shell中是否就不能執行java程序了呢。
答案是否定的。我們可以通過app_process來執行java程序。
寫一個hello world吧,就是剛開始學java的時候 寫得那個hello world,這次要在android上運行。
用記事本新建hello.java文件,編寫如下代碼:
1
2
3
4
5
|
public static class hello { public void main(String args[]){ System.out.println( "Hello Android" ); } } |
得到hello.class文件 執行"java hello" 可以看到輸出結果
那么如何讓這個最簡單的java程序 在android上運行呢。
.class文件可以在普通的jvm上運行,要放到android下還需要轉換成dex,需要用android sdk中的dx工具進行轉換
1
|
dx --dex --output=hello.dex hello. class |
得到hello.dex,這個hello.dex就可以放到android上執行了。
連接手機,打開usb調試
adb push hello.dex /sdcard/
adb shell 進入android命令行
使用app_process 運行hello.dex
app_process -Djava.class.path=/sdcard/hello.dex /sdcard hello
好了,至此我們成功的在android上運行了普通的java程序。
要知道這可是用記事本寫的android代碼,真是聞所未聞啊!趕快像小伙伴炫耀一下吧。
PS:JAVA代碼執行shell命令并解析
在Android可能有的系統信息沒有直接提供API接口來訪問,為了獲取系統信息時我們就要在用shell指令來獲取信息,這時我們可以在代碼中來執行命令 ,這里主要用到ProcessBuilder 這個類.
代碼部分 :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
|
package com.yin.system_analysis; import java.io.File; import java.io.IOException; import java.io.InputStream; import android.app.Activity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.TextView; public class MainActivity extends Activity { private final static String[] ARGS = { "ls" , "-l" }; private final static String TAG = "com.yin.system" ; Button mButton; TextView myTextView; public void onCreate(Bundle savedInstanceState) { super .onCreate(savedInstanceState); setContentView(R.layout.main); mButton = (Button) findViewById(R.id.myButton); myTextView = (TextView) findViewById(R.id.textView); mButton.setOnClickListener( new OnClickListener() { public void onClick(View v) { myTextView.setText(getResult()); } }); } public String getResult(){ ShellExecute cmdexe = new ShellExecute ( ); String result= "" ; try { result = cmdexe.execute(ARGS, "/" ); } catch (IOException e) { Log.e(TAG, "IOException" ); e.printStackTrace(); } return result; } private class ShellExecute { /* * args[0] : shell 命令 如"ls" 或"ls -1"; * args[1] : 命令執行路徑 如"/" ; */ public String execute ( String [] cmmand,String directory) throws IOException { String result = "" ; try { ProcessBuilder builder = new ProcessBuilder(cmmand); if ( directory != null ) builder.directory ( new File ( directory ) ) ; builder.redirectErrorStream ( true ) ; Process process = builder.start ( ) ; //得到命令執行后的結果 InputStream is = process.getInputStream ( ) ; byte [] buffer = new byte [ 1024 ] ; while ( is.read(buffer) != - 1 ) { result = result + new String (buffer) ; } is.close ( ) ; } catch ( Exception e ) { e.printStackTrace ( ) ; } return result ; } } } |