Service与Activity通信

本文介绍了一个使用广播接收器实现的Android应用内部组件间的通信案例。通过定义特定的动作标识符,Activity可以启动或停止Service,并接收Service发送的状态更新。此方案展示了如何利用LocalBroadcastManager在同一个应用的不同组件间高效地传递消息。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Activity与Service通过广播通信:

LocalServiceBroadcaster.java

import android.app.Activity;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.v4.app.ServiceCompat;
import android.support.v4.content.LocalBroadcastManager;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class LocalServiceBroadcaster extends Activity {
    static final String ACTION_STARTED = "com.example.android.supportv4.STARTED";
    static final String ACTION_UPDATE = "com.example.android.supportv4.UPDATE";
    static final String ACTION_STOPPED = "com.example.android.supportv4.STOPPED";

    LocalBroadcastManager mLocalBroadcastManager;
    BroadcastReceiver mReceiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.local_service_broadcaster);

        // This is where we print the data we get back.
        final TextView callbackData = (TextView)findViewById(R.id.callback);

        // Put in some initial text.
        callbackData.setText("No broadcast received yet");

        // We use this to send broadcasts within our local process.
        mLocalBroadcastManager = LocalBroadcastManager.getInstance(this);

        // We are going to watch for interesting local broadcasts.
        IntentFilter filter = new IntentFilter();
        filter.addAction(ACTION_STARTED);
        filter.addAction(ACTION_UPDATE);
        filter.addAction(ACTION_STOPPED);
        mReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                if (intent.getAction().equals(ACTION_STARTED)) {
                    callbackData.setText("STARTED");
                } else if (intent.getAction().equals(ACTION_UPDATE)) {
                    callbackData.setText("Got update: " + intent.getIntExtra("value", 0));
                } else if (intent.getAction().equals(ACTION_STOPPED)) {
                    callbackData.setText("STOPPED");
                }
            }
        };
        mLocalBroadcastManager.registerReceiver(mReceiver, filter);

        // Watch for button clicks.
        Button button = (Button)findViewById(R.id.start);
        button.setOnClickListener(mStartListener);
        button = (Button)findViewById(R.id.stop);
        button.setOnClickListener(mStopListener);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mLocalBroadcastManager.unregisterReceiver(mReceiver);
    }

    private OnClickListener mStartListener = new OnClickListener() {
        public void onClick(View v) {
            startService(new Intent(LocalServiceBroadcaster.this, LocalService.class));
        }
    };

    private OnClickListener mStopListener = new OnClickListener() {
        public void onClick(View v) {
            stopService(new Intent(LocalServiceBroadcaster.this, LocalService.class));
        }
    };

    public static class LocalService extends Service {
        LocalBroadcastManager mLocalBroadcastManager;
        int mCurUpdate;

        static final int MSG_UPDATE = 1;

        Handler mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case MSG_UPDATE: {
                        mCurUpdate++;
                        Intent intent = new Intent(ACTION_UPDATE);
                        intent.putExtra("value", mCurUpdate);
                        mLocalBroadcastManager.sendBroadcast(intent);
                        Message nmsg = mHandler.obtainMessage(MSG_UPDATE);
                        mHandler.sendMessageDelayed(nmsg, 1000);
                    } break;
                    default:
                        super.handleMessage(msg);
                }
            }
        };

        @Override
        public void onCreate() {
            super.onCreate();
            mLocalBroadcastManager = LocalBroadcastManager.getInstance(this);
        }

        public int onStartCommand(Intent intent, int flags, int startId) {
            // Tell any local interested parties about the start.
            mLocalBroadcastManager.sendBroadcast(new Intent(ACTION_STARTED));

            // Prepare to do update reports.
            mHandler.removeMessages(MSG_UPDATE);
            Message msg = mHandler.obtainMessage(MSG_UPDATE);
            mHandler.sendMessageDelayed(msg, 1000);
            return ServiceCompat.START_STICKY;
        }

        @Override
        public void onDestroy() {
            super.onDestroy();

            // Tell any local interested parties about the stop.
            mLocalBroadcastManager.sendBroadcast(new Intent(ACTION_STOPPED));

            // Stop doing updates.
            mHandler.removeMessages(MSG_UPDATE);
        }

        @Override
        public IBinder onBind(Intent intent) {
            return null;
        }
    }
}

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:padding="4dip"
    android:gravity="center_horizontal"
    android:layout_width="match_parent" android:layout_height="match_parent">

    <Button android:id="@+id/start"
        android:layout_width="wrap_content" android:layout_height="wrap_content"
        android:text="@string/start_service">
        <requestFocus />
    </Button>

    <Button android:id="@+id/stop"
        android:layout_width="wrap_content" android:layout_height="wrap_content"
        android:text="@string/stop_service">
    </Button>

    <TextView android:id="@+id/callback"
        android:layout_width="match_parent" android:layout_height="wrap_content"
        android:layout_weight="0"
        android:gravity="center_horizontal" android:paddingTop="4dip"/>

</LinearLayout>


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值