Service作为Android四大组件(activity、service、content provider、broadcast receiver)之一,在每一个应用程序中都扮演着非常重要的角色。它主要用于在后台处理一些耗时的逻辑,或者去执行某些需要长期运行的任务,并且不提供用户界面,服务能被其它应用程序的组件启动,即使用户切换到另外的应用时还能保持后台运行。必要的时候我们甚至可以在程序退出的情况下,让Service在后台继续保持运行状态。
可以处理网络传输、音乐播放、下载,执行文件I/O、或者与content provider进行交互
3.StartService方式启动Service应该如何做(启动和停止及生命周期)
实现步骤:
<service android:name=".MyService" />
Demo
MyService.java
package com.example.fpl.week3application;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log;
public class MyService extends Service {
String TAG="MyService";
private int num;
@Override
public IBinder onBind(Intent intent) {
Log.e(TAG," onBind......");
return null;
}
@Override
public void onCreate() {
Log.e(TAG,"onCreate......");
super.onCreate();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
String name=intent.getStringExtra("name");
Log.e(TAG,"onStartCommand......"+name);
new Thread(new Runnable() {
@Override
public void run() {
// Log.e(TAG,Thread.currentThread().getName());
while (num<100){
Log.e(TAG, String.valueOf(num));
num++;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
Log.e(TAG,"onDestroy......");
super.onDestroy();
}
}
MyActivity.java
package com.example.fpl.week3application;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private Button button;
private Button button2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bindID();
}
private void bindID() {
button=findViewById(R.id.Servicestart_BTN);
button2=findViewById(R.id.Servicestop_BTN);
button2.setOnClickListener(this);
button.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.Servicestart_BTN:
Intent intent=new Intent(this,MyService.class);
intent.putExtra("name","隆记");
//通过startService启动
startService(intent);
break;
case R.id.Servicestop_BTN:
Intent intent2=new Intent(this,MyService.class);
//关闭Service
stopService(intent2);
break;
default:
break;
}
}
@Override
protected void onDestroy() {
Log.e("MainActivity","onDestory......");
Intent intent2=new Intent(this,MyService.class);
stopService(intent2);
super.onDestroy();
}
}
优点:使用简单,
缺点:线程开启后不受控制,
引入BindService
这里要引入Binder,通过Binder绑定Service,起到控制Service的作用,当连接中断时Service也被销毁;
package com.example.fpl.week3application;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.provider.Settings;
import android.support.annotation.Nullable;
import android.util.Log;
public class SecondService extends Service {
private int count=0;
//Binder类实例化对象
private MyBinder binder=new MyBinder();
//继承Binder
public class MyBinder extends Binder{
public SecondService getServices(){
return SecondService.this;
}
}
@Nullable
//返回binder
@Override
public IBinder onBind(Intent intent) {
System.out.println("执行onBind方法...");
return binder;
}
@Override
public boolean onUnbind(Intent intent) {
System.out.println("执行onUnBind方法...");
return true;
}
@Override
public void onCreate() {
super.onCreate();
System.out.println("执行onCreate方法");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
System.out.println("执行onStartCommand方法");
//三种返回值(仅限使用startService方法启动时有效果)
//START_STICKY,服务被异常杀掉后,会重启服务
//START_NOT_STICKY,服务被异常杀掉后,不会重启服务
//START_REDELIVER_INTENT,服务被异常kill掉,系统会自动重启该服务,并将Intent的值传入
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onRebind(Intent intent) {
super.onRebind(intent);
System.out.println("rebind");
}
@Override
public void onDestroy() {
super.onDestroy();
System.out.println("执行onDestroy方法");
}
public void ff(){
new Thread(new Runnable() {
@Override
public void run() {
while (count<100){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
count++;
Log.e("Second", String.valueOf(count));
}
}
}).start();
/* class MyThread extends Thread{
@Override
public void run() {
while (count<100){
try {
Thread.sleep(1000);
System.out.print(Thread.currentThread().getName()+"*******"+Thread.currentThread().getId());
} catch (InterruptedException e) {
e.printStackTrace();
}
count++;
System.out.print(count);
}
super.run();
}
}*/
}
}
package com.example.fpl.week3application;
import android.app.Service;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class SecondMainActivity extends AppCompatActivity implements View.OnClickListener{
private Button button;
private Button button1;
private Intent intent;
//通过ServiceConnection连接
private ServiceConnection connection=new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
SecondService ms = ((SecondService.MyBinder) service).getServices();
//调用Service方法
ms.ff();
}
@Override
public void onServiceDisconnected(ComponentName name) {
System.out.println("connected");
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second_main);
// intent=new Intent(this,SecondService.class);
bindID();
}
private void bindID() {
button=findViewById(R.id.ServicestartSec_BTN);
button1=findViewById(R.id.ServicestopSec_BTN);
button.setOnClickListener(this);
button1.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.ServicestartSec_BTN:
intent=new Intent(this,SecondService.class);
//bindService启动
bindService(intent,connection, Service.BIND_AUTO_CREATE);
break;
case R.id.ServicestopSec_BTN:
unbindService(connection);
break;
default:
break;
}
}
}
和一般的Service最主要的不同是:
- 它里面的方法(onHandleIntent)能直接在里面进行耗时程序操作,不用开任何子线程;
- 它只能通过startService的方式启动
注意事项:要在manifests文件里注册该Service,注册时一般会报错只需在Service文件里添加该段代码:
public DemoService(){
super("DemoService");
}
package com.example.fpl.week3application;
import android.app.IntentService;
import android.content.Intent;
import android.support.annotation.Nullable;
import android.util.Log;
public class ThirdService extends IntentService {
private int num;
/**
* Creates an IntentService. Invoked by your subclass's constructor.
*
* @param name Used to name the worker thread, important only for debugging.
*/
public ThirdService(){
super("ThirdService");
}
public ThirdService(String name) {
super(name);
}
@Override
protected void onHandleIntent(@Nullable Intent intent) {
while (num<100){
Log.e("Second", String.valueOf(num));
num++;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}