[Android实例] 在 Android 中Service, Broadcast, BroadcastReceiver 的演示(转)

from : http://www.eoeandroid.com/forum.php?mod=viewthread&tid=152136

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> 

main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical" android:layout_width="fill_parent"
        android:layout_height="fill_parent">
        
        <Button android:text="startService" android:id="@+id/btnStart"
                android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
        <Button android:text="stopService" android:id="@+id/btnStop"
                android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
        <Button android:text="bindService" android:id="@+id/btnBind"
                android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
        <Button android:text="unbindService" android:id="@+id/btnUnbind"
                android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
        <TextView android:id="@+id/txtMsg" android:layout_width="fill_parent"
                android:layout_height="wrap_content" />
                
</LinearLayout>


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值