什么是服务


服务这个概念最开始是 windows中 使用到的 ,
后来 android 出现的时候, 谷歌工程师, 也 模仿去 弄出了 服务.
服务: 实际上就是长期可以在后台运行的, 没有界面的, 运行在 当前的进程空间中的


为什么要有服务


(开始可能会以为服务很鸡肋Activity可以做到服务可以做到的一切,但是不是的)
从安卓中各种进程说起
安卓对进程的解释是
Android 系统会尽可能的保持应用程序的进程 一致存在, 即使在应用退出了之后 也仍然 这样… 但是 如果发现内存不够用了,
要去启动 新的进程时, 那么会按照进程的优先级顺序 去 杀死 某些 老的进程 .

进程: 就是一块独立的内存空间,用来运行 程序的。

所以在开始程序退出以后,该程序的进程还会继续存在一段时间,知道内存不够被释放位置。

介绍一下安卓中的几种进程

1.前台进程:

Foreground process ,  可以与用户直接进行交互的 , 就是前台进程 (可以获得焦点的)

2.可视进程:

Visble process, 可以看到, 但是不能直接与用户进行交互

3.服务进程:

Servise process, 进程中 运行了一个服务.  在运行着

4.后台进程:

Background process, 例如, 一个activity 现在不可见了, 但是 在后台运行

5.空进程:

Empty process一个进程中,没有服务, 也没有 activity, 整个 应用程序已经退出

正是这些进程优先级的不同,才体现出Servise的重要性;

重要优先级:  前台进程> 可视进程>服务进程> 后台进程> 空进程

首先说一下Activity如果在它中创建一个进程,当Activity关闭的时候进程会默认变为空进程。但是服务进程不是

服务可以在长期后台运行的, 是与 当前的 启动 服务的acitvity 是没有关系的.

还有在服务进程关闭后当内存充足的时候是可以重启的但是空进程不行。

那么来写一个服务进程吧


首先定义一个StartServise的类
然后让他继承 Servise.app;

public class StartServise extends Service {
   //private String TAG = ww;
     Boolean key ;
//继承父类的
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
//为了清楚的显示服务我们在创建的时候提示一下
    @Override
    public void onCreate() {
        super.onCreate();
        Log.d("TAG","服务创建了");
        key =true;
        while(key == true){
        //创建一个线程 做一个消耗时间的事
            new Thread(){
                @Override
                public void run() {
                    Log.d("TAG","服务正在运行");
                 SystemClock.sleep(200);
                    Log.d("TAG",Thread.currentThread().getName());
                   key = false;
                }


            }.start();

        }
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return super.onStartCommand(intent, flags, startId);

    }

    @Override
    //改变Key的值来关闭进程
    public void onDestroy() {
        key = false;
        super.onDestroy();
        Log.d("TAG","服务销毁了");
    }


}

设置两个按钮来开启服务关闭服务


<Button
        android:onClick="start"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="开启服务"/>
    <Button
    android:onClick="stop"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="关闭服务"/>

声明服务

<service android:name=".StartServise"></service>

最后在Acticvity中使用

public void start(View view){

       Intent intent =new Intent();
       intent.setClass(this,StartServise.class);
       startService(intent);
   }
    public void stop(View view){
        Intent intent = new Intent();
        intent.setClass(this,StartServise.class);
        stopService(intent);

    }