`

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

阅读更多

介绍
在 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> 


OK

 

分享到:
评论
1 楼 qingyue0530 2011-04-28  
谢谢!

相关推荐

    Android-Service与Activity传值

    - **使用BroadcastReceiver**:`Service`通过发送Broadcast,`Activity`注册BroadcastReceiver来接收数据。`Service`创建一个`LocalBroadcastManager`实例,发送广播;`Activity`在需要接收数据的地方注册Receiver...

    android service 通过broadcast通知activity

    本主题将深入探讨如何使用Service以及BroadcastReceiver来实现特定的功能:当Service检测到某个函数的状态变化时,通过Broadcast发送通知,进而启动一个新的Activity。 首先,让我们了解`Service`。在Android中,...

    Android_Activity、Service、Broadcast、Notification

    Android Activity、Service、Broadcast、Notification四合一例子,Activity中点击按钮启动服务,服务里每4秒发送一次广播,广播接受者每接受到一个发送一条通知。

    Android Broadcast 广播机制 实例

    当一个Broadcast被发送时,所有注册了与该Broadcast匹配的BroadcastReceiver(广播接收器)都会收到这个消息,并可以执行相应的处理操作。这种机制使得不同应用程序之间可以相互协作,例如,当手机接收到短信时,...

    Service和Activity通过Broadcast共享数据

    在Android应用开发中,Service和Activity是两个非常重要的组件。Service用于在后台执行长时间运行的任务,而Activity则负责用户界面交互。在某些场景下,Service和Activity之间需要进行数据共享,例如更新UI、传递...

    android 服务和广播机制(service和broadcast)

    在Android系统中,服务(Service)和广播接收者(BroadcastReceiver)是两个核心组件,它们在后台执行任务和实现跨应用程序通信。本教程将深入探讨如何利用这两种组件来实现手机背景的定时切换功能,比如根据用户...

    android多个activity和一个service通信

    1. **BroadcastReceiver**: 创建一个BroadcastReceiver作为中介,Service通过发送BroadcastIntent更新数据,各个Activity注册这个Receiver接收并处理这些广播。这种方式简单但可能导致性能问题,因为广播会触发所有...

    基于Android的广播接收器的设计与应用.pdf

    基于Android的广播接收器的设计与应用 本文主要介绍了基于Android的广播接收器的设计与应用。 Android系统通过广播接收器可以实时监听系统中的广播信息,当用户使用手机时,如遇到电话或者短信,系统会将电话或短信...

    Android创建Service后台常驻服务并使用Broadcast通信

    1. 发送广播:在Service中,可以通过`sendBroadcast()`方法发送广播,让其他组件(如Activity)接收。 ```java Intent intent = new Intent("com.example.MY_BROADCAST_ACTION"); sendBroadcast(intent); ``` 2. ...

    android--broadcast实例

    BroadcastReceiver(广播接收器)是接收广播的关键类,让我们深入探讨一下Broadcast实例在Android开发中的应用及其相关知识点。 首先,BroadcastReceiver的工作原理是基于Intent的发布和订阅模式。当一个广播意图被...

    系出名门Android系列文章整合

    Android应用由四大组件构成:活动(Activity)、服务(Service)、广播接收者(Broadcast Receiver)和内容提供者(Content Provider)。Activity是用户界面的基石,Service在后台执行任务,Broadcast Receiver响应...

    Android-广播的发送与接收demo

    1. **创建广播接收器(BroadcastReceiver)**: 在Android项目中,我们需要创建一个新的BroadcastReceiver子类。例如,我们可以命名为`MyBroadcastReceiver`,并在其中重写`onReceive()`方法,这是处理广播事件的...

    四大组件 Activity Service content provider broadcast receiver

    ### 四大组件详解:Activity、Service、Content Provider与Broadcast Receiver #### 一、Activity **定义:** Activity是Android应用程序中的四大基本组件之一,它代表一个屏幕界面,用户可以直接与其进行交互。每...

    Android应用程序注册广播接收器(registerReceiver)的过程分析

    RegisterReceiver:在 registerReceiver 函数中,我们将广播接收器实例和 IntentFilter 实例传递给 ActivityManagerService,以便注册广播接收器。 六、结论 在本文中,我们探讨了 Android 应用程序注册广播接收...

    android service 通过broadcast通知activity.zip

    当Service需要与Activity进行通信时,可以使用BroadcastReceiver(广播接收器)这一机制。本资料“android service 通过broadcast通知activity.zip”显然是关于如何在Service和Activity之间通过Broadcast进行通信的...

    Android 利用广播调用服务(Service)中的方法

    在Android应用开发中,服务(Service)是一种用于执行长时间运行操作的组件,它不提供用户界面,但可以在后台持续运行。然而,直接从一个Activity中调用Service中的方法是不被允许的,因为这可能会导致应用程序出现...

    安卓-Activity-广播接收者的使用

    广播接收者(Broadcast Receiver)则是Android系统中实现事件监听的一种机制,它能够接收并处理系统或应用发送的广播消息。下面我们将详细探讨Activity和广播接收者的使用。 首先,我们来看Activity的创建方式。...

    Android Service与Activity交互

    本示例"Android Service与Activity交互"旨在演示如何在Service启动后,通过线程进行异步操作,并在完成特定任务后,通过发送广播(Broadcast)通知Activity来更新用户界面。 首先,我们需要创建一个Service,通常在...

    Android程序源码--广播

    在“Android程序源码--广播”中,你可以找到关于如何创建和注册广播接收器、发送广播Intent以及在onReceive()方法中处理广播事件的示例代码。通过对这些源码的学习,你能更好地理解广播在实际项目中的运用,例如如何...

Global site tag (gtag.js) - Google Analytics