[索引页]
[源码下载]


系出名门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{

TextViewtxt;

/** Calledwhentheactivityisfirstcreated. */
@Override
public void onCreate(BundlesavedInstanceState){
super .onCreate(savedInstanceState);
this .setContentView(R.layout.main);

txt
= (TextView) this .findViewById(R.id.txt);
txt.setText(
" Activity1 " );

Buttonbtn
= (Button) this .findViewById(R.id.btn);
btn.setText(
" 启动另一个Activity " );
btn.setOnClickListener(
new Button.OnClickListener(){
@Override
public void onClick(Viewv){

// 实例化Intent,指定需要启动的Activity
Intentintent = new Intent();
intent.setClass(Main.
this ,MyActivity. class );

// 实例化Bundle,设置需要传递的参数
Bundlebundle = 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,Intentdata){
if (resultCode == Activity.RESULT_OK){
Bundlebundle
= data.getExtras();

Stringname
= bundle.getString( " name " );
double salary = bundle.getDouble( " salary " );

txt.setText(
" Activity1 " + " \n名字: " + name + " \n薪水: " + String.valueOf(salary));
}
}

@Override
protected void onStart(){
// TODOAuto-generatedmethodstub
super .onStart();

Log.d(
" MyDebug " , " onStart " );
}

@Override
protected void onStop(){
// TODOAuto-generatedmethodstub
super .onStop();

Log.d(
" MyDebug " , " onStop " );
}

@Override
protected void onRestart(){
// TODOAuto-generatedmethodstub
super .onRestart();

Log.d(
" MyDebug " , " onRestart " );
}

@Override
protected void onPause(){
// TODOAuto-generatedmethodstub
super .onPause();

Log.d(
" MyDebug " , " onPause " );
}

@Override
protected void onResume(){
// TODOAuto-generatedmethodstub
super .onResume();

Log.d(
" MyDebug " , " onResume " );
}

@Override
protected void onDestroy(){
// TODOAuto-generatedmethodstub
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{

Intentintent;

/** Calledwhentheactivityisfirstcreated. */
@Override
public void onCreate(BundlesavedInstanceState){
super .onCreate(savedInstanceState);
this .setContentView(R.layout.main2);

// 获取启动者传递过来的参数
intent = this .getIntent();
Bundlebundle
= intent.getExtras();
Stringname
= bundle.getString( " name " );
double salary = bundle.getDouble( " salary " );

TextViewtxt
= (TextView) this .findViewById(R.id.txt);
txt.setText(
" Activity2 " + " \n名字: " + name + " \n薪水: " + String.valueOf(salary));

Buttonbtn
= (Button) this .findViewById(R.id.btn);
btn.setText(
" 返回前一个Activity " );
btn.setOnClickListener(
new Button.OnClickListener(){
public void onClick(Viewv){
// 返回参数给启动者
MyActivity. this .setResult(Activity.RESULT_OK,intent);
MyActivity.
this .finish();
}
});
}
}

AndroidManifest.xml
代码 <? xmlversion="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 ="Activity2" />
</ 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 TextViewtxtMsg;

@Override
public void onCreate(BundlesavedInstanceState){
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();
IntentFilterfilter
= 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(Viewv){
Intentintent
= 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 ServiceConnectionconn = new ServiceConnection(){
@Override
public void onServiceConnected(ComponentNameclassName,IBinderservice){

}
@Override
public void onServiceDisconnected(ComponentNameclassName){

}
};

private Stringmsg = "" ;
private UpdateReceiverreceiver;
// 实现一个BroadcastReceiver,用于接收指定的Broadcast
public class UpdateReceiver extends BroadcastReceiver{

@Override
public void onReceive(Contextcontext,Intentintent){
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 IBinderonBind(Intentintent){

Log.d(
" MyDebug " , " onBind " );
sendMsg(
" onBind " );

// TODOAuto-generatedmethodstub
return null ;
}

@Override
public void onCreate(){
// TODOAuto-generatedmethodstub
super .onCreate();

Log.d(
" MyDebug " , " onCreate " );
sendMsg(
" onCreate " );
}

@Override
public void onDestroy(){
// TODOAuto-generatedmethodstub
super .onDestroy();

Log.d(
" MyDebug " , " onDestroy " );
sendMsg(
" onDestroy " );
}

@Override
public void onRebind(Intentintent){
// TODOAuto-generatedmethodstub
super .onRebind(intent);

Log.d(
" MyDebug " , " onRebind " );
sendMsg(
" onRebind " );
}

@Override
public void onStart(Intentintent, int startId){
super .onStart(intent,startId);

Log.d(
" MyDebug " , " onStart " );
sendMsg(
" onStart " );
}

@Override
public boolean onUnbind(Intentintent){

Log.d(
" MyDebug " , " onUnbind " );
sendMsg(
" onUnbind " );

// TODOAuto-generatedmethodstub
return super .onUnbind(intent);
}

// 发送广播信息
private void sendMsg(Stringmsg){
// 指定广播目标的action(注:指定了此action的receiver会接收此广播)
Intentintent = 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(Contextarg0,Intentarg1){
Log.d(
" MyDebug " , " onReceive " );

// 启动服务
Intentservice = new Intent(arg0,MyService. class );
arg0.startService(service);
}

}

AndroidManifest.xml
代码 <? xmlversion="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 >



OK
[源码下载]

更多相关文章

  1. Android系统进程Zygote启动过程的源代码分析(2)
  2. Android之Intent的基本使用
  3. Android(安卓)Launcher启动流程
  4. android中的四种启动模式launchMode
  5. Android中Activity启动模式详解
  6. Android果然强大,连截字这种操作都集成了
  7. Android命令行启动程序-am命令的使用-纠正网上大部分资料的错误
  8. Android面试题整理--1
  9. Android(安卓)启动过程详解

随机推荐

  1. [Android軟體] SanDisk Memory Zone 智慧
  2. Android自义定捕获异常
  3. android 记事本demo!!!(listview与SQLite综合
  4. android高仿微信视频编辑页
  5. android 震动效果类
  6. Android(安卓)MediaCodec API实现的音视
  7. Android字符串及字符串资源的格式化
  8. android和javaEE更完美的通信-传递对象
  9. 开发者大杀器 —— Battery Historian,刨
  10. 2019年Android开发者常见面试题(一)