下面是一个我们经常会见到的例子,也是文档中描述的例子:
private static void ping() { Process process=null; try { process = new ProcessBuilder() .command("ping", "www.google.com") .redirectErrorStream(true) .start(); InputStream in = process.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String s = null; while((s = br.readLine())!= null) { System.out.println(s); } } catch(IOException e) { e.printStackTrace(System.out); System.err.println("创建进程时出错"); System.exit(1); } finally { process.destroy(); } }
package com.linc.AndroidProcess; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import android.app.Activity; import android.os.Bundle; import android.util.Log; import android.widget.TextView; public class AndroidProcess extends Activity { private TextView text; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); text = (TextView)findViewById(R.id.text); ping(); } private void ping() { Process process=null; try { process = new ProcessBuilder() // .command("/system/bin/ping", "www.google.com") .command("/system/bin/date") // .command("/system/bin/ifconfig") .redirectErrorStream(true) .start(); InputStream in = process.getInputStream(); OutputStream out = process.getOutputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String s = null; while((s = br.readLine())!= null) { Log.d("AndroidProcess get date: ", s); } } catch(IOException e) { e.printStackTrace(System.out); System.err.println("创建进程时出错"); System.exit(1); } finally { process.destroy(); } } }
public void invokeCamera() { Intent mIntent = new Intent(); ComponentName comp = new ComponentName("com.android.camera", "com.android.camera.Camera" ); mIntent.setComponent(comp); mIntent.setAction("android.intent.action.VIEW"); startActivity(mIntent); }这里用到了android.content.ComponentName类,它有4个构造函数,这里用的是“包名+类名“为参数。