http://sailerya.tistory.com/6
Runtime runtime = Runtime.getRuntime();
Process process;
String res = "-0-";
try {
String cmd = "top -n 1";
process = runtime.exec(cmd);
BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line ;
while ((line = br.readLine()) != null) {
Log.i("test",line);
}
} catch (Exception e) {
e.fillInStackTrace();
Log.e("Process Manager", "Unable to execute top command");
}
http://blog.burt.pe.kr/
안드로이드에서 명령문 실행하기
Java의 표준 라이브러리인 Runtime 을 이용해서 실행할 수 있다. Runtime.exec() 를 통해서 Process 를 생성하고 Process 가 stdout에서 Process가 뱉는 결과를 받아 오는 방식이다. 아래의 예제는 ls 명령어를 실행하는 예제이다.
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 | <LinearLayout 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" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" android:paddingBottom="@dimen/activity_vertical_margin" android:orientation="vertical" tools:context=".MainActivity"> <Button android:id="@+id/mRunButton" android:layout_width="match_parent" android:layout_height="56dp" android:text="Run ls command"/> <ScrollView android:layout_width="match_parent" android:layout_height="wrap_content"> <TextView android:id="@+id/mResult" android:text="" android:layout_width="match_parent" android:layout_height="match_parent" /> </ScrollView> </LinearLayout> |
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 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 | package kr.pe.burt.android.executebinary; import android.app.Activity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.TextView; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class MainActivity extends Activity implements View.OnClickListener { TextView mResult; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mResult = (TextView)findViewById(R.id.mResult); findViewById(R.id.mRunButton).setOnClickListener(this); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } @Override public void onClick(View v) { try { String result = runProcess(); mResult.setText(result); } catch (RuntimeException e) { e.printStackTrace(); finish(); } } public String runProcess() throws RuntimeException { try { // 명령문 실행 Process process = Runtime.getRuntime().exec("/system/bin/ls "); // 결과를 읽는다 // 참고 : process.getOutputStream() 을 통해서 명령문의 stdin 에 쓰기를 할 수 있다. BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream())); int read; char[] buffer = new char[4096]; StringBuffer output = new StringBuffer(); while ((read = reader.read(buffer)) > 0) { output.append(buffer, 0, read); } reader.close(); // 명령문이 종료될 때까지 기다린다 process.waitFor(); return output.toString(); } catch (IOException e) { throw new RuntimeException(e); } catch (InterruptedException e) { throw new RuntimeException(e); } } } |
실행결과
![실행결과](http://blog.burt.pe.kr/wp-content/uploads/2014/11/%EC%8A%A4%ED%81%AC%EB%A6%B0%EC%83%B7-2014-11-07-%EC%98%A4%ED%9B%84-2.29.29.png)
Process prc=Runtime.getRuntime().exec("ps | grep applicationname");
//applicationname으로 process에서 찾기 시작.
BufferedReader rdr = new BufferedReader(new InputStreamReader(prc.getInputStream()));
char[] buffer = new char[1024];
//buffer의 길이를 1024
rdr.read(buffer);
//rdr 객체에서 buffer 만큼 읽기
StringBuffer output = new StringBuffer();
output.append(buffer, 0, 1024);
//buffer의 를 output stringbuffer에 옮기기
resString=output.toString();
//output 스트링을 resString 이라는 String 객체에 복사
String[] test=resString.split("\\s+");
//resString 객체를 띄어쓰기 마다 잘라서 test 스트링 배열에 저장
prc=Runtime.getRuntime().exec("cat /proc/"+test[9]+"/maps");
// test[9]에는 해당 application의 pid가 저장되어 있다. 이를 이용해 maps 정보를 가져올 수 있다. (이를 가져오기 위해선 root 권한이 필요. 따라서 일반적인 상황에선 permission error남)
참고 : 위의 조잡한 string 객체 생성을 피하고 단순하게도 할 수 있음.
mㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ
public class CurlConnect {
public static void RunCurl(String input) throws RuntimeException {
try {
Process prc = Runtime.getRuntime().exec("ps | grep live");
/*
"curl '" + "http://dic.naver.com/search.nhn?dicQuery="
+ input + "&query=" + input
+ "&target=dic&ie=utf8&query_utf=&isOnlyViewEE="
+ "'");
*/
BufferedReader rdr = new BufferedReader(new InputStreamReader(
prc.getInputStream()));
char[] buffer = new char[1024];
// buffer의 길이를 1024
rdr.read(buffer);
// rdr 객체에서 buffer 만큼 읽기
StringBuffer outBuff = new StringBuffer();
outBuff.append(buffer, 0, 1024);
TransService.output=outBuff.toString();//rdr.readLine(buffer).toString();//
//TransService.output=outBuff.toString();
//TransService.output="hello";
// buffer의 를 output stringbuffer에 옮기기
//return TransService.output;
} catch (IOException e) {
throw new RuntimeException(e);
}
//return null;
}
}