Android - 活动(Activity), 服务(Service), 广播(Broadcast), 广播接收器(BroadcastReceiver)

June 9, 2011 | tags    | views
Comments 0

 介绍
在 Android 中使用 Activity, Service, Broadcast, BroadcastReceiver
活动(Activity) - 用于表现功能 
服务(Service) - 相当于后台运行的 Activity
广播(Broadcast) - 用于发送广播 
广播接收器(BroadcastReceiver) - 用于接收广播
Intent - 用于连接以上各个组件,并在其间传递消息  


1、演示 Activity 的基本用法,一个 Activity 启动另一个 Activity,启动另一个 Activity 时为其传递参数,被启动的 Activity 返回参数给启动者的 Activity

Java代码 复制代码
  1. Main.java   
  2.   
  3. 代码    
  4. package com.webabcd.activity;   
  5.   
  6. import android.app.Activity;   
  7. import android.content.Intent;   
  8. import android.os.Bundle;   
  9. import android.util.Log;   
  10. import android.view.View;   
  11. import android.widget.Button;   
  12. import android.widget.TextView;   
  13.   
  14. public class Main extends Activity {   
  15.        
  16.     TextView txt;   
  17.        
  18.       
  19.     @Override  
  20.     public void onCreate(Bundle savedInstanceState) {   
  21.         super.onCreate(savedInstanceState);   
  22.         this.setContentView(R.layout.main);   
  23.   
  24.         txt (TextView) this.findViewById(R.id.txt);   
  25.         txt.setText("Activity 1");   
  26.   
  27.         Button btn (Button) this.findViewById(R.id.btn);   
  28.         btn.setText("启动另一个Activity");   
  29.         btn.setOnClickListener(new Button.OnClickListener() {   
  30.             @Override  
  31.             public void onClick(View v) {   
  32.                    
  33.                 // 实例化 Intent,指定需要启动的 Activity   
  34.                 Intent intent new Intent();   
  35.                 intent.setClass(Main.thisMyActivity.class);   
  36.   
  37.                 // 实例化 Bundle,设置需要传递的参数   
  38.                 Bundle bundle new Bundle();   
  39.                 bundle.putString("name""webabcd");   
  40.                 bundle.putDouble("salary"100.13);   
  41.   
  42.                 // 将需要传递的参数赋值给 Intent 对象   
  43.                 intent.putExtras(bundle);   
  44.   
  45.                 // startActivity(intent); // 启动指定的 Intent(不等待返回结果)   
  46.                 // Main.this.finish();   
  47.                    
  48.                 // 启动指定的 Intent,并等待返回结果   
  49.                 // 其中第二个参数如果大于等于零,则返回结果时会回调 onActivityResult() 方法   
  50.                 startActivityForResult(intent, 0);   
  51.             }   
  52.         });   
  53.            
  54.         Log.d("MyDebug""onCreate");   
  55.     }   
  56.        
  57.     // 被启动的 Activity 返回结果时的回调函数   
  58.     @Override  
  59.     protected void onActivityResult(int requestCode, int resultCode, Intent data) {   
  60.         if (resultCode == Activity.RESULT_OK){   
  61.             Bundle bundle data.getExtras();   
  62.                
  63.             String name bundle.getString("name");   
  64.             double salary bundle.getDouble("salary");   
  65.                
  66.             txt.setText("Activity 1" "\n名字:" name "\n薪水:" String.valueOf(salary));   
  67.         }   
  68.     }   
  69.   
  70.     @Override  
  71.     protected void onStart() {   
  72.         // TODO Auto-generated method stub   
  73.         super.onStart();   
  74.            
  75.         Log.d("MyDebug""onStart");   
  76.     }   
  77.   
  78.     @Override  
  79.     protected void onStop() {   
  80.         // TODO Auto-generated method stub   
  81.         super.onStop();   
  82.            
  83.         Log.d("MyDebug""onStop");   
  84.     }   
  85.   
  86.     @Override  
  87.     protected void onRestart() {   
  88.         // TODO Auto-generated method stub   
  89.         super.onRestart();   
  90.            
  91.         Log.d("MyDebug""onRestart");   
  92.     }   
  93.        
  94.     @Override  
  95.     protected void onPause() {   
  96.         // TODO Auto-generated method stub   
  97.         super.onPause();   
  98.            
  99.         Log.d("MyDebug""onPause");   
  100.     }   
  101.   
  102.     @Override  
  103.     protected void onResume() {   
  104.         // TODO Auto-generated method stub   
  105.         super.onResume();   
  106.            
  107.         Log.d("MyDebug""onResume");   
  108.     }   
  109.        
  110.     @Override  
  111.     protected void onDestroy() {   
  112.         // TODO Auto-generated method stub   
  113.         super.onDestroy();   
  114.            
  115.         Log.d("MyDebug""onDestroy");   
  116.     }   
  117. }   
  118.   
  119. MyActivity.java   
  120.   
  121. 代码    
  122. package com.webabcd.activity;   
  123.   
  124. import android.app.Activity;   
  125. import android.content.Intent;   
  126. import android.os.Bundle;   
  127. import android.view.View;   
  128. import android.widget.Button;   
  129. import android.widget.TextView;   
  130.   
  131. // 被另一个 Activity 所启动的 Activity   
  132. public class MyActivity extends Activity {   
  133.        
  134.     Intent intent;   
  135.        
  136.       
  137.     @Override  
  138.     public void onCreate(Bundle savedInstanceState) {   
  139.         super.onCreate(savedInstanceState);   
  140.         this.setContentView(R.layout.main2);   
  141.   
  142.         // 获取启动者传递过来的参数   
  143.         intent this.getIntent();   
  144.         Bundle bundle intent.getExtras();           
  145.         String name bundle.getString("name");   
  146.         double salary bundle.getDouble("salary");   
  147.            
  148.         TextView txt (TextView) this.findViewById(R.id.txt);   
  149.         txt.setText("Activity 2" "\n名字:" name "\n薪水:" String.valueOf(salary));   
  150.   
  151.         Button btn (Button) this.findViewById(R.id.btn);   
  152.         btn.setText("返回前一个Activity");   
  153.         btn.setOnClickListener(new Button.OnClickListener() {   
  154.             public void onClick(View v) {   
  155.                 // 返回参数给启动者   
  156.                 MyActivity.this.setResult(Activity.RESULT_OK, intent);   
  157.                 MyActivity.this.finish();   
  158.             }   
  159.         });   
  160.     }   
  161. }   
  162.   
  163.   
  164. AndroidManifest.xml   
  165.   
  166. 代码    
  167. <?xml version="1.0" encoding="utf-8"?>   
  168. <manifest xmlns:android="http://schemas.android.com/apk/res/android"  
  169.     package="com.webabcd.activity" android:versionCode="1"  
  170.     android:versionName="1.0">   
  171.     <application android:icon="@drawable/icon" android:label="@string/app_name">   
  172.         <activity android:name=".Main" android:label="@string/app_name">   
  173.             <intent-filter>   
  174.                 <action android:name="android.intent.action.MAIN" />   
  175.                 <category android:name="android.intent.category.LAUNCHER" />   
  176.             </intent-filter>   
  177.         </activity>   
  178.         <!--   
  179.             如果有需要用到的 Activity ,则都要在这里做相应的配置   
  180.         -->   
  181.         <activity android:name=".MyActivity" android:label="Activity 2" />   
  182.     </application>   
  183.     <uses-sdk android:minSdkVersion="3" />   
  184. </manifest>    
  185.   
  186.   
  187. 2、Service, Broadcast, BroadcastReceiver 的演示   
  188. Main.java   
  189.   
  190. 代码    
  191. package com.webabcd.service;   
  192.   
  193. import android.app.Activity;   
  194. import android.content.BroadcastReceiver;   
  195. import android.content.ComponentName;   
  196. import android.content.Context;   
  197. import android.content.Intent;   
  198. import android.content.IntentFilter;   
  199. import android.content.ServiceConnection;   
  200. import android.os.Bundle;   
  201. import android.os.IBinder;   
  202. import android.view.View;   
  203. import android.view.View.OnClickListener;   
  204. import android.widget.TextView;   
  205.   
  206.   
  207. public class Main extends Activity implements OnClickListener {   
  208.   
  209.     private TextView txtMsg;   
  210.        
  211.     @Override  
  212.     public void onCreate(Bundle savedInstanceState) {   
  213.         super.onCreate(savedInstanceState);   
  214.         setContentView(R.layout.main);   
  215.   
  216.         setTitle("android 之 service");   
  217.   
  218.         this.findViewById(R.id.btnStart).setOnClickListener(this);   
  219.         this.findViewById(R.id.btnStop).setOnClickListener(this);   
  220.         this.findViewById(R.id.btnBind).setOnClickListener(this);   
  221.         this.findViewById(R.id.btnUnbind).setOnClickListener(this);   
  222.            
  223.         txtMsg (TextView)this.findViewById(R.id.txtMsg);   
  224.            
  225.         // 实例化自定义的 BroadcastReceiver   
  226.         receiver new UpdateReceiver();   
  227.         IntentFilter filter new IntentFilter();   
  228.         // 为 BroadcastReceiver 指定 action ,使之用于接收同 action 的广播   
  229.         filter.addAction("com.webabcd.service.msg");   
  230.            
  231.         // 以编程方式注册  BroadcastReceiver 。配置方式注册 BroadcastReceiver 的例子见 AndroidManifest.xml 文件   
  232.         // 一般在 OnStart 时注册,在 OnStop 时取消注册   
  233.         this.registerReceiver(receiver, filter);   
  234.         // this.unregisterReceiver(receiver);   
  235.            
  236.     }   
  237.   
  238.     @Override  
  239.     public void onClick(View v) {   
  240.         Intent intent new Intent(Main.thisMyService.class);   
  241.         switch (v.getId()) {   
  242.         case R.id.btnStart:   
  243.             this.startService(intent);   
  244.             break;   
  245.         case R.id.btnStop:   
  246.             this.stopService(intent);   
  247.             break;   
  248.         case R.id.btnBind:   
  249.             this.bindService(intent, conn, Context.BIND_AUTO_CREATE);   
  250.             break;   
  251.         case R.id.btnUnbind:   
  252.             this.unbindService(conn);   
  253.             break;   
  254.         }   
  255.     }   
  256.   
  257.     // bindService() 所需的 ServiceConnection 对象   
  258.     private ServiceConnection conn new ServiceConnection() {   
  259.         @Override  
  260.         public void onServiceConnected(ComponentName className, IBinder service) {   
  261.                
  262.         }   
  263.         @Override  
  264.         public void onServiceDisconnected(ComponentName className) {   
  265.                
  266.         }   
  267.     };   
  268.        
  269.     private String msg="";   
  270.     private UpdateReceiver receiver;   
  271.     // 实现一个 BroadcastReceiver,用于接收指定的 Broadcast   
  272.     public class UpdateReceiver extends BroadcastReceiver{   
  273.   
  274.         @Override  
  275.         public void onReceive(Context context, Intent intent) {   
  276.             msg intent.getStringExtra("msg");   
  277.                
  278.             txtMsg.append(msg "\n");   
  279.         }   
  280.            
  281.     }   
  282. }   
  283.   
  284. MyService.java   
  285.   
  286. 代码    
  287. package com.webabcd.service;   
  288.   
  289. import android.app.Service;   
  290. import android.content.Intent;   
  291. import android.os.IBinder;   
  292. import android.util.Log;   
  293.   
  294. // 演示 Service 的生命周期。具体信息运行程序后在 LogCat 中查看   
  295. public class MyService extends Service {   
  296.   
  297.     @Override  
  298.     public IBinder onBind(Intent intent) {   
  299.            
  300.         Log.d("MyDebug""onBind");   
  301.         sendMsg("onBind");   
  302.            
  303.         // TODO Auto-generated method stub   
  304.         return null;   
  305.     }   
  306.   
  307.     @Override  
  308.     public void onCreate() {   
  309.         // TODO Auto-generated method stub   
  310.         super.onCreate();   
  311.            
  312.         Log.d("MyDebug""onCreate");   
  313.         sendMsg("onCreate");   
  314.     }   
  315.   
  316.     @Override  
  317.     public void onDestroy() {   
  318.         // TODO Auto-generated method stub   
  319.         super.onDestroy();   
  320.            
  321.         Log.d("MyDebug""onDestroy");   
  322.         sendMsg("onDestroy");   
  323.     }   
  324.   
  325.     @Override  
  326.     public void onRebind(Intent intent) {   
  327.         // TODO Auto-generated method stub   
  328.         super.onRebind(intent);   
  329.            
  330.         Log.d("MyDebug""onRebind");   
  331.         sendMsg("onRebind");   
  332.     }   
  333.   
  334.     @Override  
  335.     public void onStart(Intent intent, int startId) {   
  336.         super.onStart(intent, startId);   
  337.            
  338.         Log.d("MyDebug""onStart");   
  339.         sendMsg("onStart");   
  340.     }   
  341.        
  342.     @Override  
  343.     public boolean onUnbind(Intent intent) {   
  344.            
  345.         Log.d("MyDebug""onUnbind");   
  346.         sendMsg("onUnbind");   
  347.            
  348.         // TODO Auto-generated method stub   
  349.         return super.onUnbind(intent);   
  350.     }   
  351.        
  352.     // 发送广播信息   
  353.     private void sendMsg(String msg){   
  354.         // 指定广播目标的 action (注:指定了此 action 的 receiver 会接收此广播)   
  355.         Intent intent new Intent("com.webabcd.service.msg");   
  356.         // 需要传递的参数   
  357.         intent.putExtra("msg"msg);   
  358.         // 发送广播   
  359.         this.sendBroadcast(intent);   
  360.     }   
  361. }   
  362.   
  363.   
  364. MyBootReceiver.java   
  365.   
  366. 代码    
  367. package com.webabcd.service;   
  368.   
  369. import android.content.BroadcastReceiver;   
  370. import android.content.Context;   
  371. import android.content.Intent;   
  372. import android.util.Log;   
  373.   
  374. public class MyBootReceiver extends BroadcastReceiver {   
  375.   
  376.     // 用于接收满足条件的 Broadcast(相应的 Broadcast 的注册信息详见 AndroidManifest.xml ,当系统启动完毕后会调用这个广播接收器)   
  377.     @Override  
  378.     public void onReceive(Context arg0, Intent arg1) {   
  379.         Log.d("MyDebug""onReceive");   
  380.            
  381.         // 启动服务   
  382.         Intent service new Intent(arg0, MyService.class);   
  383.         arg0.startService(service);   
  384.     }   
  385.   
  386. }   
  387.   
  388.   
  389. AndroidManifest.xml   
  390.   
  391. 代码    
  392. <?xml version="1.0" encoding="utf-8"?>   
  393. <manifest xmlns:android="http://schemas.android.com/apk/res/android"  
  394.     package="com.webabcd.service" android:versionCode="1"  
  395.     android:versionName="1.0">   
  396.     <application android:icon="@drawable/icon" android:label="@string/app_name">   
  397.         <activity android:name=".Main" android:label="@string/app_name">   
  398.             <intent-filter>   
  399.                 <action android:name="android.intent.action.MAIN" />   
  400.                 <category android:name="android.intent.category.LAUNCHER" />   
  401.             </intent-filter>   
  402.         </activity>   
  403.            
  404.         <!--   
  405.             如果有需要用到的 service ,则都要在这里做相应的配置   
  406.         -->   
  407.         <service android:name=".MyService"></service>   
  408.            
  409.         <!--   
  410.             注册一个 BroadcastReceiver   
  411.             其 intent-filter 为 android.intent.action.BOOT_COMPLETED(用于接收系统启动完毕的 Broadcast)   
  412.         -->   
  413.         <receiver android:name=".MyBootReceiver">   
  414.             <intent-filter>   
  415.                 <action android:name="android.intent.action.BOOT_COMPLETED" />   
  416.             </intent-filter>   
  417.         </receiver>   
  418.     </application>   
  419.        
  420.     <!--   
  421.         接受系统启动完毕的 Broadcast 的权限   
  422.     -->   
  423.     <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />   
  424.     <uses-sdk android:minSdkVersion="3" />   
  425. </manifest>    
  426.   

 



文章本月排行 文章本年排行
   



发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。