总的来说ANDROID的NDK远不及其应用开发的SDK完善(虽然经过一番不算复杂的折腾发现NDK用起来很方便),而且它本身也不推荐使用这种做法,至少目前也不将此作为重点。但是某些中间层面系统测试(主要如多媒体和OpenGL ES的测试和演示等)必须通过本地代码实现,因此NDK应当是必由之路。
JAVA程序 1: 2:
3: import android.app.Activity; 4: import android.os.Bundle; 5: import android.widget.TextView; 6: import java.util.*; 7:
8: public class Sample extends Activity { 9:
10: enum UpdateType { 11:
Modify,
12:
Append
13:
}
14:
15: private class UpdateTextRunner implements Runnable { 16: public UpdateTextRunner(String s, UpdateType type) { 17:
mS = s;
18:
mType = type;
19:
}
20:
21: public void run() { 22: if (mType == UpdateType.Modify) { 23:
mLines.clear();
24:
mLines.add(mS);
25:
mTV.setText(mS);
26: } else { 27:
mLines.add(mS);
28: /* intended to display no more than `mMaxLineCount' 29: * lines and scroll, however this is not 30: * always the case, consider if mS is broken 31: * into several lines 32: */ 33: while (mLines.size() > mMaxLineCount) 34:
mLines.remove(0);
35:
36: StringBuilder sb = new StringBuilder(); 37: for (int i = 0; i < mLines.size(); i++) 38:
sb.append(mLines.get(i));
39:
mTV.setText(sb.toString());
40:
}
41:
}
42:
43: private String mS; 44: private UpdateType mType; 45:
}
46:
47: /** Called when the activity is first created. */ 48:
@Override
49: public void onCreate(Bundle savedInstanceState) { 50: super .onCreate(savedInstanceState); 51:
52: mTV = new TextView(this ); 53: mTV.setText( "initial text" ); 54:
setContentView(mTV);
55:
56:
initTextGenerator();
57:
58: /* The following thread object simply contains 59: * an overriden run method which invokes 60: * runTextGenerator on this Sample object 61: */ 62: mThread = new TextUpdatorThread(this ); 63:
mThread.start();
64:
}
65:
66:
@Override
67: public void onDestroy() { 68:
stopTextGenerator();
69:
70: try { 71:
mThread.join();
72: } catch (InterruptedException e) { 73:
e.printStackTrace();
74:
}
75: super .onDestroy(); 76:
}
77:
78: public void modifyText(String s) { 79: this .runOnUiThread(new UpdateTextRunner(s, UpdateType.Modify)); 80:
}
81:
82: public void appendText(String s) { 83: this .runOnUiThread(new UpdateTextRunner(s, UpdateType.Append)); 84:
}
85:
86: public native void initTextGenerator(); 87: public native void stopTextGenerator(); 88: public native void runTextGenerator(); 89:
90: private TextView mTV; 91: private ArrayList mLines = new ArrayList(); 92: private int mMaxLineCount = 20; 93:
94: private TextUpdatorThread mThread; 95:
96: static { 97: System.loadLibrary("sample" ); // the corresponding C library is libsample.so 98:
}
99:
}
(俞怡炜) |