打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
系出名门Android(4) - 活动(Activity), 服务(Service), 广...

系出名门Android(4) - 活动(Activity), 服务(Service), 广播(Broadcast), 广播接收器(BroadcastReceiv

文章分类:移动开发
转自:http://www.cnblogs.com/webabcd/archive/2010/01/21/1652982.html

介绍
在 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.     /** Called when the activity is first created. */  
  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.this, MyActivity.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.     /** Called when the activity is first created. */  
  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.  * startService() 和 bindService() 的区别   
  208.  * startService() - 正常理解就好  
  209.  * bindService() - 使当前上下文对象(本例中就是 Activity)通过一个 ServiceConnection 对象邦定到指定的 Service 。这样,如果上下文对象销毁了的话,那么其对应的 Service 也会被销毁  
  210.  */  
  211. public class Main extends Activity implements OnClickListener {   
  212.   
  213.     private TextView txtMsg;   
  214.        
  215.     @Override  
  216.     public void onCreate(Bundle savedInstanceState) {   
  217.         super.onCreate(savedInstanceState);   
  218.         setContentView(R.layout.main);   
  219.   
  220.         setTitle("android 之 service");   
  221.   
  222.         this.findViewById(R.id.btnStart).setOnClickListener(this);   
  223.         this.findViewById(R.id.btnStop).setOnClickListener(this);   
  224.         this.findViewById(R.id.btnBind).setOnClickListener(this);   
  225.         this.findViewById(R.id.btnUnbind).setOnClickListener(this);   
  226.            
  227.         txtMsg = (TextView)this.findViewById(R.id.txtMsg);   
  228.            
  229.         // 实例化自定义的 BroadcastReceiver   
  230.         receiver = new UpdateReceiver();   
  231.         IntentFilter filter = new IntentFilter();   
  232.         // 为 BroadcastReceiver 指定 action ,使之用于接收同 action 的广播   
  233.         filter.addAction("com.webabcd.service.msg");   
  234.            
  235.         // 以编程方式注册  BroadcastReceiver 。配置方式注册 BroadcastReceiver 的例子见 AndroidManifest.xml 文件   
  236.         // 一般在 OnStart 时注册,在 OnStop 时取消注册   
  237.         this.registerReceiver(receiver, filter);   
  238.         // this.unregisterReceiver(receiver);   
  239.            
  240.     }   
  241.   
  242.     @Override  
  243.     public void onClick(View v) {   
  244.         Intent intent = new Intent(Main.this, MyService.class);   
  245.         switch (v.getId()) {   
  246.         case R.id.btnStart:   
  247.             this.startService(intent);   
  248.             break;   
  249.         case R.id.btnStop:   
  250.             this.stopService(intent);   
  251.             break;   
  252.         case R.id.btnBind:   
  253.             this.bindService(intent, conn, Context.BIND_AUTO_CREATE);   
  254.             break;   
  255.         case R.id.btnUnbind:   
  256.             this.unbindService(conn);   
  257.             break;   
  258.         }   
  259.     }   
  260.   
  261.     // bindService() 所需的 ServiceConnection 对象   
  262.     private ServiceConnection conn = new ServiceConnection() {   
  263.         @Override  
  264.         public void onServiceConnected(ComponentName className, IBinder service) {   
  265.                
  266.         }   
  267.         @Override  
  268.         public void onServiceDisconnected(ComponentName className) {   
  269.                
  270.         }   
  271.     };   
  272.        
  273.     private String msg="";   
  274.     private UpdateReceiver receiver;   
  275.     // 实现一个 BroadcastReceiver,用于接收指定的 Broadcast   
  276.     public class UpdateReceiver extends BroadcastReceiver{   
  277.   
  278.         @Override  
  279.         public void onReceive(Context context, Intent intent) {   
  280.             msg = intent.getStringExtra("msg");   
  281.                
  282.             txtMsg.append(msg + "\n");   
  283.         }   
  284.            
  285.     }   
  286. }   
  287.   
  288. MyService.java   
  289.   
  290. 代码    
  291. package com.webabcd.service;   
  292.   
  293. import android.app.Service;   
  294. import android.content.Intent;   
  295. import android.os.IBinder;   
  296. import android.util.Log;   
  297.   
  298. // 演示 Service 的生命周期。具体信息运行程序后在 LogCat 中查看   
  299. public class MyService extends Service {   
  300.   
  301.     @Override  
  302.     public IBinder onBind(Intent intent) {   
  303.            
  304.         Log.d("MyDebug""onBind");   
  305.         sendMsg("onBind");   
  306.            
  307.         // TODO Auto-generated method stub   
  308.         return null;   
  309.     }   
  310.   
  311.     @Override  
  312.     public void onCreate() {   
  313.         // TODO Auto-generated method stub   
  314.         super.onCreate();   
  315.            
  316.         Log.d("MyDebug""onCreate");   
  317.         sendMsg("onCreate");   
  318.     }   
  319.   
  320.     @Override  
  321.     public void onDestroy() {   
  322.         // TODO Auto-generated method stub   
  323.         super.onDestroy();   
  324.            
  325.         Log.d("MyDebug""onDestroy");   
  326.         sendMsg("onDestroy");   
  327.     }   
  328.   
  329.     @Override  
  330.     public void onRebind(Intent intent) {   
  331.         // TODO Auto-generated method stub   
  332.         super.onRebind(intent);   
  333.            
  334.         Log.d("MyDebug""onRebind");   
  335.         sendMsg("onRebind");   
  336.     }   
  337.   
  338.     @Override  
  339.     public void onStart(Intent intent, int startId) {   
  340.         super.onStart(intent, startId);   
  341.            
  342.         Log.d("MyDebug""onStart");   
  343.         sendMsg("onStart");   
  344.     }   
  345.        
  346.     @Override  
  347.     public boolean onUnbind(Intent intent) {   
  348.            
  349.         Log.d("MyDebug""onUnbind");   
  350.         sendMsg("onUnbind");   
  351.            
  352.         // TODO Auto-generated method stub   
  353.         return super.onUnbind(intent);   
  354.     }   
  355.        
  356.     // 发送广播信息   
  357.     private void sendMsg(String msg){   
  358.         // 指定广播目标的 action (注:指定了此 action 的 receiver 会接收此广播)   
  359.         Intent intent = new Intent("com.webabcd.service.msg");   
  360.         // 需要传递的参数   
  361.         intent.putExtra("msg", msg);   
  362.         // 发送广播   
  363.         this.sendBroadcast(intent);   
  364.     }   
  365. }   
  366.   
  367.   
  368. MyBootReceiver.java   
  369.   
  370. 代码    
  371. package com.webabcd.service;   
  372.   
  373. import android.content.BroadcastReceiver;   
  374. import android.content.Context;   
  375. import android.content.Intent;   
  376. import android.util.Log;   
  377.   
  378. public class MyBootReceiver extends BroadcastReceiver {   
  379.   
  380.     // 用于接收满足条件的 Broadcast(相应的 Broadcast 的注册信息详见 AndroidManifest.xml ,当系统启动完毕后会调用这个广播接收器)   
  381.     @Override  
  382.     public void onReceive(Context arg0, Intent arg1) {   
  383.         Log.d("MyDebug""onReceive");   
  384.            
  385.         // 启动服务   
  386.         Intent service = new Intent(arg0, MyService.class);   
  387.         arg0.startService(service);   
  388.     }   
  389.   
  390. }   
  391.   
  392.   
  393. AndroidManifest.xml   
  394.   
  395. 代码    
  396. <?xml version="1.0" encoding="utf-8"?>   
  397. <manifest xmlns:android="http://schemas.android.com/apk/res/android"  
  398.     package="com.webabcd.service" android:versionCode="1"  
  399.     android:versionName="1.0">   
  400.     <application android:icon="@drawable/icon" android:label="@string/app_name">   
  401.         <activity android:name=".Main" android:label="@string/app_name">   
  402.             <intent-filter>   
  403.                 <action android:name="android.intent.action.MAIN" />   
  404.                 <category android:name="android.intent.category.LAUNCHER" />   
  405.             </intent-filter>   
  406.         </activity>   
  407.            
  408.         <!--   
  409.             如果有需要用到的 service ,则都要在这里做相应的配置   
  410.         -->   
  411.         <service android:name=".MyService"></service>   
  412.            
  413.         <!--   
  414.             注册一个 BroadcastReceiver   
  415.             其 intent-filter 为 android.intent.action.BOOT_COMPLETED(用于接收系统启动完毕的 Broadcast)   
  416.         -->   
  417.         <receiver android:name=".MyBootReceiver">   
  418.             <intent-filter>   
  419.                 <action android:name="android.intent.action.BOOT_COMPLETED" />   
  420.             </intent-filter>   
  421.         </receiver>   
  422.     </application>   
  423.        
  424.     <!--   
  425.         接受系统启动完毕的 Broadcast 的权限   
  426.     -->   
  427.     <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />   
  428.     <uses-sdk android:minSdkVersion="3" />   
  429. </manifest>    
  430.   
  431.   
  432. OK  
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
activity、service、BroadcastReceive之间如何互相通讯,并取回相应的结果
总结篇之五:BroadcastReceiver应用详解
Android多媒体学习六:利用Service实现背景音乐的播放
android语音识别方法
Android Bundle详解
android service 学习(上)
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服