Android的Activity和Service互相通信的实现

 

 

先写MainActivity的代码

package com.example.server;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity {

    private Button bind;
    private Button send;
    private Button send2;

    private Messenger messenger;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        bind = (Button) findViewById(R.id.bindButton);
        send = (Button) findViewById(R.id.sendButton);
        send2 = (Button) findViewById(R.id.sendButton2);



        bind.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, MessengerService.class);
                bindService(intent, new ServiceConnection() {
                    @Override
                    public void onServiceConnected(ComponentName name, IBinder binder) {
                        //绑定且获得信差
                        messenger = new Messenger(binder);
                    }

                    @Override
                    public void onServiceDisconnected(ComponentName arg0) {
                    }
                }, Context.BIND_AUTO_CREATE);
            }
        });

        send.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Message msg = new Message();
                msg.what = 1;
                try {
                    messenger.send(msg);
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
            }
        });
        send2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Message msg = new Message();
                msg.what = 2;
                //把信差对象放入消息
                msg.obj = mMessenger;
                try {
                    //和服务连接的信差发送消息.
                    messenger.send(msg);
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /*--------------处理服务发送过来的消息--------------*/
    //创建信差,传入handler对象.
    Messenger mMessenger = new Messenger(new ServiceComingHander());

    private class ServiceComingHander extends Handler {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 3)
                Toast.makeText(MainActivity.this, "收到来自服务的消息", Toast.LENGTH_SHORT).show();
            super.handleMessage(msg);
        }
    }
}

然后在写Service的代码:

package com.example.server;

import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.os.SystemClock;
import android.support.annotation.Nullable;
import android.widget.Toast;

public class MessengerService extends Service {
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        //返回信差的绑定
        return msng.getBinder();

    }

    //信使,信差
    Messenger msng = new Messenger(new ActivityComingHander());

    private class ActivityComingHander extends Handler {
        Handler mHandler = new Handler();

        Messenger mMessenger;

        @Override
        public void handleMessage(final Message msg) {
            if (msg.what == 1) {
                Toast.makeText(MessengerService.this, "Activity发过来信息-标记是1", Toast.LENGTH_SHORT).show();
            }
            if (msg.what == 2) {
                //获取Activity发送过来的信差
                mMessenger = (Messenger) msg.obj;
                //定义消息和标记,等下发给Activity
                final Message msgg = new Message();
                msgg.what = 3;

                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        SystemClock.sleep(2000);
                        mHandler.post(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(MessengerService.this, "Activity发过来信息-标记是2", Toast.LENGTH_SHORT).show();
                            }
                        });
                    }
                }).start();
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        //三秒后服务给Activity发送消息
                        SystemClock.sleep(3000);
                        try {
                            mMessenger.send(msgg);
                        } catch (RemoteException e) {
                            e.printStackTrace();
                        }
                    }
                }).start();
                super.handleMessage(msg);
            }
        }
    }
}

再是AndroidManifest.xml代码,这个比较关于service的写法比较重要:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.server">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <service android:name=".MessengerService"
            android:enabled="true"
            android:exported="true">
            <intent-filter>
                <action android:name=".msng"/>
                <category android:name="android.intent.category.DEFAULT"/>
            </intent-filter>
        </service>
    </application>

</manifest>

还有布局文件的代码:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/bindButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="bindButton"
        android:layout_gravity="center"
        android:layout_margin="10dp"/>

    <Button
        android:id="@+id/sendButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="sendButton"
        android:layout_gravity="center"
        android:layout_margin="10dp"/>

    <Button
        android:id="@+id/sendButton2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="sendButton2"
        android:layout_gravity="center"
        android:layout_margin="10dp"/>


</LinearLayout>

 

最后是参考文献:

activity和service通信"-三大方法之-使用Messenger(信使,信差)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值