`
coach
  • 浏览: 381817 次
  • 性别: Icon_minigender_2
  • 来自: 印度
社区版块
存档分类
最新评论

在 Android 中使用 Activity, Service, Broadcast, BroadcastReceiver

阅读更多
介绍
在 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
分享到:
评论

相关推荐

    Android代码-通过更简洁的方式启动 Activity、Service、Broadcast 等

    Now you can launch an explicit Activity like this: SmartGo.from(this) .to(ExplicitActivity.class) .shareElements() .like(v) .withSystemUI() .go(); or an implicit Activity like: SmartGo.from(this)...

    android GPS+Service例子

    一个结合了用service获得GPS信息,并用service将gps写入sqlite的gps表里,并用service通过broadcast发送经纬度信息给activity接收,activity通过BroadcastReceiver接收到service发送过来的经纬度信息后,在activity...

    疯狂Android讲义源代码2

    第10章 Service与Broadcast Receiver 第11章 多媒体应用开发 第12章 OpenGL与3D应用开发 第13章 Android的网络应用 第14章 管理Android手机桌面 第15章 传感器应用开发 第16章 GPS应用开发 第17章 使用Google Map...

    Android_Activity&Intent;

    服务(Service) - 相当于后台运行的 Activity 广播(Broadcast) - 用于发送广播 广播接收器(BroadcastReceiver) - 用于接收 ContentProvider-用于应用间共享数据 Intent - 用于连接以上各个组件,并在其间传递消息

    实验四-Android基本组件交互实验.doc

    实验四 Android基本组件交互实验 【实验目的】 本实验是Android基本组件实验,主要针对Activity、Service和Receiver实现和使用方 法。通过实验使学生掌握Activity的跳转、Service的启动停止以及Receiver的接受等。 ...

    疯狂Android讲义源码

     12.3.1 在Android应用中使用  OpenGL ES 454  12.3.2 绘制平面上的多边形 457  12.3.3 旋转 463  12.4 绘制3D图形 465  12.4.1 构建3D图形 465  12.4.2 应用纹理贴图 469  12.5 本章小结 475  第13章 ...

    android开发入门与实战(下)

    4.2 体验“选货”的乐趣——在G1上体验Market的使用 4.3 Android开发活动及特色应用 4.3.1 开发应用的领域 4.3.2 AndroidMarket特色应用一览 4.4 你也可以做东家——申请Market账号 4.4.1 卖东西要先入伙——准备...

    android开发入门教程

    9.2.1 实现Android中的广播事件 9.2.2 BroadCastReceiver介绍 9.3 应用实例详解 9.3.1 程序操作演示 9.3.2 实例编程实现 9.4 本章小结 第10章 一切为用户服务——Service应用实例 10.1 认识Service 10.2 使用...

    android开发入门与实战(上)

    4.2 体验“选货”的乐趣——在G1上体验Market的使用 4.3 Android开发活动及特色应用 4.3.1 开发应用的领域 4.3.2 AndroidMarket特色应用一览 4.4 你也可以做东家——申请Market账号 4.4.1 卖东西要先入伙——准备...

    疯狂Android讲义.part2

    12.3.1 在Android应用中使用 OpenGL ES 454 12.3.2 绘制平面上的多边形 457 12.3.3 旋转 463 12.4 绘制3D图形 465 12.4.1 构建3D图形 465 12.4.2 应用纹理贴图 469 12.5 本章小结 475 第13章 Android的网络应用 476 ...

    疯狂Android讲义.part1

    12.3.1 在Android应用中使用 OpenGL ES 454 12.3.2 绘制平面上的多边形 457 12.3.3 旋转 463 12.4 绘制3D图形 465 12.4.1 构建3D图形 465 12.4.2 应用纹理贴图 469 12.5 本章小结 475 第13章 Android的网络应用 476 ...

    安卓应用实现之音乐播放器

    界面的上半部显示正在播放的歌曲信息。...和Mediaplayer在musics receive里面发送广播,将会在Activity组件中的broadcast receive接收到, main Activity中的broadcast receiver将会监听从service传回来的广播。

    Google.Android开发入门与实战

     由于Android平台被推出的时间才一年左右,了解Android平台软件开发技术的程序员还不多,如何迅速地推广和普及Android平台软件开发技术,让越来越多的人参与到Android应用的开发中,是整个产业链都在关注的一个话题...

    《深入理解Android》卷Ⅱ

    6.4 Broadcast和BroadcastReceiver分析 6.4.1 registerReceiver流程分析 6.4.2 sendBroadcast流程分析 6.4.3 BROADCAST_INTENT_MSG消息处理函数 6.4.4 应用进程处理广播分析 6.4.5 广播处理总结 6.5 start...

    andriod精华学习教程

    Android中,Activity是所有程序的根本,所有程序的流程都运行在Activity之 中,Activity具有自己的生命周期(由系统控制生命周期,程序无法改变,但可 以用onSaveInstanceState保存其状态)。 对于Activity,关键是其...

    ap6212a0_bb16v3_sina33验证通过BT的功能_wifi部分有问题_20170626_1148没有外层目录.7z

    # frameworks/native/data/etc/android.hardware.touchscreen.multitouch.jazzhand.xml:system/etc/permissions/android.hardware.touchscreen.multitouch.jazzhand.xml \ # frameworks/native/data/etc/android....

    hm1375_parrotv1.1验证通过_20170824_1528.7z

    key_value紧跟着key后面的等号后面, 位于同一行中; ; key_value限制大小为256字节以内; ; ;------------------------------------------------------------------------------- ;---------------------------...

    ap6212a0_a33_sc3817r_神舟验证版本_借用nvram_ap6210这个配置文件_20170626_1834没有外层目录.7z

    # frameworks/native/data/etc/android.hardware.touchscreen.multitouch.jazzhand.xml:system/etc/permissions/android.hardware.touchscreen.multitouch.jazzhand.xml \ # frameworks/native/data/etc/android....

    ap6212a0_a33_sc3817r_服务器验证通过_bt已经通了_wifi需要修改配置_需要再次验证_20170626_1549.7z

    # frameworks/native/data/etc/android.hardware.touchscreen.multitouch.jazzhand.xml:system/etc/permissions/android.hardware.touchscreen.multitouch.jazzhand.xml \ # frameworks/native/data/etc/android....

Global site tag (gtag.js) - Google Analytics