Service是什么呢?
他同Activity相比,最大的不同就是他没有专门的Layout展示界面,他默默的工作在App的后台。
虽然除了少数几种情况,我们不需要使用Service,但我们也有必要了解一下Service的使用方法
我们知道Activity由于其自有缺陷,如果Activity产生了跳转,那么当前Activity的工作就会被完全停止。
但是有时候我们希望在听歌、打接电话、下载文件的过程中继续别的活动,这时候我们就应该使用Service,不论前端的Activity如何变幻,只要Service没有被停止,Service就会继续他的工作。
Service的工作流程图如下:
使用Service首先需要新建一个继承自Service的类
package com.example.testservice;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.widget.Toast;
public class ServiceTest extends Service {
@Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "已经绑定好了", Toast.LENGTH_SHORT).show();
return null;
}
@Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
Toast.makeText(getApplicationContext(), "服务解除", Toast.LENGTH_SHORT).show();
}
@Override
public void onStart(Intent intent, int startId) {
// TODO Auto-generated method stub
super.onStart(intent, startId);
Toast.makeText(getApplicationContext(), "已经绑定好了", Toast.LENGTH_SHORT).show();
}
}
<service android:name="ServiceTest"></service>
下面我们来看看调用Service服务的两种方案:
一、startService
Intent startService = new Intent(MainActivity.this,ServiceTest.class);
startService(startService);
二、bindService
Intent startService = new Intent(MainActivity.this,ServiceTest.class);
ServiceConnection serviceConnect = null;
bindService(startService,serviceConnect,Context.BIND_AUTO_CREATE);
这两种方法最大的不同在于 bindService会在APP程序退出时自动解除对于Service的绑定,而startService则需要手动终止服务,所以我们需要根据自己的需要选择合适的方法调用Service