轉(zhuǎn)自:http://www.cnblogs.com/webabcd/archive/2010/01/21/1652982.html
介紹
在 Android 中使用 Activity, Service, Broadcast, BroadcastReceiver
活動(Activity) - 用于表現(xiàn)功能
服務(wù)(Service) - 相當(dāng)于后臺運(yùn)行的 Activity
廣播(Broadcast) - 用于發(fā)送廣播
廣播接收器(BroadcastReceiver) - 用于接收廣播
Intent - 用于連接以上各個組件,并在其間傳遞消息
1、演示 Activity 的基本用法,一個 Activity 啟動另一個 Activity,啟動另一個 Activity 時為其傳遞參數(shù),被啟動的 Activity 返回參數(shù)給啟動者的 Activity
- Main.java
-
- 代碼
- 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) {
-
-
- 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);
-
-
-
-
-
-
- startActivityForResult(intent, 0);
- }
- });
-
- Log.d("MyDebug", "onCreate");
- }
-
-
- @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");
- }
- }
-
- MyActivity.java
-
- 代碼
- 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;
-
-
- 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();
- }
- });
- }
- }
-
-
- AndroidManifest.xml
-
- 代碼
- <?xml version="1.0" encoding="utf-8"?>
- <manifest xmlns:android="http://schemas.android.com/apk/res/android"
- package="com.webabcd.activity" android:versionCode="1"
- android:versionName="1.0">
- <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 ,則都要在這里做相應(yīng)的配置
- -->
- <activity android:name=".MyActivity" android:label="Activity 2" />
- </application>
- <uses-sdk android:minSdkVersion="3" />
- </manifest>
-
-
- 2、Service, Broadcast, BroadcastReceiver 的演示
- Main.java
-
- 代碼
- 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;
-
- @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);
-
-
- receiver = new UpdateReceiver();
- IntentFilter filter = new IntentFilter();
-
- filter.addAction("com.webabcd.service.msg");
-
-
-
- this.registerReceiver(receiver, filter);
-
-
- }
-
- @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;
- }
- }
-
-
- private ServiceConnection conn = new ServiceConnection() {
- @Override
- public void onServiceConnected(ComponentName className, IBinder service) {
-
- }
- @Override
- public void onServiceDisconnected(ComponentName className) {
-
- }
- };
-
- private String msg="";
- private UpdateReceiver receiver;
-
- public class UpdateReceiver extends BroadcastReceiver{
-
- @Override
- public void onReceive(Context context, Intent intent) {
- msg = intent.getStringExtra("msg");
-
- txtMsg.append(msg + "\n");
- }
-
- }
- }
-
- MyService.java
-
- 代碼
- 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 IBinder onBind(Intent intent) {
-
- Log.d("MyDebug", "onBind");
- sendMsg("onBind");
-
-
- return null;
- }
-
- @Override
- public void onCreate() {
-
- super.onCreate();
-
- Log.d("MyDebug", "onCreate");
- sendMsg("onCreate");
- }
-
- @Override
- public void onDestroy() {
-
- super.onDestroy();
-
- Log.d("MyDebug", "onDestroy");
- sendMsg("onDestroy");
- }
-
- @Override
- public void onRebind(Intent intent) {
-
- super.onRebind(intent);
-
- Log.d("MyDebug", "onRebind");
- sendMsg("onRebind");
- }
-
- @Override
- public void onStart(Intent intent, int startId) {
- super.onStart(intent, startId);
-
- Log.d("MyDebug", "onStart");
- sendMsg("onStart");
- }
-
- @Override
- public boolean onUnbind(Intent intent) {
-
- Log.d("MyDebug", "onUnbind");
- sendMsg("onUnbind");
-
-
- return super.onUnbind(intent);
- }
-
-
- private void sendMsg(String msg){
-
- Intent intent = new Intent("com.webabcd.service.msg");
-
- intent.putExtra("msg", msg);
-
- this.sendBroadcast(intent);
- }
- }
-
-
- MyBootReceiver.java
-
- 代碼
- 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);
- }
-
- }
-
-
- AndroidManifest.xml
-
- 代碼
- <?xml version="1.0" encoding="utf-8"?>
- <manifest xmlns:android="http://schemas.android.com/apk/res/android"
- package="com.webabcd.service" android:versionCode="1"
- android:versionName="1.0">
- <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 ,則都要在這里做相應(yīng)的配置
- -->
- <service android:name=".MyService"></service>
-
- <!--
- 注冊一個 BroadcastReceiver
- 其 intent-filter 為 android.intent.action.BOOT_COMPLETED(用于接收系統(tǒng)啟動完畢的 Broadcast)
- -->
- <receiver android:name=".MyBootReceiver">
- <intent-filter>
- <action android:name="android.intent.action.BOOT_COMPLETED" />
- </intent-filter>
- </receiver>
- </application>
-
- <!--
- 接受系統(tǒng)啟動完畢的 Broadcast 的權(quán)限
- -->
- <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
- <uses-sdk android:minSdkVersion="3" />
- </manifest>
-
-
- OK
Main.java代碼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;/** Called when the activity is first created. */@Overridepublic 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() {@Overridepublic void onClick(View v) {// 實例化 Intent,指定需要啟動的 ActivityIntent intent = new Intent();intent.setClass(Main.this, MyActivity.class);// 實例化 Bundle,設(shè)置需要傳遞的參數(shù)Bundle bundle = new Bundle();bundle.putString("name", "webabcd");bundle.putDouble("salary", 100.13);// 將需要傳遞的參數(shù)賦值給 Intent 對象intent.putExtras(bundle);// startActivity(intent); // 啟動指定的 Intent(不等待返回結(jié)果)// Main.this.finish();// 啟動指定的 Intent,并等待返回結(jié)果// 其中第二個參數(shù)如果大于等于零,則返回結(jié)果時會回調(diào) onActivityResult() 方法startActivityForResult(intent, 0);}});Log.d("MyDebug", "onCreate");}// 被啟動的 Activity 返回結(jié)果時的回調(diào)函數(shù)@Overrideprotected 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));}}@Overrideprotected void onStart() {// TODO Auto-generated method stubsuper.onStart();Log.d("MyDebug", "onStart");}@Overrideprotected void onStop() {// TODO Auto-generated method stubsuper.onStop();Log.d("MyDebug", "onStop");}@Overrideprotected void onRestart() {// TODO Auto-generated method stubsuper.onRestart();Log.d("MyDebug", "onRestart");}@Overrideprotected void onPause() {// TODO Auto-generated method stubsuper.onPause();Log.d("MyDebug", "onPause");}@Overrideprotected void onResume() {// TODO Auto-generated method stubsuper.onResume();Log.d("MyDebug", "onResume");}@Overrideprotected void onDestroy() {// TODO Auto-generated method stubsuper.onDestroy();Log.d("MyDebug", "onDestroy");}}MyActivity.java代碼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 所啟動的 Activitypublic class MyActivity extends Activity {Intent intent;/** Called when the activity is first created. */@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);this.setContentView(R.layout.main2);// 獲取啟動者傳遞過來的參數(shù)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) {// 返回參數(shù)給啟動者M(jìn)yActivity.this.setResult(Activity.RESULT_OK, intent);MyActivity.this.finish();}});}}AndroidManifest.xml代碼<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"package="com.webabcd.activity" android:versionCode="1"android:versionName="1.0"><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 ,則都要在這里做相應(yīng)的配置--><activity android:name=".MyActivity" android:label="Activity 2" /></application><uses-sdk android:minSdkVersion="3" /></manifest>2、Service, Broadcast, BroadcastReceiver 的演示Main.java代碼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;/** startService() 和 bindService() 的區(qū)別* startService() - 正常理解就好* bindService() - 使當(dāng)前上下文對象(本例中就是 Activity)通過一個 ServiceConnection 對象邦定到指定的 Service 。這樣,如果上下文對象銷毀了的話,那么其對應(yīng)的 Service 也會被銷毀*/public class Main extends Activity implements OnClickListener {private TextView txtMsg;@Overridepublic 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);// 實例化自定義的 BroadcastReceiverreceiver = new UpdateReceiver();IntentFilter filter = new IntentFilter();// 為 BroadcastReceiver 指定 action ,使之用于接收同 action 的廣播filter.addAction("com.webabcd.service.msg");// 以編程方式注冊 BroadcastReceiver 。配置方式注冊 BroadcastReceiver 的例子見 AndroidManifest.xml 文件// 一般在 OnStart 時注冊,在 OnStop 時取消注冊this.registerReceiver(receiver, filter);// this.unregisterReceiver(receiver);}@Overridepublic 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() {@Overridepublic void onServiceConnected(ComponentName className, IBinder service) {}@Overridepublic void onServiceDisconnected(ComponentName className) {}};private String msg="";private UpdateReceiver receiver;// 實現(xiàn)一個 BroadcastReceiver,用于接收指定的 Broadcastpublic class UpdateReceiver extends BroadcastReceiver{@Overridepublic void onReceive(Context context, Intent intent) {msg = intent.getStringExtra("msg");txtMsg.append(msg + "\n");}}}MyService.java代碼package com.webabcd.service;import android.app.Service;import android.content.Intent;import android.os.IBinder;import android.util.Log;// 演示 Service 的生命周期。具體信息運(yùn)行程序后在 LogCat 中查看public class MyService extends Service {@Overridepublic IBinder onBind(Intent intent) {Log.d("MyDebug", "onBind");sendMsg("onBind");// TODO Auto-generated method stubreturn null;}@Overridepublic void onCreate() {// TODO Auto-generated method stubsuper.onCreate();Log.d("MyDebug", "onCreate");sendMsg("onCreate");}@Overridepublic void onDestroy() {// TODO Auto-generated method stubsuper.onDestroy();Log.d("MyDebug", "onDestroy");sendMsg("onDestroy");}@Overridepublic void onRebind(Intent intent) {// TODO Auto-generated method stubsuper.onRebind(intent);Log.d("MyDebug", "onRebind");sendMsg("onRebind");}@Overridepublic void onStart(Intent intent, int startId) {super.onStart(intent, startId);Log.d("MyDebug", "onStart");sendMsg("onStart");}@Overridepublic boolean onUnbind(Intent intent) {Log.d("MyDebug", "onUnbind");sendMsg("onUnbind");// TODO Auto-generated method stubreturn super.onUnbind(intent);}// 發(fā)送廣播信息private void sendMsg(String msg){// 指定廣播目標(biāo)的 action (注:指定了此 action 的 receiver 會接收此廣播)Intent intent = new Intent("com.webabcd.service.msg");// 需要傳遞的參數(shù)intent.putExtra("msg", msg);// 發(fā)送廣播this.sendBroadcast(intent);}}MyBootReceiver.java代碼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 {// 用于接收滿足條件的 Broadcast(相應(yīng)的 Broadcast 的注冊信息詳見 AndroidManifest.xml ,當(dāng)系統(tǒng)啟動完畢后會調(diào)用這個廣播接收器)@Overridepublic void onReceive(Context arg0, Intent arg1) {Log.d("MyDebug", "onReceive");// 啟動服務(wù)Intent service = new Intent(arg0, MyService.class);arg0.startService(service);}}AndroidManifest.xml代碼<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"package="com.webabcd.service" android:versionCode="1"android:versionName="1.0"><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 ,則都要在這里做相應(yīng)的配置--><service android:name=".MyService"></service><!--注冊一個 BroadcastReceiver其 intent-filter 為 android.intent.action.BOOT_COMPLETED(用于接收系統(tǒng)啟動完畢的 Broadcast)--><receiver android:name=".MyBootReceiver"><intent-filter><action android:name="android.intent.action.BOOT_COMPLETED" /></intent-filter></receiver></application><!--接受系統(tǒng)啟動完畢的 Broadcast 的權(quán)限--><uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" /><uses-sdk android:minSdkVersion="3" /></manifest>OK