Android 实现Service和Activity之间的通信

(1)创建一个Service类 MyService

/*
    1.创建BindService服务端,继承自Service并在类中,创建一个实现IBinder 接口的实例对象并提供公共方法给客户端调用
    2.从 onBind() 回调方法返回此 Binder 实例。
    3.在客户端中,从 onServiceConnected() 回调方法接收 Binder,并使用提供的方法调用绑定服务
 */
public class MyService extends Service {
    private String data = "Service data";
    private String str;
    boolean serviceRunning;

    //IBinder接口
    //当另一个组件想要调用bindService()与服务绑定时,调用该方法
    //在此方法的中需要返回一个IBinder接口的实现类(启动状态下返回null)
    @Override
    public IBinder onBind(Intent intent) {
        Log.i("----***---","onBind方法被调用");
        return new MyBinder();
    }
    //Binder类实现IBinder
    public  class MyBinder extends Binder{
        //提供公共方法给客户端调用
        MyService getService(){
            return MyService.this;
        }
        public void setData(String data){
            MyService.this.data = data;
        }
    }

    //该方法只会被调用一次,用来执行一次性的设置
    @Override
    public void onCreate() {
        Log.i("----***---","onCreate方法被调用");
        super.onCreate();
        new Thread(){
            @Override
            public void run() {
                int n = 0;
                while (!serviceRunning){
                    n++;
                    str = n + data;
                    Log.d("Thread",str);
                    if (dataCallback!=null){
                        //不断的调用回调函数更新UI
                        dataCallback.dataChanged(str);
                    }else {
                        Log.d("Thread","dataCallback为空");
                    }
                    try {
                        sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }.start();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.i("----***---","onStartCommand方法被调用");
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        //当Service销毁时,停止while循环
        this.serviceRunning = true;
        Log.i("----***---","onDestroy方法被调用");
        super.onDestroy();
    }

    @Override
    public boolean onUnbind(Intent intent) {
        Log.i("----***---","onUnbind方法被调用");
        return super.onUnbind(intent);
    }

    DataCallback dataCallback = null;
    public DataCallback getDataCallback(){
        return  dataCallback;
    }

    public void setDataCallback(DataCallback dataCallback){
        this.dataCallback = dataCallback;
    }

    //通过回调机制,将Service内部的变化传递到外部
    public interface DataCallback{
        void dataChanged(String str);
    }
}

在实现的Service类中,在onCreate()方法中启动一个线程,不断调用回调函数,把Service的数据传给Activity 

(2)ServiceDemo1Activity.java

public class ServiceDemo1Activity extends AppCompatActivity implements View.OnClickListener{

    EditText et1,et2;
    Intent intent;
    Button start,stop,bind,unbind,sync;
    MyServiceConn myServiceConn;
    MyService.MyBinder binder = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_service_demo1);
        start = (Button) findViewById(R.id.start);
        stop = (Button) findViewById(R.id.stop);
        bind = (Button) findViewById(R.id.bind);
        unbind = (Button) findViewById(R.id.unbind);
        sync = (Button) findViewById(R.id.sync);
        et1 = (EditText) findViewById(R.id.et1);
        et2 = (EditText) findViewById(R.id.et2);
        //通过Intent绑定 Service
        intent = new Intent(ServiceDemo1Activity.this,MyService.class);
        myServiceConn = new MyServiceConn();
        start.setOnClickListener(this);
        stop.setOnClickListener(this);
        bind.setOnClickListener(this);
        unbind.setOnClickListener(this);
        sync.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch(v.getId()){
            case R.id.start:
                startService(intent);
                break;
            case R.id.stop:
                stopService(intent);
                break;
            case R.id.bind:
                //再连接时,调用onServiceConnected()
                bindService(intent,myServiceConn, Context.BIND_AUTO_CREATE);
                break;
            case R.id.unbind:
                unbindService(myServiceConn);
                break;
            case R.id.sync:
                //需要先绑定,才能同步数据
                if (binder != null){
                    binder.setData(et2.getText().toString());
                }else {
                }
                break;
            default:
                break;
        }
    }
    class MyServiceConn implements ServiceConnection{

        //当调用bindService()时,
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            binder = (MyService.MyBinder) service;
            //调用Service的回调函数,并具体实现其中的接口,在其中发送数据
            binder.getService().setDataCallback(new MyService.DataCallback() {
                @Override
                public void dataChanged(String str) {
                    Message message = new Message();
                    Bundle bundle = new Bundle();
                    bundle.putString("str",str);
                    message.setData(bundle);
                    //子线程发送消息到主线程
                    handler.sendMessage(message);
                }
            });
        }

        Handler handler = new Handler(){
            @Override
            public void handleMessage(Message msg) {
                //在handler中更新UI
                et1.setText(msg.getData().getString("str"));
            }
        };

        //服务崩溃或者被杀掉执行
        //当客户端取消绑定时,不会调用该方法
        @Override
        public void onServiceDisconnected(ComponentName name) {
            binder = null;
        }
    }
}

(3)xml文件




    
    
    

参考资料:《新编Android应用开发从入门到精通》

你可能感兴趣的:(Service)