Service

1、创建service类,并在AndroidManifest.xml里面注册该组件。

public class FirstService extends Service{}

<service
    android:name=".FirstService"
    android:enabled="true"
    android:exported="true"></service>

2、在service类中重写一些方法

启动和关闭service有两组方法可以被使用:

(1)startService和stopService
//Service被绑定时回调该方法(虽然在startService和stopService这组方法下onBind()没用,但必须写,不然会报错)
@Override
public IBinder onBind(Intent intent) {
	System.out.println("Service is bind");
	return null;
}
//Service被创建时回调该方法
@Override
public void onCreate() {
    super.onCreate();
    System.out.println("Service is Created");
}
//Service被启动时回调该方法
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    System.out.println("Service is Started");
    return super.onStartCommand(intent, flags, startId);
}
//Service被关之前回调该方法
@Override
public void onDestroy() {
    super.onDestroy();
    System.out.println("Service is Destroyed");
}
(2)bindService和unbindService
//Service被创建时回调该方法
@Override
public void onCreate() {
    super.onCreate();
    System.out.println("Service is Created");
}
//Service被绑定时回调该方法
@Override
public IBinder onBind(Intent intent) {
    System.out.println("Service is bind");
    return null;
}
//Service被解除绑定时回调该方法
@Override
public boolean onUnbind(Intent intent) {
    System.out.println("Service is unbind");
    return super.onUnbind(intent);
}
//Service被关之前回调该方法
@Override
public void onDestroy() {
    super.onDestroy();
    System.out.println("Service is Destroyed");
}

3、MainActivity中启动、关闭Service

(在布局文件中设置按钮控制service的启动和关闭)

启动和关闭service有两组方法可以被使用:

(1)startService和stopService
Button stopBn = findViewById(R.id.stopBn);
Button bindBn = findViewById(R.id.bindBn);
startBn.setOnClickListener(v -> startService(new Intent(this,FirstService.class)));
stopBn.setOnClickListener(v -> stopService(new Intent(this,FirstService.class)));
(2)bindService和unbindService
Button bindBn = findViewById(R.id.bindBn);
Button unbindBn = findViewById(R.id.unbindBn);

bindBn.setOnClickListener(v -> bindService(new 	       Intent(this,FirstService.class),connection,Context.BIND_AUTO_CREATE));

unbindBn.setOnClickListener(v -> unbindService(connection));

//activity和service的桥梁
private ServiceConnection connection = new ServiceConnection() {
    @Override
    public void onServiceConnected(ComponentName name, IBinder service) {

    }

    @Override
    public void onServiceDisconnected(ComponentName name) {

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值