什么是Service:
可以长时间运行在后台的不可见的没有界面的组件
运行在主线程中
可以跨进程调用
为什么要使用service
因为service是Android中实现程序后台运行的解决方案,非常适合那些不需要与用户进行交互且需要长期运行的任务。
service启动方式有哪些
startService和bindService两种
使用startservice启动服务
1.新建类继承Service
public class MyService extends Service {
2.重写onCreate(),用来数据的初始化,在服务没有停止之前,只会执行一次
public void onCreate() {
super.onCreate();
Log.e(TAG+Thread.currentThread().toString(), "onCreate: " );
}
3.重写onStartCommand(),用来接收调用者传递过来的参数,可以编写需要的逻辑代码
当重复调用Service时,会重复执行
public int onStartCommand(Intent intent, int flags, int startId) {
return super.onStartCommand(intent, flags, startId);
}
4.实现onBind()方法
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
Log.e(TAG, "onBind: " );
throw new UnsupportedOperationException("Not yet implemented");
//return mBinder;
}
5.重写onDestroy(),做释放资源的操作
public void onDestroy() {
super.onDestroy();
Log.e(TAG, "onDestroy: " );
}
6.注册Service(在创建时会帮你实现)
<service
android:name=".MyService"
android:enabled="true"
android:exported="true"></service>
7.在context环境中通过startService启动Service
startIntent = new Intent(MainActivity.this,MyService.class);
this.startService(startIntent);
8.在context环境中通过stopService停止Service
this.stopService(startIntent);
实例讲解:
效果展现:点击启动服务和停止服务两次
可以看到虽然我点击了启动服务两次,但是,只执行了onCreate一次,但onStartCommand执行了两次,还有就是我点击了两次停止服务,但只执行了一次onDestroy方法,这原因我在介绍Service已经说过了,还可以看到的是,当服务停止时,线程并没有停止,这是因为子线程必须要执行完才会停止,不受服务关闭的影响,因为我在打印时同时打印了线程名,于是你可以看到,启动子线程的两个名字并不一样,且两个子线程各干各的,互不干扰
代码实现步骤:
1.在布局文件中完成控件的添加和id的设置,三四按钮暂时用不到
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.administrator.servicetest.MainActivity">
<EditText
android:id=