您的位置:首页 > 移动开发 > Android开发

Android——Service服务介绍

2017-06-25 14:24 309 查看
这一篇介绍一下Android的是四大组件中服务Service

Service组件也是可以执行程序的,它也是有自己的生命周期,创建,清单文件的配置,和Activity相似。可以理解成没有界面的Activity。

做背后工作的组件

Service 基本的。如下

1
import android.app.Service;
2
import android.content.Intent;
3
import android.os.IBinder;
4
import android.support.annotation.Nullable;
5
import android.util.Log;
6
7
/**
8
* Created by YacaToy on 2017/6/24.
9
*/
10
11
public class MyService extends Service {
12
private String TAG = "MyService";
13
//必须实现的方法
14
@Nullable
15
@Override
16
public IBinder onBind(Intent intent) {
17
Log.w(TAG, "onBind: ");
18
return null;
19
}
20
21
//被创建时回调的方法
22
@Override
23
public void onCreate() {
24
Log.w(TAG, "onCreate: ");
25
super.onCreate();
26
}
27
28
//被启动时回调的方法
29
@Override
30
public int onStartCommand(Intent intent, int flags, int startId) {
31
Log.w(TAG, "onStartCommand: ");
32
return super.onStartCommand(intent, flags, startId);
33
}
34
35
//被关闭之前回调的方法
36
@Override
37
public void onDestroy() {
38
Log.w(TAG, "onDestroy: ");
39
super.onDestroy();
40
}
41
}
42
一个Service创建必须要有onBind()方法。没有的话就会报错。这个看报错提示就应该知道,所以不要担心。然后就是Service三个基本回调方法。创建,启动还有就是销毁的时候的回调。开启一个Service和开启一个Activity差不多,只是多了一个关闭。开启staticService(intent),关闭stopService(intent)



1

//开启


2

Button bt_static = (Button)findViewById(R.id.bt_static);


3

bt_static.setOnClickListener(new View.OnClickListener() {


4

@Override


5

public void onClick(View v) {


6

startService(new Intent(MainActivity.this,MyService.class));


7

}


8

});


9

//关闭


10

Button bt_stop = (Button)findViewById(R.id.bt_stop);


11

bt_stop.setOnClickListener(new View.OnClickListener() {


12

@Override


13

public void onClick(View v) {


14

stopService(new Intent(MainActivity.this,MyService.class));


15

}


16

});


下面是点击效果
点击第一次开启

1
06-25 04:46:07.969 11691-11691/mycervicedata.example.yacatoy.myservicedata W/MyService: onCreate:
2
06-25 04:46:07.969 11691-11691/mycervicedata.example.yacatoy.myservicedata W/MyService: onStartCommand:
点击第二次开启



1

06-25 04:48:44.939 11691-11691/mycervicedata.example.yacatoy.myservicedata W/MyService: onStartCommand:


点击第三次开启

1
06-25 04:49:20.639 11691-11691/mycervicedata.example.yacatoy.myservicedata W/MyService: onStartCommand:
这里就可以看出。开启Service服务,onCreate之后调用一次。接下来来的开启都是onStartCommand。这样理解,已经创建了就只要启动了
点击关闭之后然后在开启,onCreate 又再次调用



1

06-25 04:52:24.339 11691-11691/mycervicedata.example.yacatoy.myservicedata W/MyService: onDestroy:


2

06-25 04:52:25.399 11691-11691/mycervicedata.example.yacatoy.myservicedata W/MyService: onCreate:


3

06-25 04:52:25.409 11691-11691/mycervicedata.example.yacatoy.myservicedata W/MyService: onStartCommand:


然后再来介绍绑定服务。绑定服务
当程序通过staticaService()和stopService()启动,关闭Service时,Serivce与访问者之间基本上不存在太多的关联,因此Series和访问者之间也无法进行通信
如果Service 和访问者之间需要进行方法调用或者交换,则应该使用bindService()和unbindService开启和绑定
下面就是代码

1
import android.app.Service;
2
import android.content.Intent;
3
import android.os.Binder;
4
import android.os.IBinder;
5
import android.support.annotation.Nullable;
6
import android.util.Log;
7
8
/**
9
* Created by YacaToy on 2017/6/24.
10
*/
11
12
public class MybindService extends Service {
13
14
import android.content.Intent;
15
import android.os.Binder;
16
import android.os.IBinder;
17
import android.support.annotation.Nullable;
18
import android.util.Log;
19
20
/**
21
* Created by YacaToy on 2017/6/24.
22
*/
23
24
public class MybindService extends Service {
25
  private String TAG = "MybindService";
26
 private int count;  //这个是用来获取的时数据,等下Activity去出这个数
27
 private boolean quit = false;
28
//定义onBinder方法返回的对象
29
 private MyBinder binder = new MyBinder();
30
//通过继承Binder来实现IBinder类
31
 public class MyBinder extends Binder{
32
  public int getCount(){
33
return count;
34
}
35
}
36
37
38
//必须实现的方法,绑定该Service时回调该方法
39
@Nullable
40
@Override
41
public IBinder onBind(Intent intent) {
42
  //返回的是  binder对象
43
  return binder;
44
}
45
46
 //
47
@Override
48
public void onCreate() {
49
  Log.w(TAG,"创建");
50
super.onCreate();
51
52
  new Thread(){
53
@Override
54
public void run() {
55
 while (!quit){
56
  try {
57
Thread.sleep(1000);
58
 } catch (InterruptedException e) {
59
e.printStackTrace();
60
 }
61
  count++;
62
}
63
64
}
65
}.start();
66
}
67
68
@Override
69
public int onStartCommand(Intent intent, int flags, int startId) {
70
  Log.w(TAG,"创建");
71
return super.onStartCommand(intent, flags, startId);
72
}
73
74
@Override
75
public void onDestroy() {
76
77
super.onDestroy();
78
  this.quit = true;
79
  Log.w(TAG,"销毁");
80
}
81
}
82
83
}
84
下面是实现

1

//绑定服务


2



3

private ServiceConnection conn = new ServiceConnection() {


4



5

  //当该Activity成功和Service连接的时候调用该方法


6

@Override


7

  public void onServiceConnected(ComponentName name, IBinder service) {


8

Log.w(TAG ,"onServiceConnected");


9

binder = (MybindService.MyBinder) service;


10

}


11



12

  //当该Activity成功和Service断开的时候调用该方法


13

  //类ServiceConnection中的onServiceDisconnected()方法在正常情况下是不被调用的,它的调用时机是当Service服务被异外销毁时,例如内存的资源不足时.


14

@Override


15

  public void onServiceDisconnected(ComponentName name) {


16

Toast.makeText(getApplicationContext(),"onServiceDisconnected",Toast.LENGTH_SHORT).show();


17

System.out.println("ServiceDisconnected");


18

Log.w(TAG ,"onServiceDisconnected");


19

}


20

};


21

  //绑定


22

  Button Bstatic = (Button) findViewById(R.id.bt_Bstatic);


23

  Bstatic.setOnClickListener(new View.OnClickListener() {


24

@Override


25

public void onClick(View v) {


26

 bindService(new Intent(MainActivity.this,MybindService.class),conn, Service.BIND_AUTO_CREATE);


27

}


28

});


29

  //解除


30

  Button Bstop = (Button) findViewById(R.id.bt_Bstop);


31

  Bstop.setOnClickListener(new View.OnClickListener() {


32

@Override


33

public void onClick(View v) {


34

 unbindService(conn);


35

}


36

});


37

  //获取数据


38

  Button bt_gethhhh = (Button) findViewById(R.id.bt_gethhhh);


39

  bt_gethhhh.setOnClickListener(new View.OnClickListener() {


40

@Override


41

public void onClick(View v) {


42

 Log.w(TAG ,binder.getCount()+"");


43



44

}


45

});


下面看点击效果

1
06-25 05:41:46.349 11691-11691/mycervicedata.example.yacatoy.myservicedata W/MybindService: 创建//第一次点击 开启 
2
06-25 05:41:46.359 11691-11691/mycervicedata.example.yacatoy.myservicedata W/MainActivity: onServiceConnected
3
06-25 05:41:48.759 11691-11691/mycervicedata.example.yacatoy.myservicedata W/MainActivity: 2//第一次点击获取  
4
06-25 05:41:49.979 11691-11691/mycervicedata.example.yacatoy.myservicedata W/MainActivity: 3//第二次点击获取  
5
06-25 05:41:52.039 11691-11691/mycervicedata.example.yacatoy.myservicedata W/MainActivity: 5//第三次点击获取  
6
06-25 05:41:56.359 11691-11691/mycervicedata.example.yacatoy.myservicedata W/MybindService: 销毁  //第一次点击销毁
创建,链接之后就不会再创建,再链接。。服务没二分之一秒的时候就会+1.所以去的数据都是不一样的。然后点击消毁。会返现onServiceDisconnected并没有响应。这是因为类ServiceConnection中的onServiceDisconnected()方法在正常情况下是不被调用的,它的调用时机是当Service服务被异外销毁时,例如内存的资源不足时.然后如果服务以及销毁的时候还去点击销毁的话,会出现异常,这里要做个容错处理。下面我添个工具类。判断服务是是否存在。



1

import java.util.List;


2



3

import android.app.ActivityManager;


4

import android.app.ActivityManager.RunningServiceInfo;


5

import android.content.Context;


6



7

public class ServiceUtil {


8



9

 /**


10

  * 


11

  * @param context 上下文


12

  * @param serviceName  需要判断的服务进程


13

  * @return  true 正在运行  否则 没有运行


14

*/


15

 public static boolean isRunning(Context context,String serviceName){


16

  //获取ActivityManager管理这对象,可以获取当前手机正在运行的所有服务


17

  ActivityManager mAM = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);


18

  //获取手机中正在运行的服务集合(多个服务)


19

  List<RunningServiceInfo> runningServices = mAM.getRunningServices(100);


20

  for(RunningServiceInfo runingService : runningServices){


21

if(serviceName.equals(runingService.service.getClassName())){


22

 return true;


23

}


24

}


25

  


26

  return false;


27

  


28

}


29

}


30



下面介绍一下IntentService
IntentService是Service的子类,因此它不是普通的Service,它比普通的Service增加了一些功能
首先看Service本省存在的问题
Service不会专门启动一个单独的线程,Service与它所在应用位于同一个进程中
Service不是一条新的线程,因此不应该在Service中直接处理耗时操作
而IntentService就解决了这个问题
IntentService会创建单独的worker线程来处理所所有的Intent请求
IntentService会创建单独的worker线程来处理onHandleIntent()方法实现的代码。因此开发者无须处理线程问题
当所有请求处理完成之后,IntentService会自动停止。因此开发者无须调用stopSelf()方法停止Service
为Service的onBind()方法提供默认实现,默认实现的onBind()方法返回null
为Service的onStartCommand()方法提供了默认实现,该实现会将Intent添加到对列当中
下面就是IntentService代码

1
import android.app.IntentService;
2
import android.content.Intent;
3
import android.support.annotation.Nullable;
4
import android.util.Log;
5
6
/**
7
* Created by YacaToy on 2017/6/25.
8
*/
9
10
public class MyIntentSeriver extends IntentService {
11
 private final String Tag = "MyIntentSeriver";
12
13
//@Override
14
//public void onCreate() {
15
//super.onCreate();
16
//  Log.w(Tag,"onHandleIntent");
17
//}
18
//这个不带参数的构造方法一定要实现
19
 public MyIntentSeriver(){
20
  super("MyIntentSeriver");
21
}
22
23
 /**
24
  * Creates an IntentService.  Invoked by your subclass's constructor.
25
  *
26
  * @param name Used to name the worker thread, important only for debugging.
27
*/
28
 public MyIntentSeriver(String name) {
29
30
  super(name);
31
  Log.w(Tag,"onHandleIntent");
32
}
33
34
@Override
35
 protected void onHandleIntent(@Nullable Intent intent) {
36
37
  Log.w(Tag,"onHandleIntent");
38
39
}
40
}
41
点击事件



1

Button intentsService = (Button) findViewById(R.id.bt_IntentService);


2

  intentsService.setOnClickListener(new View.OnClickListener() {


3

@Override


4

public void onClick(View v) {


5

 Log.w(TAG ,"intentsService");


6

 startService(new Intent(MainActivity.this,MyIntentSeriver.class));


7

}


8

});


也就是这么简单,在onHandleIntent()中实现耗时操作

这里就简单做个Service做一个介绍。慢慢来,基础一定要牢固

有问题一起讨论。新手之间多交流

关于服务的生命周期:http://blog.csdn.net/iispring/article/details/48169339
去他的博客看一下。详细
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: