Android Service

service中也有一系列生命周期的方法:
IBinder onBinder(Intent intent)
void onCreate()
void onDestroy()
int onStartCommand(Intent intent, int flags, int startId)
boolean onUnbind(Intent intent)

public class MyService extends Service {
    public static final String TAG="mTimer";
    public int NOTIFICATION_ID=0x123;
    public int count;
    @Override
    public void onCreate() {
        super.onCreate();
        Log.e(TAG, "Service is Create");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        Log.e(TAG,"Service is Start");
        return super.onStartCommand(intent, flags, startId);
    }

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

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

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return myBinder;
    }
    class MyBinder extends Binder{
        public int getCount(){
            return count;
        }
        public void startFromMine(){
            Log.e(TAG,"Service is Connection");
        }
    }
}

启动和关闭service,以及绑定和解除绑定可以直接在button的事件里进行

 public void ben_start(View view){
        Intent startIntent=new Intent(this,MyService.class);
        startService(startIntent);
    }
    public void btn_stop(View view){
        Intent stopIntent=new Intent(this,MyService.class);
        stopService(stopIntent);
    }
    public void btn_bind(View view){
        Intent bindIntent=new Intent(this,MyService.class);
        bindService(bindIntent, connection, BIND_AUTO_CREATE);

    }
    public void btn_getCount(View view){

        Log.e("---------",""+myBinder.getCount());
    }
    public void btn_unBind(View view){
        unbindService(connection);
    }

其中绑定的是IBinder对象,绑定后Activity就可以与Service进行通信。
btn_getCount()这个方法就是通过IBinder对象获取在Service中设置的数据值
Demo

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值