文章目录
一、Service是什么?
Service则是Android提供一个允许长时间留驻后台的一个组件,执行长时间运行且不需要用户交互的任务。最常见的 用法就是做轮询操作,或者想在后台做一些事情,比如后台下载更新…服务包含的状态:
二、Service的生命周期
三、Service的使用
1.startService 与 stopService
设置两个按钮,分别是startService 与 stopService
<!-- startService 对应 stopService 区域 -->
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="startService 对应 stopService 区域"
android:textSize="20dp"
android:textColor="@color/design_default_color_secondary"
android:layout_gravity="center_horizontal"
/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="startServce"
android:onClick="startServce"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="stopServce"
android:onClick="stopServce"
/>
</LinearLayout>
对应的点击事件:
/**
* 跳转到第二个Activity 的事件函数
* @param view
*/
public void startActivity2(View view) {
startActivity(new Intent(this, MainActivity2.class));
}
// =========================== startService 对应 stopService 区域
// 启动服务
public void startServce(View view) {
startService(new Intent(this, MyService.class));
}
// 停止服务
public void stopServce(View view) {
stopService(new Intent(this, MyService.class));
}
2.bindService 与unBindService
设置两个按钮,分别是bindService和unBindService
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="bindService 对应 unBindService 区域"
android:textSize="20dp"
android:textColor="@color/black"
android:layout_marginTop="100dp"
android:layout_gravity="center_horizontal"
/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="bindServce"
android:onClick="bindServce"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="unBindServce"
android:onClick="unBindServce"
/>
</LinearLayout>
对应的点击事件:
// =========================== bindService 对应 unBindService 区域
public void bindServce(View view) {
bindService(new Intent(this, MyService.class), connecton, Context.BIND_AUTO_CREATE);
}
public void unBindServce(View view) {
unbindService(connecton);
}
// MainActivity 与 MyService 的桥梁
private ServiceConnection connecton = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
}
@Override
public void onServiceDisconnected(ComponentName name) {
}
};
// 一般的写法,当此Activity被销毁的时候,自动解绑服务
@Override
protected void onDestroy() {
super.onDestroy();
unbindService(connecton);
}