[Android執行個體] 在 Android 中Service, Broadcast, BroadcastReceiver 的示範)

來源:互聯網
上載者:User

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>

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.