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

简介:
[索引页]
[源码下载]


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


作者: webabcd


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


1、演示 Activity 的基本用法,一个 Activity 启动另一个 Activity,启动另一个 Activity 时为其传递参数,被启动的 Activity 返回参数给启动者的 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; 
         
         /** Called when the activity is first created. */ 
        @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,指定需要启动的 Activity 
                                Intent intent =  new Intent(); 
                                intent.setClass(Main. this, MyActivity. class); 

                                 // 实例化 Bundle,设置需要传递的参数 
                                Bundle bundle =  new Bundle(); 
                                bundle.putString( "name""webabcd"); 
                                bundle.putDouble( "salary", 100.13); 

                                 // 将需要传递的参数赋值给 Intent 对象 
                                intent.putExtras(bundle); 

                                 // startActivity(intent); // 启动指定的 Intent(不等待返回结果) 
                                 // Main.this.finish(); 
                                 
                                 // 启动指定的 Intent,并等待返回结果 
                                 // 其中第二个参数如果大于等于零,则返回结果时会回调 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() { 
                 // TODO Auto-generated method stub 
                 super.onStart(); 
                 
                Log.d( "MyDebug""onStart"); 
        } 

        @Override 
         protected  void onStop() { 
                 // TODO Auto-generated method stub 
                 super.onStop(); 
                 
                Log.d( "MyDebug""onStop"); 
        } 

        @Override 
         protected  void onRestart() { 
                 // TODO Auto-generated method stub 
                 super.onRestart(); 
                 
                Log.d( "MyDebug""onRestart"); 
        } 
         
        @Override 
         protected  void onPause() { 
                 // TODO Auto-generated method stub 
                 super.onPause(); 
                 
                Log.d( "MyDebug""onPause"); 
        } 

        @Override 
         protected  void onResume() { 
                 // TODO Auto-generated method stub 
                 super.onResume(); 
                 
                Log.d( "MyDebug""onResume"); 
        } 
         
        @Override 
         protected  void onDestroy() { 
                 // TODO Auto-generated method stub 
                 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; 

// 被另一个 Activity 所启动的 Activity 
public  class MyActivity  extends Activity { 
         
        Intent intent; 
         
         /** Called when the activity is first created. */ 
        @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 ,则都要在这里做相应的配置 
                
--> 
                 < 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() 的区别    
* startService() - 正常理解就好 
* bindService() - 使当前上下文对象(本例中就是 Activity)通过一个 ServiceConnection 对象邦定到指定的 Service 。这样,如果上下文对象销毁了的话,那么其对应的 Service 也会被销毁 
*/
 
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); 
                 
                 // 实例化自定义的 BroadcastReceiver 
                receiver =  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); 
                 
        } 

        @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) { 
                         
                } 
        }; 
         
         private String msg=""; 
         private UpdateReceiver receiver; 
         // 实现一个 BroadcastReceiver,用于接收指定的 Broadcast 
         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; 

// 演示 Service 的生命周期。具体信息运行程序后在 LogCat 中查看 
public  class MyService  extends Service { 

        @Override 
         public IBinder onBind(Intent intent) { 
                 
                Log.d( "MyDebug""onBind"); 
                sendMsg( "onBind"); 
                 
                 // TODO Auto-generated method stub 
                 return  null
        } 

        @Override 
         public  void onCreate() { 
                 // TODO Auto-generated method stub 
                 super.onCreate(); 
                 
                Log.d( "MyDebug""onCreate"); 
                sendMsg( "onCreate"); 
        } 

        @Override 
         public  void onDestroy() { 
                 // TODO Auto-generated method stub 
                 super.onDestroy(); 
                 
                Log.d( "MyDebug""onDestroy"); 
                sendMsg( "onDestroy"); 
        } 

        @Override 
         public  void onRebind(Intent intent) { 
                 // TODO Auto-generated method stub 
                 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"); 
                 
                 // TODO Auto-generated method stub 
                 return  super.onUnbind(intent); 
        } 
         
         // 发送广播信息 
         private  void sendMsg(String msg){ 
                 // 指定广播目标的 action (注:指定了此 action 的 receiver 会接收此广播) 
                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 { 

         // 用于接收满足条件的 Broadcast(相应的 Broadcast 的注册信息详见 AndroidManifest.xml ,当系统启动完毕后会调用这个广播接收器) 
        @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 ,则都要在这里做相应的配置 
                
--> 
                 < service  android:name =".MyService" > </ service > 
                 
                <!--  
                        注册一个 BroadcastReceiver 
                        其 intent-filter 为 android.intent.action.BOOT_COMPLETED(用于接收系统启动完毕的 Broadcast) 
                
--> 
                 < receiver  android:name =".MyBootReceiver" > 
                         < intent-filter > 
                                 < action  android:name ="android.intent.action.BOOT_COMPLETED"  /> 
                         </ intent-filter > 
                 </ receiver > 
         </ application > 
         
        <!--  
                接受系统启动完毕的 Broadcast 的权限 
        
--> 
         < uses-permission  android:name ="android.permission.RECEIVE_BOOT_COMPLETED"  /> 
         < uses-sdk  android:minSdkVersion ="3"  /> 
</ manifest >
 
 



          本文转自webabcd 51CTO博客,原文链接:http://blog.51cto.com/webabcd/342046 ,如需转载请自行联系原作者
相关文章
|
安全 Java 网络安全
Android远程连接和登录FTPS服务代码(commons.net库)
Android远程连接和登录FTPS服务代码(commons.net库)
351 1
|
JavaScript 前端开发 Android开发
让Vite+Vue3项目在Android端离线打开(不需要起服务)
让Vite+Vue3项目在Android端离线打开(不需要起服务)
767 10
|
安全 API 开发工具
Android平台RTMP推送|轻量级RTSP服务如何实现麦克风|扬声器声音采集切换
Android平台扬声器播放声音的采集,在无纸化同屏等场景下,意义很大,早期低版本的Android设备,是没法直接采集扬声器audio的(从Android 10开始支持),所以,如果需要采集扬声器audio,需要先做系统版本判断,添加相应的权限。
418 0
|
编解码 开发工具 Android开发
Android平台实现屏幕录制(屏幕投影)|音频播放采集|麦克风采集并推送RTMP或轻量级RTSP服务
Android平台屏幕采集、音频播放声音采集、麦克风采集编码打包推送到RTMP和轻量级RTSP服务的相关技术实现,做成高稳定低延迟的同屏系统,还需要有配套好的RTMP、RTSP直播播放器
395 1
|
调度 Android开发 UED
Android经典实战之Android 14前台服务适配
本文介绍了在Android 14中适配前台服务的关键步骤与最佳实践,包括指定服务类型、请求权限、优化用户体验及使用WorkManager等。通过遵循这些指南,确保应用在新系统上顺畅运行并提升用户体验。
1030 6
|
数据处理 开发工具 数据安全/隐私保护
Android平台RTMP推送|轻量级RTSP服务|GB28181接入之文字、png图片水印的精进之路
本文探讨了Android平台上推流模块中添加文字与PNG水印的技术演进。自2015年起,为了满足应急指挥及安防领域的需求,逐步发展出三代水印技术:第一代为静态文字与图像水印;第二代实现了动态更新水印内容的能力,例如实时位置与时间信息;至第三代,则优化了数据传输效率,直接使用Bitmap对象传递水印数据至JNI层,减少了内存拷贝次数。这些迭代不仅提升了用户体验和技术效率,也体现了开发者追求极致与不断创新的精神。
218 7
|
数据采集 编解码 开发工具
Android平台实现无纸化同屏并推送RTMP或轻量级RTSP服务(毫秒级延迟)
一个好的无纸化同屏系统,需要考虑的有整体组网、分辨率、码率、实时延迟、音视频同步和连续性等各个指标,做容易,做好难
224 2
|
监控 开发工具 Android开发
Android平台实现RTSP拉流转发至轻量级RTSP服务
为满足Android平台上从外部RTSP摄像头拉流并提供轻量级RTSP服务的需求,利用大牛直播SDK实现了相关功能。SDK支持开始与停止拉流、音频视频数据回调处理及RTSP服务的启动与发布等操作。拉流仅需将未解码数据回调,对性能影响小。音频和视频数据经由特定接口传递给发布端进行处理。此外,SDK还提供了获取RTSP会话数量的功能。此方案适用于监控和巡检等低延迟应用场景,并支持二次水印添加等功能。
408 1
|
编解码 API 开发工具
Android平台轻量级RTSP服务模块二次封装版调用说明
本文介绍了Android平台上轻量级RTSP服务模块的二次封装实践,旨在简化开发流程,让开发者能更专注于业务逻辑。通过`LibPublisherWrapper`类提供的API,可在应用中轻松初始化RTSP服务、配置视频参数(如分辨率、编码类型)、启动与停止RTSP服务及流发布,并获取RTSP会话数量。此外,还展示了如何处理音频和视频数据的采集与推送。最后,文章提供了从启动服务到销毁资源的完整示例,帮助开发者快速集成实时流媒体功能。
171 0
|
编解码 开发工具 Android开发
Android平台轻量级RTSP服务模块技术接入说明
为满足内网无纸化/电子教室等内网超低延迟需求,避免让用户配置单独的服务器,大牛直播SDK在推送端发布了轻量级RTSP服务SDK。 轻量级RTSP服务解决的核心痛点是避免用户或者开发者单独部署RTSP或者RTMP服务,实现本地的音视频数据(如摄像头、麦克风),编码后,汇聚到内置RTSP服务,对外提供可供拉流的RTSP URL,轻量级RTSP服务,适用于内网环境下,对并发要求不高的场景,支持H.264/H.265,支持RTSP鉴权、单播、组播模式,考虑到单个服务承载能力,我们支持同时创建多个RTSP服务,并支持获取当前RTSP服务会话连接数。
297 0

热门文章

最新文章