这篇文章记录的是我学Service基本知识的一个过程,做一个记录,希望能够和新手们共勉。
一 什么是服务:
Service是什么?服务,Activity给我们呈现出来的是具体的一个一个界面,而服务则像幕后工作者一样默默地给我们处理着一些后台数据.而且服务是一直默默挂在后台执行的。这是我的理解。
二 服务的运行过程:
服务不会自己执行,必须通过开启和绑定,在服务还没执行onCreate的时候,首先进入服务,会先执行onCreate然后进行onStart,如果服务正在执行的时候在进行开启和绑定的话,就会执行onStart,所以一个服务的onStart方法可能会被多次执行,所以个人理解服务的onStart方法是个很重要的,一般项目会在这里面进行很多操作,
如果stopService的时候会直接onDestroy,如果是调用者自己直接退出而没有调用stopService的话,Service会一直在后台运行,该Service的调用者再启动起来后可以通过stopService关闭Service
三 服务的生命周期:
这里我用一个小小的Demo来给大家演示一下,我最初学习的时候也是这样来观看的:
MainActivity
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private final static String TAG= "MyService";
private MyService.MyBinder mBinder;
private Messenger myServiceMessenger;
private Messenger mActivityMessenger;
private Button btnStartService,btnStopService,btnBinderService,btnUnbinderService;
private ProgressBar progressBar;
private Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
progressBar.setProgress(Integer.parseInt(msg.obj.toString()));
}
};
private ServiceConnection connection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
MyService.MyBinder myBinder = (MyService.MyBinder) service;
MyService myService = myBinder.getMyService();
myService.setCallBack(new MyService.CallBack(){
@Override
public void onDataChanged(String data) {
Message message = new Message();
message.obj = data;
handler.sendMessage(message);
}
});
Log.d(TAG,"ServiceConnected");
}
@Override
public void onServiceDisconnected(ComponentName name) {
mBinder=null;
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
setOnClickListner();
}
public void init(){
btnStartService = (Button) findViewById(R.id.btn_startservice);
btnStopService = (Button) findViewById(R.id.btn_stopservice);
btnBinderService = (Button) findViewById(R.id.btn_bindservice);
btnUnbinderService = (Button) findViewById(R.id.btn_unbindservice);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
}
public void setOnClickListner(){
btnStartService.setOnClickListener(this);
btnStopService.setOnClickListener(this);
btnBinderService.setOnClickListener(this);
btnUnbinderService.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.btn_startservice:
Intent startIntent = new Intent(this,MyService.class);
startService(startIntent);
break;
case R.id.btn_stopservice:
Intent stopIntent = new Intent(this,MyService.class);
stopService(stopIntent);
break;
case R.id.btn_bindservice:
Intent intent = new Intent(this, MyService.class);
bindService(intent, connection, Service.BIND_AUTO_CREATE);
break;
case R.id.btn_unbindservice:
unbindService(connection);
break;
default:
}
}
}
MyService
public class MyService extends Service {
private final static String TAG="MyService";
private MyBinder myBinder= new MyBinder();
private boolean threadIsRunning = false;
private CallBack callBack;
public void onCreate() {
super.onCreate();
Log.d(TAG, "onCreate() executed");
threadIsRunning = true;
new Thread(new Runnable() {
@Override
public void run() {
int count = 0;
while(threadIsRunning ==true){
count++;
if(count==100)
count=0;
if(callBack!=null){
callBack.onDataChanged(count+"");
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
}
public void setCallBack(CallBack callBack){
this.callBack = callBack;
}
public static interface CallBack{
void onDataChanged(String data);
}
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d(TAG, "onStartCommand() executed");
return super.onStartCommand(intent, flags, startId);
}
public IBinder onBind(Intent intent) {
return myBinder;
}
public void onDestroy() {
Log.d(TAG,"摧毁");
super.onDestroy();
threadIsRunning =false;
}
class MyBinder extends Binder {
public MyService getMyService(){
return MyService.this;
}
}
}
activity_main
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.administrator.learnservice.MainActivity">
<Button
android:id="@+id/btn_startservice"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAllCaps="false"
android:text="启动Service"/>
<Button
android:id="@+id/btn_stopservice"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAllCaps="false"
android:text="暂停Service"/>
<Button
android:id="@+id/btn_bindservice"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAllCaps="false"
android:text="绑定Service"/>
<Button
android:id="@+id/btn_unbindservice"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAllCaps="false"
android:text="解除Service"/>
<ProgressBar
android:id="@+id/progressBar"
android:layout_width="80dp"
android:layout_height="80dp"
android:visibility="visible"
/>
</LinearLayout>
先说一下具体思路,在MainActivity中,我们放了四个按钮,分别是启动服务,停止服务,绑定服务,解除绑定。然后我们给按钮建立监听的时候,分别点击不同按钮,实现不同的方法,startService,stopService,bindService,unBindService;
代码中可以看到,开启和停止服务都需要一个Intent对象,而绑定和解绑都需要一个ServiceConnection对象,代码中都有,Connection有失败和成功两种,代码中有都有。
然后我们在绑定成功的时候输出ServiceConnected
然后MyService中,我们在onCreate中输出onCreate,
在onStart中输出onStart,在 销毁的时候输出onDes
然后运行一下看看效果:
首先我们点击启动服务:
D/MyService: onCreate() executed
D/MyService: onStartCommand() executed
打印出来的日志是这样,他分别调用了onCreate和onStart
我们在点击停止服务:
D/MyService: 摧毁
打印出来摧毁,调用了onDes方法。
我们在点击绑定服务:
D/MyService: onCreate() executed
D/MyService: ServiceConnected
他首先调用了onCreate 方法然后又调用了MainActivity中的连接成功的方法。
然后我们点击解除绑定:
D/MyService: 摧毁
同上
现在我们多次点击开启服务:
onCreate() executed
onStartCommand() executed
onStartCommand() executed
onStartCommand() executed
onStartCommand() executed
可以看到首先进来的时候他分别调用了一次onCreate 和onStart
然后再点击之后他就会重复调用onStart
现在我们多次点击绑定服务:
D/MyService: onCreate() executed
D/MyService: ServiceConnected
可以看到这个多次点击绑定服务并不会有什么区别.
好了,这基本上就是Service的运行流程。这只是很基础的。还有更多的东西需要去学习。本人记录的只是学习过程,有不对的和不清楚的地方,请大神们多多包涵。