Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發 >> 初階開發

Android 四大元件入門:Activity、Service 與廣播機制

編輯:初階開發

Android 的核心由幾個角色組成,彼此透過 Intent 溝通:

  • Activity——負責呈現功能畫面;
  • Service——等同於在背景運行的 Activity,沒有使用者介面;
  • Broadcast——用於發送廣播訊息;
  • BroadcastReceiver——用於接收廣播;
  • Intent——串起以上元件,並在它們之間傳遞訊息。

一、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;

    @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) {
                // 指定要啟動的 Activity
                Intent intent = new Intent();
                intent.setClass(Main.this, MyActivity.class);

                // 準備要傳遞的參數
                Bundle bundle = new Bundle();
                bundle.putString("name", "webabcd");
                bundle.putDouble("salary", 100.13);
                intent.putExtras(bundle);

                // 啟動並等待回傳結果;第二個參數 >= 0 時會回呼 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()   { super.onStart();   Log.d("MyDebug", "onStart"); }
    @Override protected void onStop()    { super.onStop();    Log.d("MyDebug", "onStop"); }
    @Override protected void onRestart() { super.onRestart(); Log.d("MyDebug", "onRestart"); }
    @Override protected void onPause()   { super.onPause();   Log.d("MyDebug", "onPause"); }
    @Override protected void onResume()  { super.onResume();  Log.d("MyDebug", "onResume"); }
    @Override protected void onDestroy() { 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;

    @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

凡是用到的 Activity 都必須在此註冊:

<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 android:name=".MyActivity" android:label="Activity 2" />
</application>

重點在於:啟動方用 startActivityForResult() 搭配 Bundle 傳參,被啟動方用 setResult() 把結果塞回 Intent,啟動方的 onActivityResult() 便會收到。若用 startActivity() 則不會等待回傳。

二、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;

public class Main extends Activity implements OnClickListener {

    private TextView txtMsg;
    private String msg = "";
    private UpdateReceiver receiver;

    @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
        // 通常在 onStart 註冊、onStop 取消註冊
        receiver = new UpdateReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction("com.webabcd.service.msg");
        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) { }
    };

    // 接收指定廣播的 receiver
    public class UpdateReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            msg = intent.getStringExtra("msg");
            txtMsg.append(msg + "\n");
        }
    }
}

MyService.java

這個 Service 的主要目的是觀察生命週期,各回呼執行時會印出 Log 並發送廣播:

package com.webabcd.service;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

public class MyService extends Service {

    @Override public void onCreate() {
        super.onCreate();
        Log.d("MyDebug", "onCreate");
        sendMsg("onCreate");
    }

    @Override public void onStart(Intent intent, int startId) {
        super.onStart(intent, startId);
        Log.d("MyDebug", "onStart");
        sendMsg("onStart");
    }

    @Override public IBinder onBind(Intent intent) {
        Log.d("MyDebug", "onBind");
        sendMsg("onBind");
        return null;
    }

    @Override public boolean onUnbind(Intent intent) {
        Log.d("MyDebug", "onUnbind");
        sendMsg("onUnbind");
        return super.onUnbind(intent);
    }

    @Override public void onRebind(Intent intent) {
        super.onRebind(intent);
        Log.d("MyDebug", "onRebind");
        sendMsg("onRebind");
    }

    @Override public void onDestroy() {
        super.onDestroy();
        Log.d("MyDebug", "onDestroy");
        sendMsg("onDestroy");
    }

    // 發送廣播,action 決定哪些 receiver 會收到
    private void sendMsg(String msg) {
        Intent intent = new Intent("com.webabcd.service.msg");
        intent.putExtra("msg", msg);
        this.sendBroadcast(intent);
    }
}

MyBootReceiver.java

開機完成後自動啟動 Service,是實際專案中很常見的需求:

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 {
    @Override
    public void onReceive(Context arg0, Intent arg1) {
        Log.d("MyDebug", "onReceive");
        Intent service = new Intent(arg0, MyService.class);
        arg0.startService(service);
    }
}

AndroidManifest.xml

<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 android:name=".MyService" />

    <!-- 註冊開機廣播接收器 -->
    <receiver android:name=".MyBootReceiver">
        <intent-filter>
            <action android:name="android.intent.action.BOOT_COMPLETED" />
        </intent-filter>
    </receiver>
</application>

<!-- 接收開機完成廣播所需的權限 -->
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

重點整理

  • Service 有兩種啟動方式:startService() 是「丟出去就不管」,bindService() 則建立持續連結,可透過 IBinder 直接溝通。
  • BroadcastReceiver 有兩種註冊方式:在程式碼中用 registerReceiver()(生命週期隨 Activity,記得解除註冊),或在 manifest 中靜態宣告(即使 App 未啟動也能收到)。
  • 自訂廣播靠 action 字串配對,命名建議加上自己的套件名前綴,避免與系統或其他 App 衝突。

(本文原發表於編程入門網:https://www.bianceng.cn/OS/extra/201004/16654_4.htm )

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved