android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Press me to say hello !"
/>
package test.widget;
import test.widget.R;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class ButtonTest extends Activity {
Activity me;
Button buttonHello;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
me = this;
buttonHello = (Button) this.findViewById(R.id.buttonHello);
buttonHello.setOnClickListener(buttonHelloListener);
}
private View.OnClickListener buttonHelloListener
= new View.OnClickListener() {
public void onClick(View arg0) {
me.showAlert("Title", "Hello!", "OK", true);
}
};
}
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1.0" />
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1.0"
android:layout_gravity="center_horizontal"
android:text=""/>
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1.0"/>
package test.clock;
import test.clock.R;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.view.View;
import android.widget.TextView;
import java.util.Calendar;
public class DigitalClock extends Activity {
View view;
TextView timeTextView = null ;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle icicle) {
super .onCreate(icicle);
setContentView(R.layout.main );
view = this .getCurrentFocus();
timeTextView = (TextView) this .findViewById(R.id.timeTextView );
timeTextView.setTextSize(48);
Message msg = mHandler.obtainMessage(CLOCK );
mNextTime = SystemClock.uptimeMillis ();
mHandler.sendMessageAtTime(msg, mNextTime);
}
private static final int CLOCK = 1;
private long mNextTime;
private final Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
if (msg.what == CLOCK ) {
long current = SystemClock.uptimeMillis ();
mNextTime = current + 1000;
msg = obtainMessage(CLOCK );
sendMessageAtTime(msg, mNextTime);
String timeStr = String.format ("%tT", Calendar.getInstance ());
timeTextView.setText(timeStr);
}
}
};
}
第八章 資源的使用 8
8.1 Android中的資源概念 8.2 Simple Values Colors
Strings
Dimensions
8.3 Drawables 8.4 Animation 8.5 Layout 8.6 Style 8.7 8.8
9
9.3 Bundle 9.4 Message import android.app.ListActivity;
import android.content.Intent;
import android.content.PackageManager;
import android.content.PackageManager.ResolveInfo;
import android.os.Bundle;
import android.view.View;
import android.widget.ListView;
import android.widget.SimpleAdapter;
自從全球資訊網 Web 被建立以後,文字型的資料處理就一直是程式設計師所必需具備的基本技巧,目前最常見的三種文字處理技術是 1. 字串物件 2. Regular Expression 比對 3. XML 文件處理.
10
java.lang
java.text
android.text Provides classes used to render or track text and text spans on the screen.
android.text.method Provides classes that monitor or modify keypad input.
android.text.style Provides classes used to view or change the style of a span of text in a View object.
android.text.util
java.util.regex
android.sax
javax.xml.parsers
org.json
org.w3c.dom
org.xml.sax This package provides the core SAX APIs.
org.xml.sax.ext This package contains interfaces to SAX2 facilities that conformant SAX drivers won't necessarily support.
org.xml.sax.helpers This package contains "helper" classes, including support for bootstrapping SAX-based applications.
11
第1節 SharedPreferences
Preference 是 Android 中用來儲存資料最簡單的一種方法,我們可以使用 :Context.getSharedPreferences() 或 Activity.getPreferences() 取得儲存的變數,或對某一 Preference變數的 editor 物件進行 put 動作以儲存資料,但這些共用資料只能在同一個 Package 底下使用。
以下是使用 Preference 來設定一個小計算機中按鍵模式keypress 的範例程式:
public class Calc extends Activity {
public static final String PREFS_NAME = "MyPrefsFile";
...
@Override
protected void onCreate(Bundle state){
super.onCreate(state);
...
// Restore preferences
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
boolean silent = settings.getBoolean("silentMode", false);
setSilent(silent);
}
@Override
protected void onStop(){
super.onStop();
// Save user preferences. We need an Editor object to
// make changes. All objects are from android.context.Context
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("silentMode", mSilentMode);
// Don't forget to commit your edits!!!
editor.commit();
}
}
第2節 Files
Context.openFileOutput() and Context.openFileInput()
If you have static files to package with your application at compile time, you can save your file in your project in res/raw/
, and then get it with Resources.openRawResource (R.raw.mydatafile).
To understand why we cannot use standard java file access, like:
Java:
FileWriter f = new FileWriter("impossible.txt");
// throws: 'java.io.FileNotFoundException: /impossible.txt '
, we have to understand the Security-Model of Android.
Each *.apk File that is installed on the Emulator/Device gets its own User-ID from the Linux System. This ID is the key to the sandbox of the application. This 'sandbox' protects the application (and its files) from other bad Twisted Evil apps, that i.e. want to manipulate the files we created in a bad manner (Like writing into them: "Whos reads this is... dumb ! Hhahaha").
Note wrote:
But, writing to SD-Cards is still possible with 'normal' Java methods Exclamation
Java:
FileWriter f = new FileWriter("/sdcard/download/impossible.txt");
will work without any problem, you just need to add virtual sdcard to your emulator.
第3節 Sqlite
To create a database, use Context.createDatabase() and Context.openDatabase(), and read and write this data as appropriate
第4節 Content Provider
Android 中要跨越應用存取資料,Content Provider 是唯一的方法,Content Provider 是可以被所有應用存取得一種物件。
Android 的網路函式庫採用了標準的 java.net.* 中的網路函式庫,包含 Socket, URL, InetAddress, …. 等物件,並且將 Android 所擴充的物件放在 android.net.* 中,以補充原先 java 網路函數上的不足,另外、Android 也從 apache當中取用了 httpClient 的函式庫以形成更完整的網路架構。
12
XMPP : ineXtensible Messaging and Presence Protocol
Totally *Unofficial* Android GTalk Client (Send/Receive XMPP Messages)
http://davanum.wordpress.com/2007/11/23/totally-unofficial-android-gtalk-client-sendreceive-xmpp-messages/
package org.apache.gtalk;
import android.app.Activity;
import android.app.NotificationManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.database.Cursor;
import android.os.Bundle;
import android.os.DeadObjectException;
import android.os.IBinder;
import android.provider.Im;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.*;
import com.google.android.xmppService.IXmppService;
import com.google.android.xmppService.IXmppSession;
import com.google.android.xmppService.Presence;
public class GTalkClient extends Activity implements View.OnClickListener {
private static final String LOG_TAG = "GTalkClient";
IXmppSession mXmppSession = null ;
EditText mSendText;
ListView mListMessages;
EditText mRecipient;
Button mSend;
Button mSetup;
/**
* Called with the activity is first created.
*/
@Override
public void onCreate(Bundle icicle) {
super .onCreate(icicle);
setContentView(R.layout.main);
// gather the troops
mSendText = (EditText) findViewById(R.id.sendText);
mListMessages = (ListView) findViewById(R.id.listMessages);
mRecipient = (EditText) findViewById(R.id.recipient);
mSend = (Button) findViewById(R.id.send);
mSetup = (Button) findViewById(R.id.setup);
// set up handler for on click
mSetup.setOnClickListener(this );
mSend.setOnClickListener(this );
bindService((new Intent()).setComponent(
com.google.android.xmppService.XmppConstants.XMPP_SERVICE_COMPONENT),
null , mConnection, 0);
}
/**
* Let the user know there was an issue
*
* @param msg
*/
private void logMessage(CharSequence msg) {
NotificationManager nm = (NotificationManager) getSystemService(
Context.NOTIFICATION_SERVICE);
nm.notifyWithText(123, msg, NotificationManager.LENGTH_LONG, null );
}
/**
* Setup the XMPP Session using a service connection
*/
private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
// This is called when the connection with the XmppService has been
// established, giving us the service object we can use to
// interact with the service. We are communicating with our
// service through an IDL interface, so get a client-side
// representation of that from the raw service object.
IXmppService xmppService = IXmppService.Stub.asInterface(service);
try {
mXmppSession = xmppService.getDefaultSession();
if (mXmppSession == null ) {
// this should not happen.
logMessage(getText(R.string.xmpp_session_not_found));
return ;
}
mXmppSession.setPresence(new Presence(Im.PresenceColumns.AVAILABLE, "Am here now!"));
} catch (DeadObjectException ex) {
Log.e(LOG_TAG, "caught " + ex);
logMessage(getText(R.string.found_stale_xmpp_service));
}
mSendText.setEnabled(true );
}
public void onServiceDisconnected(ComponentName componentName) {
// This is called when the connection with the service has been
// unexpectedly disconnected -- that is, its process crashed.
mXmppSession = null ;
mSendText.setEnabled(false );
}
};
/**
* Handle clicks on the 2 buttions
*
* @param view
*/
public void onClick(View view) {
if (view == mSetup) {
Log.i(LOG_TAG, "onClick - Setup");
// Run a query against CONTENT_URI = "content://im/messages"
Cursor cursor = managedQuery(Im.Messages.CONTENT_URI, null ,
"contact=/'" + mRecipient.getText().toString() + "/'", null , null );
// Display the cursor results in a simple list
// Note that the adapter is dyamic (picks up new entries automatically)
ListAdapter adapter = new SimpleCursorAdapter(this ,
android.R.layout.simple_list_item_1,
cursor, // Give the cursor to the list adatper
new String[]{Im.MessagesColumns.BODY},
new int []{android.R.id.text1});
this .mListMessages.setAdapter(adapter);
} else if (view == mSend) {
// use XmppService to send data message to someone
String username = mRecipient.getText().toString();
if (!isValidUsername(username)) {
logMessage(getText(R.string.invalid_username));
return ;
}
if (mXmppSession == null ) {
logMessage(getText(R.string.xmpp_service_not_connected));
return ;
}
try {
mXmppSession.sendTextMessage(username, 0, mSendText.getText().toString());
} catch (DeadObjectException ex) {
Log.e(LOG_TAG, "caught " + ex);
logMessage(getText(R.string.found_stale_xmpp_service));
mXmppSession = null ;
}
}
}
private boolean isValidUsername(String username) {
return !TextUtils.isEmpty(username) && username.indexOf('@') != -1;
}
}
Android 中所採用的瀏覽器是 WebKit,和 iPhone 中的一樣,要控置瀏覽器很簡單,只要 import android.webkit.WebView 後,呼叫 loadUrl() 函數載入網頁即可。
package test.web;
import android.app.Activity;
import android.os.Bundle;
import android.webkit.WebView;
public class WebViewTest extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle icicle) {
super .onCreate(icicle);
WebView webView = new WebView(this );
webView.loadUrl("http://www.google.com/pda/");
setContentView(webView);
}
}
第十三章 二維繪圖功能 Android 中的二維繪圖功能主要在 android.graphics 函式庫中,重要的物件有 Bitmap, Canvas, Paint 等等,
13
13.1 Android 的繪圖相關物件 android.graphics.Camera
android.graphics.drawable.Drawable
Paint
setStyle
setColor
setStrokeWidth(strokeWidth);
setAntiAlias(true);
setARGB(255, 255, 255, 255);
Path
PathEffect
Matrix
.setPolyToPoly(src, 0, dst, 0, src.length >> 1);
Paint.FontMetrics
mFontMetrics = mPaint.getFontMetrics();
13.2 繪製基本圖形 13.3 整合練習 - 繪圖版範例
package test.paint;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
public class PaintActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle icicle) {
super .onCreate(icicle);
setContentView(new PaintView(this ));
}
}
class PaintView extends View {
Bitmap mBitmap;
Canvas mCanvas;
private final Paint mPaint;
private int strokeWidth = 2;
public PaintView(Context c) {
super (c);
mPaint = new Paint();
mPaint.setStrokeWidth(strokeWidth);
mPaint.setAntiAlias(true );
mPaint.setARGB(255, 255, 255, 255);
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
int curW = mBitmap != null ? mBitmap.width() : 0;
int curH = mBitmap != null ? mBitmap.height() : 0;
if (curW >= w && curH >= h) {
return ;
}
if (curW < w) curW = w;
if (curH < h) curH = h;
Bitmap newBitmap = Bitmap.createBitmap (curW, curH, false );
Canvas newCanvas = new Canvas();
newCanvas.setDevice(newBitmap);
if (mBitmap != null ) {
newCanvas.drawBitmap(mBitmap, 0, 0, null );
}
mBitmap = newBitmap;
mCanvas = newCanvas;
}
@Override
protected void onDraw(Canvas canvas) {
if (mBitmap != null ) {
canvas.drawBitmap(mBitmap, 0, 0, null );
}
}
private int mCurX, mCurY, mLastX, mLastY;
boolean isDown = false ;
@Override
public boolean onMotionEvent(MotionEvent event) {
mCurX = (int )event.getX();
mCurY = (int )event.getY();
int action = event.getAction();
if (action == MotionEvent.ACTION_DOWN ) {
isDown = true ;
mLastX = mCurX;
mLastY = mCurY;
}
if (action == MotionEvent.ACTION_UP ) {
isDown = false ;
}
if (isDown && action == MotionEvent.ACTION_MOVE ) {
if (mBitmap != null ) {
mCanvas.drawLine(mLastX, mLastY, mCurX, mCurY, mPaint);
invalidate();
}
mLastX = mCurX;
mLastY = mCurY;
}
return true ;
}
}
14
14.1
Bitmap
createBitmap(int[] colors, int width, int height, boolean hasAlpha)
int getPixel(int x, int y)
int height()
void setPixels(int[] pixels, int offset, int stride, int x, int y, int width, int height)
int width()
Canvas :
setDevice()
boolean clipPath(Path path, ClipMode mode)
boolean clipRect(float left, float top, float right, float bottom)
Intersect the current clip with the specified rectangle, which is expressed in local coordinates.
void drawBitmap(Bitmap bitmap, Rect src, Rect dst, Paint paint)
void drawBitmap(Bitmap bitmap, float left, float top, Paint paint)
void drawBitmap(Bitmap bitmap, Rect src, RectF dst, Paint paint)
void drawCircle(float cx, float cy, float radius, Paint paint)
void drawColor(int color)
void drawColor(int color, Mode mode)
void drawLine(float startX, float startY, float stopX, float stopY, Paint paint)
void drawOval(RectF oval, Paint paint)
void drawPaint(Paint paint)
void drawPath(Path path, Paint paint)
void drawPoint(float x, float y, Paint paint)
void drawPoints(float[] pts, int offset, int length, Paint paint)
void drawPoints(float[] pts, Paint paint)
void drawPosText(char[] text, int index, int count, float[] pos, Paint paint)
void drawPosText(String text, float[] pos, Paint paint)
void drawRGB(int r, int g, int b)
void drawRect(RectF rect, Paint paint)
void drawRect(float left, float top, float right, float bottom, Paint paint)
void drawRect(Rect r, Paint paint)
void drawRoundRect(RectF rect, float rx, float ry, Paint paint)
void drawText(String text, int start, int end, float x, float y, Paint paint)
void drawText(char[] text, int index, int count, float x, float y, Paint paint)
void drawText(String text, float x, float y, Paint paint)
void drawText(CharSequence text, int start, int end, float x, float y, Paint paint)
void drawTextOnPath(String text, Path path, float hOffset, float vOffset, Paint paint)
void drawTextOnPath(char[] text, int index, int count, Path path, float hOffset, float vOffset, Paint paint)
14.2 變形與轉換 Android 中二維的動畫功能主要在 android.view.animation 函式庫中,包含兩種動畫功能,第一種是二維轉換 (tweened animation) ,第二種是逐畫面的動畫(frame by frame animation)。
二維轉換總共有四種基本轉換
1. AlphaAnimation 透明度轉換 (transparency changes)
2. RotateAnimation旋轉 (rotations)
3. ScaleAnimation 縮放 (growing or shrinking)
4. TranslateAnimation 位移 (position changes)
描述二維轉換的方式又可分為 1. 使用 XML 2. 使用 Java 程式 兩種方法。
(1) 使用 XML 描述二維轉換
android:interpolator="@android:anim/ease_in_interpolator">
android:toXDelta="30"
android:duration="800"
android:fillAfter="true"/>
android:pivotX="50%"
android:pivotY="50%" >
android:toDegrees="-90"
android:fillAfter="true"
android:startOffset="800"/>
android:toXScale="2.0"
android:fromYScale="1.0"
android:toYScale="2.0"
android:startOffset="800" />
android:fillAfter="true"
android:duration="800"
android:startOffset="1600"/>
(2) 使用 Java 實作二維轉換
// Create root AnimationSet.
AnimationSet rootSet = new AnimationSet(true);
rootSet.setInterpolator(new EaseInInterpolator());
rootSet.setRepeatMode(Animation.NO_REPEAT);
// Create and add first child, a motion animation.
TranslateAnimation trans1 = new TranslateAnimation(0, 30, 0, 0);
trans1.setStartOffset(0);
trans1.setDuration(800);
trans1.setFillAfter(true);
rootSet.addAnimation(trans1);
// Create a rotate and a size animation.
RotateAnimation rotate = new RotateAnimation(
0,
-90,
RotateAnimation.RELATIVE_TO_SELF, 0.5f,
RotateAnimation.RELATIVE_TO_SELF, 0.5f);
rotate.setFillAfter(true);
rotate.setDuration(800);
ScaleAnimation scale = new ScaleAnimation(
1, 2, 1, 2, // From x, to x, from y, to y
ScaleAnimation.RELATIVE_TO_SELF, 0.5f,
ScaleAnimation.RELATIVE_TO_SELF, 0.5f);
scale.setDuration(800);
scale.setFillAfter(true);
// Add rotate and size animations to a new set,
// then add the set to the root set.
AnimationSet childSet = new AnimationSet(true);
childSet.setStartOffset(800);
childSet.addAnimation(rotate);
childSet.addAnimation(scale);
rootSet.addAnimation(childSet);
// Add a final motion animation to the root set.
TranslateAnimation trans2 = new TranslateAnimation(0, 0, 0, -100);
trans2.setFillAfter(true);
trans2.setDuration(800);
trans2.setStartOffset(1600);
rootSet.addAnimation(trans2);
// Start the animation.
animWindow.startAnimation(rootSet);
載入與啟動二維轉換
// Hook into the object to be animated.
TextView animWindow = (TextView)findViewById(R.id.anim);
// Load the animation from XML (XML file is res/anim/move_animation.xml).
Animation anim = AnimationUtils.loadAnimation(AnimationSample.this, R.anim.move_animation);
anim.setRepeatMode(Animation.NO_REPEAT);
// Play the animation.
animWindow.startAnimation(anim);
14.3
Android 使用 OpenGL這個 3D 動畫遊戲引擎的嵌入式版本,稱為 OpenGL|ES,這和 J2ME 中的 JSR239 OpenGL ES API 大至上是相同的,但並不完全一樣。
15
在 Android 中使用 OpenGL 時,首先要先繼承 View 這個物件,然後在程式中取得 OpenGLContext 這個物件,接著在 onDraw() 這個函數中執行對應的繪圖的功能,以下是一個範例。
class GLView extends View
{
public GLView(Context context)
{
…
mGLContext = new OpenGLContext(0);
…
}
@Override
protected void onDraw(Canvas canvas) {
…
GL10 gl = (GL10)(mGLContext.getGL());
…
mGLContext.waitNative(canvas, this);
…
gl.glViewport(0, 0, w, h);
float ratio = (float)w / h;
gl.glMatrixMode(gl.GL_PROJECTION);
gl.glLoadIdentity();
gl.glFrustumf(-ratio, ratio, -1, 1, 2, 12);
gl.glDisable(gl.GL_DITHER);
gl.glClearColor(1,1,1,1);
gl.glEnable(gl.GL_SCISSOR_TEST);
gl.glScissor(0, 0, w, h);
gl.glClear(gl.GL_COLOR_BUFFER_BIT);
gl.glMatrixMode(gl.GL_MODELVIEW);
gl.glLoadIdentity();
gl.glTranslatef(0, 0, -3.0f);
gl.glScalef(0.5f, 0.5f, 0.5f);
gl.glRotatef(mAngle, 0, 1, 0);
gl.glRotatef(mAngle*0.25f, 1, 0, 0);
gl.glColor4f(0.7f, 0.7f, 0.7f, 1.0f);
gl.glEnableClientState(gl.GL_VERTEX_ARRAY);
gl.glEnableClientState(gl.GL_COLOR_ARRAY);
gl.glEnable(gl.GL_CULL_FACE);
mCube.draw(gl);
mAngle += 1.2f;
mGLContext.waitGL();
…
}
…
}
Android 的 android.media.MediaPlayer 函式庫提供了影片與聲音的播放功能,另外也在android.media.MediaRecorder中提供了錄音與錄影的功能,但這些功能在模擬器當中將無法運作,只有真實的手機才會具備此功能。
您可播放位於程式資源資料夾中的影音資源,也可以播放檔案系統中的影音檔,甚至播放網路上的影音檔案,但方法稍有差異。
16
MediaPlayer mp = MediaPlayer.create(context, R.raw.sound_file_1);
mp.prepare();
mp.start();
MediaPlayer mp = new MediaPlayer();
mp.setDataSource(PATH_TO_FILE);
mp.prepare();
mp.start();
ContentURI myURL = new ContentURI("http://myserver.com/link/to/my.mp3");
Intent intent = new Intent(Intent.VIEW_ACTION, myURL);
intent.setType("audio/*");
startActivity(intent);
Bitmap copyWindowBitmap()
Return a copy of the bitmap holding the overall contents of the window this view is attached to.
void getAbsoluteLocationOnScreen(int[] location)
Computes the coordinates of this view on the screen.
16.5 錄音與錄影 1. 啟動錄製功能
recorder = new MediaRecorder();
ContentValues values = new ContentValues(3);
values.put(Video.MediaColumns.TITLE, SOME_NAME_HERE);
values.put(Video.MediaColumns.TIMESTAMP, System.currentTimeMillis());
values.put(Video.MediaColumns.MIME_TYPE, recorder.getMimeContentType());
contentResolver = new ContentResolver();
ContentURI base = Video.Media.INTERNAL_CONTENT_URI;
ContentURI newUri = contentResolver.insert(base, values);
if (newUri == null) {
// need to handle exception here - we were not able to create a new
// content entry
}
String path = contentResolver.getDataFilePath(newUri);
// could use setPreviewDisplay() to display a preview to suitable View here
recorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
recorder.setVideoSize(176, 144); // QCIF
recorder.setVideoFrameRate(15);
recorder.setVideoEncoder(MediaRecorder.VideoEncoder.H263);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
recorder.setOutputFile(path);
recorder.prepare();
recorder.start();
2. 停止錄製功能
recorder.stop();
recorder.release();
package test.camera;
import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.PixelFormat;
import android.hardware.CameraDevice;
import android.os.Bundle;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.Window;
// ----------------------------------------------------------------------
public class CameraTest extends Activity
{
@Override
protected void onCreate(Bundle icicle)
{
super .onCreate(icicle);
// Hide the window title.
requestWindowFeature(Window.FEATURE_NO_TITLE );
// Make sure to create a TRANSLUCENT window. This is recquired
// for SurfaceView to work. Eventually this'll be done by
// the system automatically.
getWindow().setFormat(PixelFormat.TRANSLUCENT );
// Create our Preview view and set it as the content of our
// Activity
mPreview = new Preview(this );
setContentView(mPreview);
}
@Override
protected boolean isFullscreenOpaque() {
// Our main window is set to translucent, but we know that we will
// fill it with opaque data. Tell the system that so it can perform
// some important optimizations.
return true ;
}
@Override
protected void onResume()
{
// Because the CameraDevice object is not a shared resource,
// it's very important to release it when the activity is paused.
super .onResume();
mPreview.resume();
}
@Override
protected void onPause()
{
// Start Preview again when we resume.
super .onPause();
mPreview.pause();
}
private Preview mPreview;
}
// ----------------------------------------------------------------------
class Preview extends SurfaceView implements SurfaceHolder.Callback
{
Preview(Context context) {
super (context);
// Install a SurfaceHolder.Callback so we get notified when the
// underlying surface is created and destroyed.
mHolder = getHolder();
mHolder.setCallback(this );
mHasSurface = false ;
// In this example, we hardcode the size of the preview. In a real
// application this should be more dynamic. This guarantees that
// the uderlying surface will never change size.
mHolder.setFixedSize(320, 240);
}
public void resume() {
// We do the actual acquisition in a separate thread. Create it now.
if (mPreviewThread == null ) {
mPreviewThread = new PreviewThread();
// If we already have a surface, just start the thread now too.
if (mHasSurface == true ) {
mPreviewThread.start();
}
}
}
public void pause() {
// Stop Preview.
if (mPreviewThread != null ) {
mPreviewThread.requestExitAndWait();
mPreviewThread = null ;
}
}
public boolean surfaceCreated(SurfaceHolder holder) {
// The Surface has been created, start our main acquisition thread.
mHasSurface = true ;
if (mPreviewThread != null ) {
mPreviewThread.start();
}
// Tell the system that we filled the surface in this call.
// This is a lie to preven the system to fill the surface for us
// automatically.
// THIS IS REQUIRED because other wise we'll access the Surface object
// from 2 different threads which is not allowd (And will crash
// currently).
return true ;
}
public void surfaceDestroyed(SurfaceHolder holder) {
// Surface will be destroyed when we return. Stop the preview.
mHasSurface = false ;
pause();
}
public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
// Surface size or format has changed. This should not happen in this
// example.
}
// ----------------------------------------------------------------------
class PreviewThread extends Thread
{
PreviewThread() {
super ();
mDone = false ;
}
@Override
public void run() {
// We first open the CameraDevice and configure it.
CameraDevice camera = CameraDevice.open ();
if (camera != null ) {
CameraDevice.CaptureParams param = new CameraDevice.CaptureParams();
param.type = 1; // preview
param.srcWidth = 1280;
param.srcHeight = 960;
param.leftPixel = 0;
param.topPixel = 0;
param.outputWidth = 320;
param.outputHeight = 240;
param.dataFormat = 2; // RGB_565
camera.setCaptureParams(param);
}
// This is our main acquisition thread's loop, we go until
// asked to quit.
SurfaceHolder holder = mHolder;
while (!mDone) {
// Lock the surface, this returns a Canvas that can
// be used to render into.
Canvas canvas = holder.lockCanvas();
// Capture directly into the Surface
if (camera != null ) {
camera.capture(canvas);
}
// And finally unlock and post the surface.
holder.unlockCanvasAndPost(canvas);
}
// Make sure to release the CameraDevice
if (camera != null )
camera.close();
}
public void requestExitAndWait() {
// don't call this from PreviewThread thread or it a guaranteed
// deadlock!
mDone = true ;
try {
join();
} catch (InterruptedException ex) { }
}
private boolean mDone;
}
SurfaceHolder mHolder;
private PreviewThread mPreviewThread;
private boolean mHasSurface;
}
Android 的電話功能主要在 android.telephony 這個函式庫當中,提供播打與接收電話的功能,其中最重要的兩個物件是 IPhone 和 PhoneNumberUtils。
17
當你想要在程式中呼叫播打電話的功能時,必需在 AndroidManifest.xml 檔案中將允許程式播打電話的權限打開,其指令如下
要建立 IPhone 物件,必需透過 ServiceManager 類別,以下是取得 IPhone 的方法:
private static IPhone getPhoneInterface() throws DeadObjectException {
IServiceManager sm = ServiceManagerNative.getDefault();
IPhone phoneService = IPhone.Stub.asInterface(sm.getService("phone"));
return phoneService;
}
一但取得 IPhone 物件後,即可使用 call 或 dial 來撥打電話,然後使用 endCall 來結束通話。
void call(String number) : Place a call to the numer.
void dial(String number) : Dial a number.
void endCall(boolean hangupOnly) : End call or go to the Home screen
dial 與 call 之間的差別是 dial 會顯示一個撥號介面,其上填入 number 這個電話號碼 (若 number 是 null,則撥號介面中將不會有預設的號碼)。
另一種撥打電話的方法是對一個電話網址 (例如: tel:0988077312) 送出 CALL_ACTION的動作,即可進行通話供能。
另外、你也可以使用 DataStateIntentReceiver 或 PhoneStateIntentReceiver 進行電話事件的註冊,以便取得撥號狀態 (IDLE, RINING, OFF_HOOK)、服務狀態 (in service, out of service, emergency only, powered off, roaming, operator name …)、訊號強度、語音留言、連線狀態 (disconnected、connecting、connected)、資料進出狀態 (data in, data out) 等等。
您也可以透過 TelephonyProperties 中的屬性值,取得許多手機相關的資訊,例如手機的電話號碼、SIM 卡的資訊等等,其方法是使用 os.SystemProperties.get() 函數,傳入 TelephonyProperties 中的對應參數即可取得之,反之、若使用os.SystemProperties.put() 則可設定這些參數。
範例一:取得 IMEI 國際手機代碼
android.os.SystemProperties.get(PROPERTY_IMEI)
範例二:取得手機的電話號碼
android.os.SystemProperties.get(PROPERTY_LINE1_NUMBER)
範例三:取得手機的語音郵件號碼
android.os.SystemProperties.get(PROPERTY_LINE1_VOICE_MAIL_NUMBER)
範例四:取得電信公司的名稱
android.os.SystemProperties.get(PROPERTY_SIM_OPERATOR_ALPHA)
範例五:取得國家的代碼
android.os.SystemProperties.get(PROPERTY_SIM_OPERATOR_ISO_COUNTRY)
與衛星定位相關得兩個函式庫是android.location 與 com.google.android.maps,目前還再草案狀態未定案
18
android.location
預計將支援四種地圖相關資訊 (class、kml、nmea、track),其中的 LocationManager 與 LocationProvider 是核心元件。
要取得 Location Manager 的方式必需透過 Context,方法如下:
LocationManager lm = Context.getSystemService(Context.LOCATION_SERVICE);
try { Intent myIntent = new Intent(android.content.Intent.VIEW_ACTION, new ContentURI("geo:38.899533,-77.036476")); startActivity(myIntent); } catch (URISyntaxException e) { }
com.google.android.maps
此函式庫支援 GoogleMap 應用程式的控制,您可以透過 MapView 物件顯示 GoogleMap,但前題是您的 Activity 必需繼承 MapActivity。
接著您可以透過 MapView 中的getController() 或 getOverlayController() 去控制MapView。
package test.map1;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import android.os.Bundle;
public class MapViewTest1 extends MapActivity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle icicle) {
super .onCreate(icicle);
MapView mapView = new MapView(this );
MapController mc = mapView.getController();
mc.zoomTo(9);
setContentView(mapView);
}
}
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent">
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1" />
android:layout_height="wrap_content"
android:text="InputAddress"
android:selectAllOnFocus="true"/>
package test.map;
import com.google.android.maps.MapActivity;
import android.os.Bundle;
public class MapViewTest extends MapActivity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle icicle) {
super .onCreate(icicle);
setContentView(R.layout.main );
}
}
18.4 在 GoogleMap 上重疊顯示 http://davanum.wordpress.com/2007/11/19/drawing-overlays-for-android-maps-aka-search-for-starbucks/
package org.apache.maps;
import android.graphics.Canvas;
import android.graphics.Paint;
import com.google.android.maps.Overlay;
import com.google.android.maps.Point;
import com.google.googlenav.Placemark;
import com.google.googlenav.Search;
public class MyOverlay extends Overlay {
BrowseMap mMap;
Paint paint1 = new Paint();
Paint paint2 = new Paint();
public MyOverlay(BrowseMap map) {
mMap = map;
paint2.setARGB(255, 255, 255, 255);
}
public void draw(Canvas canvas, PixelCalculator pixelCalculator, boolean b) {
super .draw(canvas, pixelCalculator, b);
Search search = mMap.getSearch();
if (search != null ) {
for (int i = 0; i < search.numPlacemarks(); i++) {
Placemark placemark = search.getPlacemark(i);
int [] screenCoords = new int [2];
Point point = new Point(placemark.getLocation().getLatitude(),
placemark.getLocation().getLongitude());
pixelCalculator.getPointXY(point, screenCoords);
canvas.drawCircle(screenCoords[0], screenCoords[1], 9, paint1);
canvas.drawText(Integer.toString(i + 1),
screenCoords[0] - 4,
screenCoords[1] + 4, paint2);
}
}
}
}
藍芽裝置由於具有獨特的搜尋裝置等特性,因此、某些功能無法納入普通的 TCP/IP 網路功能之下,因此、需要特殊的函式庫支援,在 Android 中,採用的是開放原始碼的 bluez 函式庫 (在 Android 中路徑為 org.bluez)。
19
20
20.1 20.2 檔案瀏覽器 第二十一章 自製視覺化元件 http://code.google.com/android/toolbox/custom-components.html
您可以經由繼承 view, layout,或任何從 View 衍生下來的元件以自製,
These steps provide a high level overview of what you need to know to get started in creating your own components:
1.Extend an existing View class or subclass with your own class.
2. Override some of the methods from the superclass: the superclass methods to override start with 'on', for example, onDraw(), onMeasure(), and onKeyDown().
This is similar to the on... events in Activity or ListActivity that you override for life cycle and other functionality hooks.
3. Use your new extension class: once completed, your new extension class can be used in place of the view upon which it was based, but now with the new functionality
The CustomView sample in the API Demos provides an example of a customized component. The custom component is defined in the LabelView class.
21
21.1 21.2 第二十二章 部署與安裝程式 22
23
附錄三 本書範例程式的使用方法
Windows/preferences
附錄四 Adb 除錯工具的使用
D:/ccc/code/Android/sdk/tools>adb
-d - directs command to a specific device
devices - list all connected devices
device commands:
adb update DATAOPTS
- Flash the specified update file.
If file is not passed, update.zip is used.
adb push
- copy file/dir to device
adb pull
- copy file/dir from device
adb sync [
] - copy host->device only if changed
(see 'adb help all')
adb shell - run remote shell interactively
adb shell - run remote shell command
adb logcat [
] - View device log
adb forward
- forward socket connections
forward specs are one of:
tcp:
local:
dev:
adb install
- push this app to the data partition
adb bugreport - return all information from the device
that should be included in a bug report.
adb help - show this help message
DATAOPTS:
(no option) - don't touch the data partition
-w - wipe the data partition
-d - flash the data partition
bootloader commands:
adb flashall DATAOPTS - reflash the device from the build output tree
adb flash [
] [
] - write to flash
adb send
- write to ram
adb debug - listen to bootloader debuglog
adb bl - send raw bootloader command
scripting:
adb wait-for-bootloader - block until bootloader is online
adb wait-for-device - block until device is online
adb start-server - ensure that there is a server running
adb kill-server - kill the server if it is running
adb get-state - prints: offline | bootloader | device
adb get-product - prints:
adb get-serialno - prints:
networking:
adb ppp
[parameters] - Run PPP over USB.
Note: you should not automatically start a PDP connection.
refers to the tty for PPP stream. Eg. dev:/dev/omap_csmi_tty1
[parameters] - Eg. defaultroute debug dump local notty usepeerdns
adb sync notes: adb sync [
]
can be interpreted in several ways:
- If it not specified, both /system and /data partitions will be updated.
- If it is "system" or "data", only the corresponding partition
is updated.
- If it is a path to a local directory, the name is examined to see if
it points to a directory named ".../system" or ".../data", or if
the directory contains subdirectories with those names. If so, it pushes
the appropriate directory/ies to the device.
- If the name of the local directory does not match ".../system" or
".../data", it is treated like an "system" directory.
- If
points to a nonexistent directory, adb sync will fail.
D:/ccc/code/Android/sdk/tools>adb shell
# sqlite3 /data/data/com.google.android.providers.settings/databases/settings.db
sqlite3 /data/data/com.google.android.providers.settings/databases/settings.db
SQLite version 3.5.0
Enter ".help" for instructions
sqlite> delete from system where _id=99
delete from system where _id=99
...> ;
;
sqlite> ls
ls
...> ;
;
SQL error: near "ls": syntax error
sqlite> .help
.help
.bail ON|OFF Stop after hitting an error. Default OFF
.databases List names and files of attached databases
.dump ?TABLE? ... Dump the database in an SQL text format
.echo ON|OFF Turn command echo on or off
.exit Exit this program
.explain ON|OFF Turn output mode suitable for EXPLAIN on or off.
.header(s) ON|OFF Turn display of headers on or off
.help Show this message
.import FILE TABLE Import data from FILE into TABLE
.indices TABLE Show names of all indices on TABLE
.load FILE ?ENTRY? Load an extension library
.mode MODE ?TABLE? Set output mode where MODE is one of:
csv Comma-separated values
column Left-aligned columns. (See .width)
html HTML
insert SQL insert statements for TABLE
line One value per line
list Values delimited by .separator string
tabs Tab-separated values
tcl TCL list elements
.nullvalue STRING Print STRING in place of NULL values
.output FILENAME Send output to FILENAME
.output stdout Send output to the screen
.prompt MAIN CONTINUE Replace the standard prompts
.quit Exit this program
.read FILENAME Execute SQL in FILENAME
.schema ?TABLE? Show the CREATE statements
.separator STRING Change separator used by output mode and .import
.show Show the current values for various settings
.tables ?PATTERN? List names of tables matching a LIKE pattern
.timeout MS Try opening locked tables for MS milliseconds
.width NUM NUM ... Set column widths for "column" mode
sqlite> select * from system
select * from system
...> ;
;
1|music_volume|3
2|voice_volume|3
3|ringer_volume|2
4|ringer_volume_last_positive_index|2
sqlite> .exit
.exit
# .exit
.exit
.exit: not found
# .quit
.quit
.quit: not found
# .help
.help
.help: not found
# ^C
D:/ccc/code/Android/sdk/tools>
code
在程式中設定
public static void setProxy() {
Properties prop = System.getProperties ();
prop.setProperty("http.proxyHost", "proxy.internal");
prop.setProperty("http.proxyPort", "3128");
prop.setProperty("https.proxyHost", "proxy.internal");
prop.setProperty("https.proxyPort", "3128");
prop.setProperty("ftp.proxyHost", "proxy.internal");
prop.setProperty("ftp.proxyPort", "3128");
prop.setProperty("ftp.nonProxyHosts", "localhost|10.10.*");
prop.setProperty("socksProxyHost", "proxy.internal");
prop.setProperty("socksProxyPort", "3128");
}
在系統中設定
Here is a potential work around. It uses the command line to add an http proxy.
Note: you may need to update the escaping to use for windows.
cd to the location of adb replace the pieces [host_or_IP] and [port] with the correct values for the proxy. So if your proxy is corp_proxy, on port 8080, then in the quotes should be corp_proxy:8080 ---- ./adb shell sqlite3 /data/data/com.google.android.providers.settings/ databases/settings.db "/"INSERT INTO system VALUES(99,'http_proxy',' [host_or_IP]:[port]');/"" ----
To see if it was added correctly you can run the following command line. You should see 99|http_proxy| [host_or_IP]:[port] ---- ./adb shell sqlite3 /data/data/com.google.android.providers.settings/ databases/settings.db "/"SELECT * FROM system/"" ----
To remove the proxy, the following script can be run: --- ./adb shell sqlite3 /data/data/com.google.android.providers.settings/ databases/settings.db "/"DELETE FROM system WHERE _id=99/""
附錄六 Android 的函式庫列表
android
Contains the resource classes used by standard Android applications.
android.app
High-level classes encapsulating the overall Android application model.
android.content
Contains classes for accessing and publishing data on the device.
android.database
Contains classes to explore data returned through a content provider.
android.database.sqlite
Contains the SQLite database management classes that an application would use to manage its own private database.
android.graphics
Provides low level graphics tools such as canvases, color filters, points, and rectangles that let you handle drawing to the screen directly.
android.graphics.drawable
Provides classes to manage a variety of visual elements that are intended for display only, such as bitmaps and gradients.
android.graphics.glutils
Provides a variety of classes to enable using OpenGL for embedded systems (OpenGL ES) to draw graphics on an Android device.
android.hardware
Provides support for hardware devices that may not be present on every Android device.
android.location Classes defining Android location-based and related services.
android.media
android.net
Classes that help with network access, beyond the normal java.net.* APIs.
android.opengl
Provides OpenGL utilities.
android.os
Provides basic operating system services, message passing, and inter-process communication on the device.
android.provider
Provides convenience classes to access the content providers supplied by Android.
android.sax
A framework that makes it easy to write efficient and robust SAX handlers.
android.speech.recognition
Provides classes for speech recogntion.
android.telephony
Provides tools to make, receive, and monitor phone calls and phone status.
android.telephony.gsm
Provides classes to control or read data from GSM phones.
android.text
Provides classes used to render or track text and text spans on the screen.
android.text.method
Provides classes that monitor or modify keypad input.
android.text.style
Provides classes used to view or change the style of a span of text in a View object.
android.text.util
android.util
Provides common utility methods such as date/time manipulation, base64 encoders and decoders, string and number conversion methods, and XML utilities.
android.view
Provides classes that expose basic user interface classes that handle screen layout and interaction with the user.
android.view.animation
Provides classes that handle tweened animations.
android.webkit
Provides tools for browsing the web.
android.widget
The widget package contains (mostly visual) UI elements to use on your Application screen.
com.google.android.maps
com.google.android.xmppService
java.io
java.lang
java.lang.annotation
java.lang.instrument
java.lang.ref
java.lang.reflect
java.math
java.net
java.nio
java.nio.channels
java.nio.channels.spi
java.nio.charset
java.nio.charset.spi
java.security
java.security.acl
java.security.cert
java.security.interfaces
java.security.spec
java.sql
java.text
java.util
java.util.concurrent
Utility classes commonly useful in concurrent programming.
java.util.concurrent.atomic
A small toolkit of classes that support lock-free thread-safe programming on single variables.
java.util.concurrent.locks
Interfaces and classes providing a framework for locking and waiting for conditions that is distinct from built-in synchronization and monitors.
java.util.jar
java.util.logging
java.util.prefs
java.util.regex
java.util.zip
javax.crypto
javax.crypto.interfaces
javax.crypto.spec
javax.microedition.khronos.opengles
javax.net
javax.net.ssl
javax.security.auth
javax.security.auth.callback
javax.security.auth.login
javax.security.auth.x500
javax.security.cert
javax.sound.midi
javax.sound.midi.spi
javax.sound.sampled
javax.sound.sampled.spi
javax.sql
javax.xml.parsers
junit.extensions
junit.framework
org.apache.commons.codec
A small set of interfaces used by the various implementations in the sub-packages.
org.apache.commons.codec.binary
Base64, Binary, and Hexadecimal String encoding and decoding.
org.apache.commons.codec.language
Language and phonetic encoders.
org.apache.commons.codec.net
Network related encoding and decoding.
org.apache.commons.httpclient
Classes and interfaces supporting the client side of the HTTP protocol.
org.apache.commons.httpclient.auth
Provides implementation of various authentication schemes as well as utility classes that can be used to authenticate HTTP requests.
org.apache.commons.httpclient.cookie
Provides cookie handling in conjunction with Cookie.
org.apache.commons.httpclient.methods
Classes implementing HttpMethod for the base HTTP methods.
org.apache.commons.httpclient.methods.multipart Provides
Multipart support classes for the MultipartPostMethod.
org.apache.commons.httpclient.params
HttpClient preferences framework.
org.apache.commons.httpclient.protocol
Provides protocol specific socket factory handling.
org.apache.commons.httpclient.util
Provides some utility classes for use by HttpClient.
org.bluez
Provides classes to manage Bluetooth functionality on the device.
org.json
org.w3c.dom
org.xml.sax
This package provides the core SAX APIs.
org.xml.sax.ext
This package contains interfaces to SAX2 facilities that conformant SAX drivers won't necessarily support.
org.xml.sax.helpers
This package contains "helper" classes, including support for bootstrapping SAX-based applications.
附錄八 下列畫面顯示了 Android 中主要的視覺化元件的呈現外觀,這些範例在 Android SDK 中的 AdiDemo 專案中都有展示。
每個 Android 文件都包含下列組成,其中的 XML Attributes 就是記載了其對映 XML 屬性的描述,在摘要與詳細內容兩段都有,整個文件的結構如下:
1. 類別定義 ex : class android.widget.TableRow.LayoutParams
2. See Also : 記載相關類別的資訊
3. Summary : 摘要
l XML Attributes
Ø XML Attributes inherited from class …
Ø Constants inherited from class …
l Fields
Ø Fields inherited from class …
l Public Constructors
Ø
l Protected Methods
Ø Methods inherited from class
4. Detail : 詳細內容
l XML Attributes
Ø XML Attributes inherited from class …
Ø Constants inherited from class …
l Fields
Ø Fields inherited from class …
l Public Constructors
Ø …
l Protected Methods
Ø Methods inherited from class
android.widget public static class
android.widget.TableRow.LayoutParams
This set of layout parameters enforces the width of each child to be FILL_PARENT and the height of each child to be WRAP_CONTENT .
See Also
· TableLayout.LayoutParams
Summary
XML Attributes
XML Attributes inherited from class android.widget.LinearLayout.LayoutParams
android:layout_gravity , android:layout_weight
XML Attributes inherited from class android.view.ViewGroup.MarginLayoutParams
android:layout_marginBottom , android:layout_marginLeft , android:layout_marginRight , android:layout_marginTop
Attribute name
Related methods
android:layout_marginBottom
setMargins(int,int,int,int)
Specifies extra space on the bottom side of this view.
android:layout_marginLeft
setMargins(int,int,int,int)
Specifies extra space on the left side of this view.
android:layout_marginRight
setMargins(int,int,int,int)
Specifies extra space on the right side of this view.
android:layout_marginTop
setMargins(int,int,int,int)
Specifies extra space on the top side of this view.
XML Attributes inherited from class android.view.ViewGroup.LayoutParams
android:layout_height , android:layout_width
Constants inherited from class android.view.ViewGroup.LayoutParams
FILL_PARENT , WRAP_CONTENT
Value
int
FILL_PARENT
Special value for the height or width requested by a View.
-1
0xffffffff
int
WRAP_CONTENT
Special value for the height or width requested by a View.
-2
0xfffffffe
Fields
public
int
column
The column index of the cell represented by the widget.
public
int
span
The number of columns the widgets spans over.
Fields inherited from class android.widget.LinearLayout.LayoutParams
gravity , weight
public
int
gravity
Gravity for the view associated with these LayoutParams.
public
float
weight
Indicates how much of the extra space in the LinearLayout will be allocated to the view associated with these LayoutParams.
Fields inherited from class android.view.ViewGroup.MarginLayoutParams
bottomMargin , leftMargin , rightMargin , topMargin
public
int
bottomMargin
The bottom margin in pixels of the child.
public
int
leftMargin
The left margin in pixels of the child.
public
int
rightMargin
The right margin in pixels of the child.
public
int
topMargin
The top margin in pixels of the child.
Fields inherited from class android.view.ViewGroup.LayoutParams
height , width
public
int
height
Information about how tall the view wants to be.
public
int
width
Information about how wide the view wants to be.
Public Constructors
Protected Methods
Methods inherited from class android.widget.LinearLayout.LayoutParams
debug
String
debug (String output)
Returns a String representation of this set of layout parameters.
Methods inherited from class android.view.ViewGroup.MarginLayoutParams
setMargins
void
setMargins (int left, int top, int right, int bottom)
Sets the margins, in pixels.
Methods inherited from class android.view.ViewGroup.LayoutParams
debug , setBaseAttributes , sizeToString
Methods inherited from class java.lang.Object
clone , equals , finalize , getClass , hashCode , notify , notifyAll , toString , wait , wait , wait
Object
clone ()
Answers a new instance of the same class as the receiver, whose slots have been filled in with the values in the slots of the receiver.
boolean
equals (Object o)
Compares the argument to the receiver, and answers true if they represent the same object using a class specific comparison.
void
finalize ()
Called by the virtual machine when there are no longer any (non-weak) references to the receiver.
final
Class
getClass ()
Answers the unique instance of java.lang.Class which represents the class of the receiver.
int
hashCode ()
Answers an integer hash code for the receiver.
final
void
notify ()
Causes one thread which is wait ing on the receiver to be made ready to run.
final
void
notifyAll ()
Causes all threads which are wait ing on the receiver to be made ready to run.
String
toString ()
Answers a string containing a concise, human-readable description of the receiver.
final
void
wait (long time, int frac)
Causes the thread which sent this message to be made not ready to run either pending some change in the receiver (as indicated by notify or notifyAll) or the expiration of the timeout.
final
void
wait (long time)
Causes the thread which sent this message to be made not ready to run either pending some change in the receiver (as indicated by notify or notifyAll) or the expiration of the timeout.
final
void
wait ()
Causes the thread which sent this message to be made not ready to run pending some change in the receiver (as indicated by notify or notifyAll).
Details
XML Attributes
android:layout_column
The index of the column in which this child should be.
Related Methods
android:layout_span
Defines how many columns this child should span. Must be >= 1.
Related Methods
Fields
public int column
The column index of the cell represented by the widget.
public int span
The number of columns the widgets spans over.
Public Constructors
public TableRow.LayoutParams( Context c, AttributeSet attrs)
public TableRow.LayoutParams(int w, int h)
Sets the child width to ViewGroup.LayoutParams and the child height to WRAP_CONTENT .
Parameters
public TableRow.LayoutParams(int w, int h, float initWeight)
Sets the child width to ViewGroup.LayoutParams and the child height to WRAP_CONTENT .
Parameters
w
ignored
h
ignored
initWeight
ignored
public TableRow.LayoutParams()
Sets the child width to ViewGroup.LayoutParams and the child height to WRAP_CONTENT .
public TableRow.LayoutParams(int column)
Puts the view in the specified column.
Sets the child width to ViewGroup.LayoutParams and the child height to WRAP_CONTENT .
Parameters
column
the column index for the view
Protected Methods
protected void setBaseAttributes( StyledAttributes a, int widthAttr, int heightAttr)
Fixes the child's width to FILL_PARENT and the child's height to WRAP_CONTENT .
Parameters
a
the styled attributes set
widthAttr
the width attribute to fetch
heightAttr
the height attribute to fetch
Android 的 DVM 所採用的是 register based machine,與 Sun 的 Stack Based machine 不同,而 Android 本身並不自稱 Java ,但實際上卻是 100 % 的 Java,Android 為了迴避 Sun 採用了一些迂迴策略,
附錄十一 常見的錯誤狀況與解決方式 要連接 Google Map 請設定 XMPP Setting,加入你的 Gmail Account
Hey guys I've been peacfully coding for about a week now with only a few problems, but right now out of goddamn nowhere the emulator started giving me that exception out of nowhere:
Java:
An error has occurred in process com.google.process.content. Unable to start receiver com.google.android.xmppService.ServiceAutoStart: java.lang.NullPointerException.
I changed only little in my code so I don't believe it is really my fault Now I cannot even run the Browser and the Maps without getting an NullPointerException Help pls.. mrocket
Hello mrocket, Up to now there are only two possible solutions for this problem. On both you should save your data (database / other files - BEFORE ) 1.) Start the emulator once with "-wipe-data" on Additional Cmd-Line-Options:
or 2.) Delete the emulator-image (userdata.img ) located at: WinXP: "C:/Documents and Settings/
/Local Settings/Application Data/Android/"
WinVista: "C:/Users/
/AppData/Local/Android/"
Both should fix it!
Regards,
plusminus
_________________
| Android Development Community / Tutorials
附錄十二 Android 的內核程式碼 Download : http://code.google.com/p/android/downloads/list
How to Make : http://blog.chinaunix.net/u/30686/showart_433547.html
download zip file( android_sdk_linux_m3-rc22a.zip ) and then install my linux machine(FC7)
I could see kernel's image in ../tools/lib/images directory file name : kernel-qemu, size : 1.2M
1. http://code.google.com/p/android/downloads/list download linux-2.6.23-android-m3-rc20.tar.gz android linux kernel source and uncompress kernel source
2. goldfish architecture configuration file copy to .config goldfish configuration file in kernel/arch/arm/configs/ goldfish_defconfig
3. toolchain http://www.codesourcery.com/gnu_toolchains/arm/download.html checking radio box Target Platform : ARM uClinux Host Platform : IA32 GNU/LINUX and then download...
4. uncompress arm-2007q3-51-arm-uclinuxeabi-i686-pc-linux-gnu.tar after download
5. evironment value setting /etc/bashrc PATH=$PATH:
export PATH
6. kernel compiled by arm-uclinuxeabi-* compiler "make zImage"
7. kernel image(zImage) copy to
/tools/lib/images/
8. execute "emulator -console -debug-kernel -kernel zImage"
9. rename kenel image( zImage ) to kernel-qemu and execute "emulator -console -debug-kernel -kernel kernel-qemu"
注意:工具鏈裡面的gcc一定要選用GCC 3.3.*,GCC 4.2.*有問題。
1. Android - An Open Handset Alliance Project - Open Source Licensing http://code.google.com/android/kb/licensingandoss.html
2. Ryan Paul, Why Google chose the Apache Software License over GPLv2 for Android, Published: November 06, 2007 - 09:26AM CT http://arstechnica.com/news.ars/post/20071106-why-google-chose-the-apache-software-license-over-gplv2.html
3. Installing the SDK http://code.google.com/android/intro/installing.html
4. Download the Android SDK http://code.google.com/android/download.html
5. Package Index http://code.google.com/android/reference/packages.html
6. Android 中文網 http://www.androidcn.net/
7. Android 中文網- Documentation http://www.androidcn.net/wiki/index.php/Documentation
以下、我們將採用預設的 QVGA-L 版本進行操作與使用說明,當你已經安裝 Android 環境後,tools 資料夾下就會具有許多開發 Android 所需要的工具,以筆者的環境而言,我將 Android 環境安裝在 D:/Android/sdk 底下,因此、模擬器emulator.exe 的位置是位於 D:/Android/sdk/tools/ 底下,如下圖所示:
所有评论(0)