Android Service与Activity的交互

Android中有时候需要在Service中改变Activity的UI,或者在Activity中修改Service中的数值。首先必须使用与Activity绑定的Service,有三种方式可以实现。第一,是使用接口回调的方式在Activty中实现Service中的接口;第二,使用广播的方式传递;第三,则是用观察者模式,在Activity中实现update方法。

使用接口回调的方式在Activty中实现Service中的接口

package com.kkrs.serivce;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log;

/**
 * Created by zd on 2018/12/20.
 */

//绑定的service
public class LocalService extends Service {

    private final static String TAG = "LocalService";
    private int count;
    private boolean quit;
    private Thread thread;
    private LocalBinder binder = new LocalBinder();


    /**
     * 回调
     */
    private Callback callback;

    /**
     * 提供接口回调方法
     * @param callback
     */
    public void setCallback(Callback callback) {
        this.callback = callback;
    }


    /**
     * 回调接口
     *
     * @author lenovo
     *
     */
    public static interface Callback {
        /**
         * 得到实时更新的数据
         *
         * @return
         */
        void getNum(int num);
    }


    @Override
    public void onCreate() {
        super.onCreate();
        Log.e(TAG, "Service is invoke Created");
        thread = new Thread(new Runnable() {
            @Override
            public void run() {
                // 每间隔一秒count加1 ,直到quit为true。
                while (!quit) {
                    try {
                        Thread.sleep(1000);

                        if(callback!=null){
                /*
                 * 得到最新数据
                 */
                            callback.getNum(count);
                        }
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    count++;
                }
            }
        });
        thread.start();
    }

    public class LocalBinder extends Binder {
        // 声明一个方法,getService。(提供给客户端调用)
        LocalService getService() {
            // 返回当前对象LocalService,这样我们就可在客户端端调用Service的公共方法了
            return LocalService.this;
        }
    }

    /**
     * 公共方法
     * @return
     */
    public int getCount(){
        return count;
    }

    @Override
    public void onDestroy() {
        Log.e(TAG, "Service is onDestroy");

        this.quit = true;
        super.onDestroy();
    }

    @Override
    public boolean onUnbind(Intent intent) {
        Log.e(TAG, "Service is onUnbind");
        return super.onUnbind(intent);
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        Log.e(TAG, "Service is onBind");

        return binder;
    }
}

  

   private ServiceConnection conn;
    private LocalService mService;
  @Override
    protected void onCreate(Bundle savedInstanceState) {
    
 conn = new ServiceConnection() {
            /**
             * 与服务器端交互的接口方法 绑定服务的时候被回调,在这个方法获取绑定Service传递过来的IBinder对象,
             * 通过这个IBinder对象,实现宿主和Service的交互。
             */
            @Override
            public void onServiceConnected(ComponentName name, IBinder service) {
                Log.e("MainActivity", "绑定成功调用:onServiceConnected");
                // 获取Binder
                LocalService.LocalBinder binder = (LocalService.LocalBinder) service;
                mService = binder.getService();
                mService.setCallback(new LocalService.Callback(){

                    @Override
                    public void getNum(int num) {
                        // TODO Auto-generated method stub
                        Log.e("num","====num===="+num);
                    }
                });
            }
            /**
             * 当取消绑定的时候被回调。但正常情况下是不被调用的,它的调用时机是当Service服务被意外销毁时,
             * 例如内存的资源不足时这个方法才被自动调用。
             */
            @Override
            public void onServiceDisconnected(ComponentName name) {
                mService=null;
            }
        };

        final Intent intent = new Intent(this, LocalService.class);

        btnBind.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Log.e("MainActivity", "绑定调用:bindService");

                bindService(intent, conn, Service.BIND_AUTO_CREATE);

            }
        });

        btnUnBind.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // 解除绑定
                Log.e("MainActivity", "解除绑定:bindService");

                if(mService!=null) {
                    Log.e("MainActivity", "mService!=null");
                    mService = null;
                    unbindService(conn);
                }
            }
        });


        btnGetDatas.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (mService != null) {
                    // 通过绑定服务传递的Binder对象,获取Service暴露出来的数据
                    Log.e("MainActivity", "从服务端获取数据:" + mService.getCount());
                } else {

                    Log.e("MainActivity", "还没绑定呢,先绑定,无法从服务端获取数据");
                }
            }
        });

}

  使用广播的方式传递

package com.kkrs.serivce;

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

import static android.content.ContentValues.TAG;

/**
 * Created by zd on 2018/12/25.
 */

public class ContentService extends Service {

    private Thread thread;

    private boolean flag = true;

    @Override
    public IBinder onBind(Intent arg0) {
        // TODO Auto-generated method stub
        flag = true;
        return new LocalBinder();
    }

    @Override
    public void onCreate() {
        // TODO Auto-generated method stub
        super.onCreate();
        Log.e(TAG, "Service is invoke Created");
        thread = new Thread(new Runnable() {
            @Override
            public void run() {
                // 每间隔一秒count加1 ,直到quit为true。
                while (flag) {
                    try {
                        Thread.sleep(1000);
                        asyncSendPerson("ContentService");

                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        thread.start();

    }

    public final class LocalBinder extends Binder {
        public ContentService getService() {
            return ContentService.this;
        }
    }

    public void asyncSendPerson(final String name) {
        // 休息5秒,模拟异步任务
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                //可以在子线程中直接发送广播
                sendContentBroadcast(name);
            }
        }).start();
    }

    /**
     * 发送广播
     * @param name
     */
    protected void sendContentBroadcast(String name) {
        // TODO Auto-generated method stub
        Intent intent=new Intent();
        intent.setAction("com.example.servicecallback.content");
        intent.putExtra("name", name);
        sendBroadcast(intent);
    }

}

  

 //广播

    private ServiceReConn connRe;
    private ContentReceiver mReceiver;

    public class ServiceReConn implements ServiceConnection {

        @Override
        public void onServiceConnected(ComponentName name, IBinder binder) {
            // service = ((LocalBinder) binder).getService();
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            // TODO Auto-generated method stub
            // service = null;
        }
    }

    public class ContentReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String name = intent.getStringExtra("name");
            Person person = new Person();
            person.setName(name);
            Log.e("ContentReceiver",person.toString());
        }
    }

    /**
     * 注册广播接收者
     */
    private void doRegisterReceiver() {
        mReceiver=new ContentReceiver();
        IntentFilter filter = new IntentFilter(
                "com.example.servicecallback.content");
        registerReceiver(mReceiver, filter);
    }

  观察者模式

public class ObserviceService extends Service {
    //被观察者
    private MyObservable mObservable;
    private Thread thread;
    private boolean flag = true;

    @Override
    public IBinder onBind(Intent arg0) {
        flag = true;
        return new LocalBinder();
    }

    @Override
    public void onCreate() {
        super.onCreate();
        mObservable = new MyObservable();
        thread = new Thread(new Runnable() {
            @Override
            public void run() {
                // 每间隔一秒count加1 ,直到quit为true。
                while (true) {
                    try {
                        Thread.sleep(1000);
                        asyncSendPerson("ObserviceService");
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                }
            }
        });
        thread.start();
    }

    public final class LocalBinder extends Binder {
        public ObserviceService getService() {
            return ObserviceService.this;
        }
    }

    public void asyncSendPerson(final String name) {
        // 休息5秒,模拟异步任务
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                handler.sendMessage(handler.obtainMessage(0, name));
            }
        }).start();
    }

    /**
     * 添加观察者
     * @param observer
     */
    public void addObserver(Observer observer) {
        mObservable.addObserver(observer);
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            String name = (String) msg.obj;
            Person person = new Person();
            person.setName(name);
            //通知更新
            mObservable.notifyChanged(person);
        }
    };

    public class MyObservable extends Observable {

        public void notifyChanged(Object object) {
            this.setChanged();
            this.notifyObservers(object);
        }
    }

    @Override
    public boolean onUnbind(Intent intent) {
        flag = false;
        return super.onUnbind(intent);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        flag = false;
    }
}

 实现Observer

private ServiceConnection conn;
    private LocalService mService;


    //观察这模式
    private MyServiceConn connOb;
    private ObserviceService observiceService;
    public class MyServiceConn implements ServiceConnection {

        @Override
        public void onServiceConnected(ComponentName name, IBinder binder) {
            observiceService = ((ObserviceService.LocalBinder) binder).getService();
            //将当前activity添加为观察者
            observiceService.addObserver(MainActivity.this);
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            observiceService = null;
        }
    }

    @Override
    public void update(Observable observable, Object o) {
        Log.e("update","观察这模式在这里修改UI");
        Person person = (Person) o;
        Log.e("update",person.toString());
    }


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_main);
btnBindOb = (Button)findViewById(R.id.btnBindOb);
btnUnBindOb = (Button)findViewById(R.id.btnUnBindOb);


final Intent obIntent = new Intent(context, ObserviceService.class);
connOb = new MyServiceConn();
btnBindOb.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
bindService(obIntent, connOb, Service.BIND_AUTO_CREATE);

}
});

btnUnBindOb.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(observiceService!=null) {
Log.e("MainActivity", "observiceService!=null");
observiceService = null;
unbindService(connOb);
}
}
});

}

  

posted @ 2018-12-25 10:02  坎坷人生0  阅读(411)  评论(0编辑  收藏  举报