Android四大组件之Service复习笔记

最基础的service基础知识,总结并且在复习一遍。

什么是服务,服务就是Android实现程序后台运行的解决方案,执行那些不需要和用户交互而且要求长时间运行的任务,服务并不是运行在一个独立的应用程序之中而是依赖于创建服务时所在的应用程序进程。

这里盗取官网一张Service的生命周期图:


用 startService()启动服务,用stopService()停止服务,Service生命周期是这样的:


如果没有点击stopService(),只需要在service类中任一位置调用stopSelf()方法就能让这个服务停下来。

服务和进程通信,Activity绑定一个服务:

用bindService()启动服务,用unbindService()停止服务,Service生命周期是这样的:

也可以既调用startService(),又调用bindService(),一个服务只要被启动或者被绑定之后就一直会处于运行状态,必须同时调用stopSelf()和unbindService(),onDestory方法才会被执行。

1.这里写一个Activity绑定Service并进行加法计算的小例子:

<span style="font-size:14px;">public class MyService extends Service {
    private final IBinder mbinder = new LocalBinder();

    public class LocalBinder extends Binder{
        public MyService getService(){
            return MyService.this;
        }
    }
    @Override
    public void onCreate() {
        super.onCreate();
        Log.i("megan", "Server-------onCreate()");
    }
    @Override
    public void onDestroy() {
        Log.i("megan", "Server-------onDestroy()");
    }
    @Override
    public void onStart(Intent intent, int startId) {
        super.onStart(intent, startId);
        Log.i("megan", "Server-------onStart()");
    }
    @Override
    public void onRebind(Intent intent) {
        Log.i("megan", "Server-------onRebind()");
        super.onRebind(intent);
    }
    @Override
    public IBinder onBind(Intent intent) {
        Log.i("megan", "Server-------onBind()");
        Toast.makeText(this, "本地绑定", Toast.LENGTH_SHORT).show();
        return mbinder;
    }
    @Override
    public boolean onUnbind(Intent intent) {
        Log.i("megan", "Server-------onUnbind()");
        Toast.makeText(this, "取消绑定", Toast.LENGTH_SHORT).show();
        return super.onUnbind(intent);
    }
    public long add(long a, long b){
        return a + b;
    }
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.i("megan", "Server-------onStartCommand()");
        return super.onStartCommand(intent, flags, startId);
    }
}</span>
Activity代码:

<span style="font-size:14px;">public class MainActivity extends Activity {
    Intent serviceIntent;
    private MyService myservice;
    TextView labelView;
    private boolean isBound = false;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        LinearLayout linearlayout = new LinearLayout(this);
        labelView = new TextView(this);
        linearlayout.addView(labelView);
        
        Button btnBind = new Button(this);
        btnBind.setText("服务绑定");
        linearlayout.addView(btnBind);

        Button btnCancelBind = new Button(this);
        btnCancelBind.setText("取消绑定");
        linearlayout.addView(btnCancelBind);

        Button btnPlus = new Button(this);
        btnPlus.setText("加法运算");
        linearlayout.addView(btnPlus);

        setContentView(linearlayout);
        btnBind.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
                if(!isBound){
                    serviceIntent = new Intent(MainActivity.this,MyService.class);
                    bindService(serviceIntent, mConnection, Context.BIND_AUTO_CREATE);
//                     startService(serviceIntent);
                    isBound = true;
                }
            }
        });
        btnCancelBind.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                if(isBound){
                    isBound = false;
                    unbindService(mConnection);
//                    stopService(serviceIntent);
                    myservice = null;

                }
            }
        });

    btnPlus.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
           if(myservice == null){
               labelView.setText("未绑定服务");
               return;
           }
           long a = Math.round(Math.random() * 100);
           long b = Math.round(Math.random() * 100);
           long result = myservice.add(a, b);
           String msg = String.valueOf(a) + "+" + String.valueOf(b)
                  + "=" + String.valueOf(result);
           labelView.setText(msg);
        }
    });
 }
    private ServiceConnection mConnection = new ServiceConnection() {
        public void onServiceDisconnected(ComponentName name) {
            myservice = null;
        }
        public void onServiceConnected(ComponentName name, IBinder service) {
            myservice = ((MyService.LocalBinder)service).getService();
        }
    };
}
在Activity中调用服务端的add()方法进行计算。
点击绑定服务,服务开启,点击加法运算按钮,会有随机数的结果和显示在最前面,
如果点击取消绑定,点击加法运算就会弹出一个toast显示服务未绑定,不能进行加法计算。
 
 







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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值