Android Service,startService binderService 以及 AIDL

一、首先了解Android中的服务,他可以长期保存在系统后天,等待系统或其他应用的调用。在系统启动时,开启了很多的系统,我们使用getSystemService(serviceName)获取到的XXXManager,其实是获取系统服务的接口,用XXXManager调用系统服务,系统服务调用时通过AIDL 机制 实现的。

二、service根据进程分为 本地service 和 远程service 。

       AIDL :Android interface Definition language 他是Android内部进程通讯的描述语言。通过他可以定义进程通讯的接口。而远程service 是通过AIDL 实现进程间通信的。调用系统服务也是用AIDL 实现的。

三、service 启动方式 

     1、startService  开启服务后 我们的上下文就和这个服务失去联系。使用该方式启动 调用者不可以访问 service里面的方法. 调用者如果被系统回收了或者调用了ondestroy方法, service还会继续存在 ,如果该service已经启动了,在调用startService 调用onStart();

      2、binderService 开启服务后上下文Context 会和 该服务建立一个连接,在建立连接中要 实现 ServiceConnection 接口,实现接口中方法

onServiceConnected(ComponentName name, IBinder service)
onServiceDisconnected(ComponentName name)

方法 ,并获取到 binder 对象 ,通过binder对象访问 service。

 在 service端 的onBind() 返回值是个 IBinder 对象。 并在在该service中 写个内部类 继承 Binder 类。通过内部类的特性:内部对象有外部类的引用,可以访问外部类。所以 在 activity中获取到 binder对象后,就可以访问service中的方法了。

binderService只能绑定服务一次,意思是 只调用 onBinder一次。

    3、service的生命周期

   

四 、 startService和 binderService 实例

(1)mainactivity

public class MainActivity extends Activity {
    Button startServiceButton;// 启动服务按钮
    Button shutDownServiceButton;// 关闭服务按钮
    Button startBindServiceButton;// 启动绑定服务按钮    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        getWidget();
        regiestListener();
    }    /** 获得组件 */
    public void getWidget() {
        startServiceButton = (Button) findViewById(R.id.startServerButton);
        startBindServiceButton = (Button) findViewById(R.id.startBindServerButton);
        shutDownServiceButton = (Button) findViewById(R.id.sutdownServerButton);
    }    /** 为按钮添加监听 */
    public void regiestListener() {
        startServiceButton.setOnClickListener(startService);
        shutDownServiceButton.setOnClickListener(shutdownService);
        startBindServiceButton.setOnClickListener(startBinderService);
    }    
    
    /** 启动服务的事件监听 */
    public Button.OnClickListener startService = new Button.OnClickListener() {        public void onClick(View view) {            /** 单击按钮时启动服务 */
            Intent intent = new Intent(MainActivity.this,
                    CountService.class);
            startService(intent);
            
            Log.v("MainStadyServics", "start Service");
        }
    };    /** 关闭服务 */
    public Button.OnClickListener shutdownService = new Button.OnClickListener() {        public void onClick(View view) {            /** 单击按钮时启动服务 */
            Intent intent = new Intent(MainActivity.this,
                    CountService.class);            /** 退出Activity是,停止服务 */
            stopService(intent);
            Log.v("MainStadyServics", "shutDown serveice");
        }
    };    /** 打开绑定服务的Activity */
    public Button.OnClickListener startBinderService = new Button.OnClickListener() {        public void onClick(View view) {            /** 单击按钮时启动服务 */
            Intent intent = new Intent(MainActivity.this, UseBrider.class);
            startActivity(intent);
            Log.v("MainStadyServics", "start Binder Service");
        }
    };
    @Override    public boolean onCreateOptionsMenu(Menu menu) {        // Inflate the menu; this adds items to the action bar if it is present.        getMenuInflater().inflate(R.menu.main, menu);        return true;
    }

(2)service

package com.example.testservice;/**引入包*/import android.app.Service;// 服务的类import android.os.IBinder;import android.os.Binder;import android.content.Intent;import android.util.Log;/** 计数的服务 */public class CountService extends Service {    /** 创建参数 */
    boolean threadDisable;    int count;    public IBinder onBind(Intent intent) {        return null;
    }    public void onCreate() {        super.onCreate();        /** 创建一个线程,每秒计数器加一,并在控制台进行Log输出 */
        new Thread(new Runnable() {            public void run() {                while (!threadDisable) {                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {

                    }
                    count++;
                    Log.v("CountService", "Count is" + count);
                }
            }
        }).start();
    }    public void onDestroy() {        super.onDestroy();        /** 服务停止时,终止计数进程 */
        this.threadDisable = true;
    }    public int getConunt() {        return count;
    }

//此方法是为了可以在Acitity中获得服务的实例
class ServiceBinder extends Binder {        public CountService getService() {            return CountService.this;
        }
    }
}

(3)bindservice(一定要记着这个是要获得,链接的对象)

package com.example.testservice;/**引入包*/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.IBinder;import android.util.Log;/** 通过bindService和unBindSerivce的方式启动和结束服务 */public class UseBrider extends Activity {    /** 参数设置 */
    CountService countService;

    @Override    public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);
        setContentView(new UseBriderFace(this));
        
        Intent intent = new Intent(UseBrider.this, CountService.class);        /** 进入Activity开始服务 */
        bindService(intent, conn, Context.BIND_AUTO_CREATE);

    }    
    private ServiceConnection conn = new ServiceConnection() {        /** 获取服务对象时的操作 */
        public void onServiceConnected(ComponentName name, IBinder service) {            // TODO Auto-generated method stub
            countService = ((CountService.ServiceBinder) service).getService();

        }        /** 无法获取到服务对象时的操作 */
        public void onServiceDisconnected(ComponentName name) {            // TODO Auto-generated method stub
            countService = null;
        }

    };    protected void onDestroy() {        super.onDestroy();        this.unbindService(conn);
        Log.v("MainStadyServics", "out");
    }
}

五、AIDL 实现
http://blog.csdn.net/liuhe688/article/details/6400385

六、其他相关问题优秀博客:

http://www.2cto.com/kf/201501/370478.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值