Android——Service服务介绍

来源:互联网 发布:上知教育一个月多少钱 编辑:程序博客网 时间:2024/06/06 13:28
这一篇介绍一下Android的是四大组件中服务Service

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

Service 基本的。如下
一个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:48:44.939 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
 //绑定服务
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.所以去的数据都是不一样的。然后点击消毁。会返现
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
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
去他的博客看一下。详细