編輯:初階開發
Android 的核心由幾個角色組成,彼此透過 Intent 溝通:
這個範例示範:一個 Activity 啟動另一個 Activity、啟動時傳遞參數、被啟動的 Activity 把結果回傳給啟動者。
package com.webabcd.activity;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class Main extends Activity {
TextView txt;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.main);
txt = (TextView) this.findViewById(R.id.txt);
txt.setText("Activity 1");
Button btn = (Button) this.findViewById(R.id.btn);
btn.setText("啟動另一個Activity");
btn.setOnClickListener(new Button.OnClickListener() {
@Override
public void onClick(View v) {
// 指定要啟動的 Activity
Intent intent = new Intent();
intent.setClass(Main.this, MyActivity.class);
// 準備要傳遞的參數
Bundle bundle = new Bundle();
bundle.putString("name", "webabcd");
bundle.putDouble("salary", 100.13);
intent.putExtras(bundle);
// 啟動並等待回傳結果;第二個參數 >= 0 時會回呼 onActivityResult()
startActivityForResult(intent, 0);
}
});
Log.d("MyDebug", "onCreate");
}
// 被啟動的 Activity 回傳結果時的回呼
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK) {
Bundle bundle = data.getExtras();
String name = bundle.getString("name");
double salary = bundle.getDouble("salary");
txt.setText("Activity 1" + "\n名字:" + name + "\n薪水:" + String.valueOf(salary));
}
}
@Override protected void onStart() { super.onStart(); Log.d("MyDebug", "onStart"); }
@Override protected void onStop() { super.onStop(); Log.d("MyDebug", "onStop"); }
@Override protected void onRestart() { super.onRestart(); Log.d("MyDebug", "onRestart"); }
@Override protected void onPause() { super.onPause(); Log.d("MyDebug", "onPause"); }
@Override protected void onResume() { super.onResume(); Log.d("MyDebug", "onResume"); }
@Override protected void onDestroy() { super.onDestroy(); Log.d("MyDebug", "onDestroy"); }
}
package com.webabcd.activity;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
// 被另一個 Activity 啟動的 Activity
public class MyActivity extends Activity {
Intent intent;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.main2);
// 取得啟動者傳來的參數
intent = this.getIntent();
Bundle bundle = intent.getExtras();
String name = bundle.getString("name");
double salary = bundle.getDouble("salary");
TextView txt = (TextView) this.findViewById(R.id.txt);
txt.setText("Activity 2" + "\n名字:" + name + "\n薪水:" + String.valueOf(salary));
Button btn = (Button) this.findViewById(R.id.btn);
btn.setText("返回前一個Activity");
btn.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
MyActivity.this.setResult(Activity.RESULT_OK, intent);
MyActivity.this.finish();
}
});
}
}
凡是用到的 Activity 都必須在此註冊:
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".Main" android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".MyActivity" android:label="Activity 2" />
</application>
重點在於:啟動方用 startActivityForResult() 搭配 Bundle 傳參,被啟動方用 setResult() 把結果塞回 Intent,啟動方的 onActivityResult() 便會收到。若用 startActivity() 則不會等待回傳。
package com.webabcd.service;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;
public class Main extends Activity implements OnClickListener {
private TextView txtMsg;
private String msg = "";
private UpdateReceiver receiver;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
setTitle("android 之 service");
this.findViewById(R.id.btnStart).setOnClickListener(this);
this.findViewById(R.id.btnStop).setOnClickListener(this);
this.findViewById(R.id.btnBind).setOnClickListener(this);
this.findViewById(R.id.btnUnbind).setOnClickListener(this);
txtMsg = (TextView) this.findViewById(R.id.txtMsg);
// 以程式碼方式註冊 BroadcastReceiver
// 通常在 onStart 註冊、onStop 取消註冊
receiver = new UpdateReceiver();
IntentFilter filter = new IntentFilter();
filter.addAction("com.webabcd.service.msg");
this.registerReceiver(receiver, filter);
// this.unregisterReceiver(receiver);
}
@Override
public void onClick(View v) {
Intent intent = new Intent(Main.this, MyService.class);
switch (v.getId()) {
case R.id.btnStart: this.startService(intent); break;
case R.id.btnStop: this.stopService(intent); break;
case R.id.btnBind: this.bindService(intent, conn, Context.BIND_AUTO_CREATE); break;
case R.id.btnUnbind: this.unbindService(conn); break;
}
}
// bindService() 所需的 ServiceConnection
private ServiceConnection conn = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName className, IBinder service) { }
@Override
public void onServiceDisconnected(ComponentName className) { }
};
// 接收指定廣播的 receiver
public class UpdateReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
msg = intent.getStringExtra("msg");
txtMsg.append(msg + "\n");
}
}
}
這個 Service 的主要目的是觀察生命週期,各回呼執行時會印出 Log 並發送廣播:
package com.webabcd.service;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
public class MyService extends Service {
@Override public void onCreate() {
super.onCreate();
Log.d("MyDebug", "onCreate");
sendMsg("onCreate");
}
@Override public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
Log.d("MyDebug", "onStart");
sendMsg("onStart");
}
@Override public IBinder onBind(Intent intent) {
Log.d("MyDebug", "onBind");
sendMsg("onBind");
return null;
}
@Override public boolean onUnbind(Intent intent) {
Log.d("MyDebug", "onUnbind");
sendMsg("onUnbind");
return super.onUnbind(intent);
}
@Override public void onRebind(Intent intent) {
super.onRebind(intent);
Log.d("MyDebug", "onRebind");
sendMsg("onRebind");
}
@Override public void onDestroy() {
super.onDestroy();
Log.d("MyDebug", "onDestroy");
sendMsg("onDestroy");
}
// 發送廣播,action 決定哪些 receiver 會收到
private void sendMsg(String msg) {
Intent intent = new Intent("com.webabcd.service.msg");
intent.putExtra("msg", msg);
this.sendBroadcast(intent);
}
}
開機完成後自動啟動 Service,是實際專案中很常見的需求:
package com.webabcd.service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
public class MyBootReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context arg0, Intent arg1) {
Log.d("MyDebug", "onReceive");
Intent service = new Intent(arg0, MyService.class);
arg0.startService(service);
}
}
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".Main" android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".MyService" />
<!-- 註冊開機廣播接收器 -->
<receiver android:name=".MyBootReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
</application>
<!-- 接收開機完成廣播所需的權限 -->
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
startService() 是「丟出去就不管」,bindService() 則建立持續連結,可透過 IBinder 直接溝通。registerReceiver()(生命週期隨 Activity,記得解除註冊),或在 manifest 中靜態宣告(即使 App 未啟動也能收到)。(本文原發表於編程入門網:https://www.bianceng.cn/OS/extra/201004/16654_4.htm )
Android GridView 網格版面實作:自定義 ImageAdapter
先前提到過 GridView 也是一種 AdapterView,和 ListView 頗為相似。實際用過一輪之後有些心得,在此分享。 思路 1. 既然與 ListVie
Android Permission 列表與 ADT 0.9.9 的權限顯示 Bug
升級到 Android 開發插件 ADT 0.9.9 後,會遇到一個小惱人的問題:無法自動列出系統的 permission 權限列表。往常我們在 androidmanif
自訂 Android DigitalClock 的時間格式
Android 的 DigitalClock 本身沒有直接提供設定時間格式的屬性,但可以透過繼承與覆寫的方式來自訂顯示內容。若只需要讓時鐘顯示小時與分鐘,可以修改原本的格
用 PackageManager 取得所有啟動器應用清單
要列出裝置上所有出現在桌面(Launcher)裡的應用,關鍵是 PackageManager 搭配一個特定的 Intent 組合。以下把實作拆成幾個步驟。 1. 定義一