1.什么是Service:
安卓四大组件之一,服务是在后台执行的一种任务,依赖于创建服务时的那个程序的进程,当这个进程被关闭时,后台服务也会关闭。
2.为什么要用Service:
用于安卓解决后台运行的问题,他不需要和用户进行交互,适合执行一些不需要和用户进行交互且需要进行长期运行的操作。
3.Service的启动方式;
共有两种:1.startService(Intent参数);
2.bindService(参数);
提示。需要在androidmanifest文件中先注册才行。
<service android:name=".myservice"/service>
4.startService的特点:
运行在后台的服务如果不需要和UI线程进行交互时调用。
回调的方法都是在主线程里执行,多次启动oncreate方法只会调用一次,而onstartcommand却是多次调用。
5.startService的使用示例:
public class MainActivity extends AppCompatActivity {
private Button bt1;
private Button bt2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bt1=findViewById(R.id.bt1);
bt2=findViewById(R.id.bt2);
bt1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent start=new Intent(MainActivity.this,service.class);
//安卓5.0后规定Intent必须为显示的才可启动服务
startService(start);//用startService启动服务
}
});
bt2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent stop=new Intent(MainActivity.this,service.class);
stopService(stop);//stopService来停止服务
}
});
}
}
public class service extends Service {
@Nullable
@Override
public IBinder onBind(Intent intent) {
Log.e("ddc", "onBind: "+"###########################################" );
return null;
}
@Override
public void onCreate() {//服务启动时只调用一次,哪怕是多次启动,主要用于完成一些初始化操作。
Log.e("ddc", "onCreate: "+"###########################################" );
super.onCreate();
}
@Override
public boolean onUnbind(Intent intent) {
Log.e("ddc", "onUnbind: "+"###########################################" );
return super.onUnbind(intent);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
new Thread(new Runnable() {//可多次回调
@Override
public void run() {
for(int i=0;i<=20;i++){
Log.e("dsd", "handleMessage: "+i +Thread.currentThread().getName()+"***************");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
Log.e("ddc", "onStartCommand: "+"###########################################" );
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {//销毁服务
Log.e("ddc", "onDestroy: "+"###########################################" );
super.onDestroy();
}
}
<?xml version="1.0" encoding="utf-8"?>
<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.zhang.service.MainActivity">
<Button
android:id="@+id/bt1"
android:text="启动服务"
android:layout_width="match_parent"
android:layout_height="80dp" />
<Button
android:id="@+id/bt2"
android:text="停止服务"
android:layout_width="match_parent"
android:layout_height="80dp" />
</LinearLayout>
6.bindService的特点:
两个不同进程间的通信或service被相同进程调用时
需要先在继承Service类里创一个内部类,再通过ServiceConnection对象在activty中创对象调用
7.bindService的使用示例:
public class Main2Activity extends AppCompatActivity {
private Button q1;
private Button q2;
private Button q3;
private ServiceConnection cn=new ServiceConnection() {//创ServiceConnection对象
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
service2 ser=((service2.guanjia)service).gets();//创继承Service类的对象
ser.fly(Main2Activity.this);//对类中方法的调用
}
@Override
public void onServiceDisconnected(ComponentName name) {
}
};
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
q1=findViewById(R.id.q1);
q2=findViewById(R.id.q2);
q3=findViewById(R.id.q3);
final Intent intent=new Intent(Main2Activity.this,service2.class);
q1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
bindService(intent,cn, Service.BIND_AUTO_CREATE);//启动服务
}
});
q2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
unbindService(cn);
}
});
q3.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent1=new Intent(Main2Activity.this,Main3Activity.class);
startActivity(intent1);
}
});
}
}
public class service2 extends Service {
public guanjia binder=new guanjia();
//得到service的对象
public class guanjia extends Binder{
public service2 gets(){
return service2.this;
}
}
public void fly(Context context){
Toast.makeText(context,"fly",Toast.LENGTH_SHORT).show();
Log.e("ygyg", "fly: "+"起飞" );
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
Log.e("ssfr", "onBind: " );
return binder;
}
@Override
public void onCreate() {
super.onCreate();
Log.e("thrh6h", "onCreate: rfr" );
}
@Override
public boolean onUnbind(Intent intent) {
Log.e("gfs", "onUnbind: jr7j7j" );
return true;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.e("fhv", "onStartCommand: hdhvhdsvds" );
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onRebind(Intent intent) {
super.onRebind(intent);
Log.e("njn", "onRebind: jvsjvsdjvs" );
}
@Override
public void onDestroy() {
super.onDestroy();
Log.e("dsv", "onDestroy: " );
}
}
<?xml version="1.0" encoding="utf-8"?>
<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.zhang.service.Main2Activity">
<Button
android:id="@+id/q1"
android:text="启动服务"
android:layout_width="match_parent"
android:layout_height="80dp" />
<Button
android:id="@+id/q2"
android:text="停止服务"
android:layout_width="match_parent"
android:layout_height="80dp" />
<Button
android:id="@+id/q3"
android:text="天平座"
android:layout_width="match_parent"
android:layout_height="80dp" />
</LinearLayout>
8.IntentService的特点及优缺点:
intentservice内部采用HandleThread来执行任务,任务执行完毕后,intentservice会自动退出。多次启动服务时,intentservice会创出多个等待,排队一个一个处理
优点:intentservice自带一个工作线程,当需要做耗时操作时可以使用intentservice。任务完成后会自动停止
9.IntentService的使用示例:
<?xml version="1.0" encoding="utf-8"?>
<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.zhang.service.Main4Activity">
<Button
android:textSize="30dp"
android:text="启动"
android:id="@+id/bt"
android:layout_width="match_parent"
android:layout_height="80dp" />
</LinearLayout>
public class Intentservice extends IntentService{
/**
* Creates an IntentService. Invoked by your subclass's constructor.
*
* @param name Used to name the worker thread, important only for debugging.
*/
public Intentservice(String name) {
super(name);
}
public Intentservice(){//必须建。不然注册时会报错
super("");
}
@Override
protected void onHandleIntent(@Nullable Intent intent) {//内置线程
for(int i=0;i<=5;i++){
try {
Thread.sleep(1000);
Log.e("fvrer", "onHandleIntent: "+i );
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class Main4Activity extends AppCompatActivity {
private Button bt;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main4);
bt=findViewById(R.id.bt);
bt.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {//启动服务
Intent intent=new Intent(Main4Activity.this,Intentservice.class);
startService(intent);
}
});
}
}
10.IntentService和Service的区别:
service是运行在主线程中,会带来UI阻塞,所以在耗时操作时,会在onstartCommand中开启一个新线程,去执行耗时操作。
为了简化工作量,就提供了一个类intentservice,intentservice自带一个工作线程,当需要做耗时操作时可以使用intentservice,任务完成后会自动停止。intentservice是继承自service类。