• Android之Service通信-(1)


    一、本地Service通信

    LocalService 

    /**
     * Created by lsj on 2015/8/29.
     * 这是一个LocalService
     */
    public class StrReplaceService extends Service {
        private final String TAG="StrReplaceService" ;
    
        public class MyBinder extends Binder{
            public StrReplaceService getService(){
                return StrReplaceService.this ;
            }
        }
    
        @Override
        public void onCreate() {
            super.onCreate();
            Log.d(TAG, "onCreate");
        }
    
        @Override
        public IBinder onBind(Intent intent) {
            Log.d(TAG, "onBind");
            return  new MyBinder() ;
        }
    
    
        @Override
        public boolean onUnbind(Intent intent) {
            Log.d(TAG, "onUnbind");
            return super.onUnbind(intent);
        }
    
        @Override
        public void onDestroy() {
            Log.d(TAG, "onDestroy");
            super.onDestroy();
        }
    
        public String strReplace (){
            String result = StringReplace.test() ;
            Log.d(TAG,result) ;
            return result ;
        }
    }
    

    测试Activity

    public class StringReplaceActivity extends BaseActivity {
    
        private TextView resultTv ;
        private ServiceConnection sc ;
        private StrReplaceService strReplaceService ;
        String result ="string" ;
    
        @Override
        public void onClick(View v) {
    
        }
    
        @Override
        protected void onStart() {
            super.onStart();
            Intent intent = new Intent(this, StrReplaceService.class);
            //onCreate时候已经有了sc
            bindService(intent, sc , Context.BIND_AUTO_CREATE) ;
        }
    
        @Override
        protected void onStop() {
            super.onStop();
            unbindService(sc);
        }
    
        @Override
        protected void findView() {
            setContentView(R.layout.activity_str_replace);
        }
    
        @Override
        protected void initView() {
            resultTv = (TextView)findViewById(R.id.str_replace_resultTv);
            sc = new ServiceConnection() {
                @Override
                public void onServiceConnected(ComponentName name, IBinder service) {
                    strReplaceService = ((StrReplaceService.MyBinder)service).getService() ;
                    //这个可以在onClick中调用
                    doService();
                }
    
                @Override
                public void onServiceDisconnected(ComponentName name) {
    
                }
            };
    
        }
    
        /**
         * 调用StrReplaceService中的方法
         */
        private void doService(){
            result = strReplaceService.strReplace() ;
            Log.d(TAG, result) ;
            resultTv.setText(result);
        }
    
        @Override
        protected void setOnClickListener() {
    
        }
    }  

      

    二、跨进程Service通信 

    RemoteService 

    /**
     * this is remote service
     */
    public class CQueueService extends Service {
        private  final String TAG ="CQueueService";
    
        public static final int MSG_NO = 0;
    
        class IncomingHandler extends  Handler{
            @Override
            public void handleMessage(Message msg) {
                if (msg.replyTo != null){
                    //收到消息后就向客户端发送一个回应
                    Message msg_to_client = this.obtainMessage() ;
                    msg_to_client.what = CQueueActivity.MSG_NO_TO_CLIENT;
                    try {
                        //得到客户端的Messenger,并向它发送消息
                        cMessenger = msg.replyTo ;
                        cMessenger.send(msg_to_client);
                    }catch (RemoteException e){
    
                    }
                }
                switch (msg.what){
                    case MSG_NO:
                        Toast.makeText(CQueueService.this, "msg from client", Toast.LENGTH_LONG).show();
                        break;
                    default:
                        super.handleMessage(msg);
                }
            }
        }
    
        /**
         * 自己的Messenger
         */
        Messenger sMessenger= new Messenger(new IncomingHandler());
        //客户端的Messenger
        Messenger cMessenger ;
        public CQueueService() {
        }
    
        @Override
        public void onCreate() {
            Log.e(TAG, "onCreate");
            super.onCreate();
        }
    
        @Override
        public IBinder onBind(Intent intent) {
            Log.e(TAG, "onBind");
            //返回自己Messenger的binder,以供客户端通过Binder(new Messenger(binder))得到Service的Messenger对象。
            return sMessenger.getBinder();
        }
    
        @Override
        public boolean onUnbind(Intent intent) {
            Log.e(TAG, "onUnbind");
            return super.onUnbind(intent);
        }
    }
    

    在配置文件中

     <!-- remote service -->
            <service
                android:name=".service.CQueueService"
                android:enabled="true"
                android:exported="true"
                android:process=":remote" >
            </service>
    

    测试Activity  

    public class CQueueActivity extends BaseActivity{
        public static final int MSG_NO_TO_CLIENT=0;
    
        ServiceConnection mSc ;
    
        /**
         * handler of incoming msg from serivce
         */
        class IncomingHandler extends Handler{
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what){
                    case MSG_NO_TO_CLIENT:
                        Toast.makeText(CQueueActivity.this,"ack_msg from service", Toast.LENGTH_LONG).show();
                        break;
                    default:
                        super.handleMessage(msg);
                }
            }
        } ;
        /**
         * 自己的Messenger
         */
        Messenger mMessenger = new Messenger(new IncomingHandler()) ;
        //remote Service 的Messenger
        Messenger sMessenger ;
    
        @Override
        protected void findView() {
            setContentView(R.layout.activity_cqueue);
        }
    
        @Override
        protected void initView() {
            mSc = new ServiceConnection() {
                @Override
                public void onServiceConnected(ComponentName name, IBinder service) {
                    Log.d(TAG, "onServiceConnected");
                    //得到服务端的Messenger
                    sMessenger = new Messenger(service);
                    //向服务端发送消息
                    sendMsg() ;
    
                }
    
                @Override
                public void onServiceDisconnected(ComponentName name) {
                    Log.d(TAG, "onServiceDisconnected");
    
                }
            } ;
        }
    
        /**
         * 使用服务端的Messenger向它发送消息
         */
        private void sendMsg(){
            Message msg_to_service = new Message();
            msg_to_service.replyTo =  mMessenger;
            try{
                sMessenger.send(msg_to_service);
            }catch (RemoteException e ){
                e.printStackTrace();
            }
        }
    
    
        @Override
        protected void onStop() {
            super.onStop();
            this.unbindService(mSc);
        }
    
        @Override
        protected void onStart() {
            super.onStart();
            Log.d(TAG, this.getApplicationContext().getPackageCodePath()) ;
            Intent service  = new Intent(this, CQueueService.class) ;
            this.bindService(service, mSc, Context.BIND_AUTO_CREATE) ;
        }
    
        @Override
        public void onClick(View v) {
    
        }
    
        @Override
        protected void setOnClickListener() {
    
        }
    }
    

      

      

  • 相关阅读:
    idea报错:error java compilation failed internal java compiler error
    idea怎么设置自己的名字和时间
    linux安装mvn后提示权限不够
    【转】java.util.Arrays.asList 的用法
    String... 用法
    zk 起别名时候碰到的问题
    集群配置 出现 “没有到主机的路由”
    修改linux的hosts 后提示“无效的参数”
    概念理解系列-------------贴近生活的奇葩解释模式
    org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'supplierAction': Injection of resource dependencies failed; nested exception is org.springframework.beans.factor
  • 原文地址:https://www.cnblogs.com/chuiyuan/p/4782553.html
Copyright © 2020-2023  润新知