Service介绍

Service是Android四大组件中与Activity最为相似的组件,它们都代表可执行的程序,
区别是:Service一直在后台运行,没有用户界面。
使用service要向Activity一样,要在AndroidManifest.xml文件中进行配置。

Service也具有自己的生命周期,下面通过一个简单的程序进行展示

public class FirstService extends Service {
@Nullable
@Override
//想要使用Service必须实现这个方法,该方法返回一个IBinder对象
//应用程序使用这个对象与Service组件进行通信
public IBinder onBind(Intent intent) {
return null;
} //Service被创建的时候回调onCreate方法
public void onCreate(){
super.onCreate();
System.out.println("Service is Created");
} //Service被启动的时候回调onStartCommand方法
public int onStartCommand(Intent intent, int flags, int startId){
System.out.println("Service is Started");
return START_STICKY;
} //Service被销毁的时候回调onDestroy方法
public void onDestroy(){
super.onDestroy();
System.out.println("Service is Destroyed");
}
}

想要使用Service必须在AndroidManifest.xml文件中进行配置,如下

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

Service的启动

接下来使用一个例子启动之前的那个Service的使用,这个程序布局只有两个按钮,这里省略,代码如下:

public class MainActivity extends AppCompatActivity {
Button start,stop; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
start = (Button) findViewById(R.id.start);
stop = (Button) findViewById(R.id.stop);
final Intent intent = new Intent(this , FirstService.class);
start.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//启动Service
startService(intent);
}
});
stop.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//停止Service
stopService(intent);
}
});
}
}

可以看到,调用startService()方法与stopService()方法就可以启动、关闭Service

Service的绑定

接下来的一个实例是绑定本地Service并进行通信
界面的代码如下:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
> <Button
android:id="@+id/bind"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="绑定SERVICE"/> <Button
android:id="@+id/unbind"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="解除绑定SERVICE"/> <Button
android:id="@+id/getServiceStatus"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="获取SERVICE状态"/>
</LinearLayout>

可以看到界面很简单,只是三个按钮,分别的功能是绑定Service,
解除绑定Service,获取Service状态

Service类的代码如下:

public class BindService extends Service{
private int count;
private boolean quit;
private MyBinder binder = new MyBinder();
//用MyBinder继承Binder来实现IBinder类
public class MyBinder extends Binder
{
public int getCount()
{
return count;
}
}
@Override
public IBinder onBind(Intent intent) {
System.out.println("Service is Binded");
return binder;
} public void onCreate(){
super.onCreate();
System.out.println("Service is Created");
//Service被创建后,启动一条线程,动态修改count的值
new Thread()
{
public void run(){
while (!quit){
try{
Thread.sleep(1000);
}
catch (InterruptedException e){
}
count++;
}
}
}.start();
} public boolean onUnbind(Intent intent)
{
System.out.println("Service isUnbinded");
return true;
}
public void onDestroy(){
super.onDestroy();
this.quit = true;
System.out.println("Service is Destroyed");
}
}

然后是Activity的代码:

public class MainActivity extends AppCompatActivity {
Button bind, unbind, getServiceStatus;
BindService.MyBinder binder; private ServiceConnection conn = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
System.out.println("--Service Connected--");
binder = (BindService.MyBinder) service;
} @Override
public void onServiceDisconnected(ComponentName name) {
System.out.println("--Service Disconnected--");
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bind = (Button) findViewById(R.id.bind);
unbind = (Button) findViewById(R.id.unbind);
getServiceStatus = (Button) findViewById(R.id.getServiceStatus);
//创建启动Service的Intent
final Intent intent = new Intent(this,BindService.class);
//按钮bind的监听事件,绑定Service
bind.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
bindService(intent, conn, Service.BIND_AUTO_CREATE);
}
});
//按钮unbind的监听事件,解除绑定Service
unbind.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
unbindService(conn);
}
});
//按钮getServiceStatus的监听事件,在Service与Activity之间传递数据
getServiceStatus.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(MainActivity.this, "Service的count值为:" +
binder.getCount() ,Toast.LENGTH_SHORT).show();
}
});
}
}

在Activity绑定了Service后,通过Service里的getCount方法,得到了Service的count值。
运行程序之后,点击绑定按钮,logcat里依次输出了

Service is Created、Service is Binded、Service Connected
再点击获取状态按钮,程序使用Toast显示出了随机数count

最后点击解除绑定按钮,logcat里依次输出了
Service is Unbinded、Service is Destroyed

两种运行Service的方式的总结

以上就是两种运行Service的方式,分别是startService()方法和bindService()方法
使用startService()方法启动Service时,访问者与Service之间没有关联,访问者退出后Service也会继续运行,
使用bindService()方法启动Service是,访问者与Service绑定在一起,访问者退出后,Service就会终止。

Service的生命周期补充

使用startService时:onCreate()→onStartCommand()→Service运行中→onDestroy()→Service被关闭
使用bindService时:onCreate()→onBind()→绑定了Service→onUnbind()→onDestroy()→Service被关闭

接下来是一种特殊情况,Service先被startService()方法启动,再被bindService方法绑定,又被解除,又再被绑定
这时所触发的生命周期方法如下:onCreate(),onStartCommand(),onBind(),onUnBind,onRebind()
可以看到这种情况下回调了onRebind()方法。并且这种情况下并没有回调过onDestroy()方法,因为
这个时候Service已经被Activity的startService方法启动过了,所以在解除绑定时Service不会终止。

Android的Service的创建与使用的更多相关文章

  1. Android服务(Service)研究

    Service是android四大组件之一,没有用户界面,一直在后台运行. 为什么使用Service启动新线程执行耗时任务,而不直接在Activity中启动一个子线程处理? 1.Activity会被用 ...

  2. Android中Service 使用详解(LocalService + RemoteService)

    Service 简介: Service分为本地服务(LocalService)和远程服务(RemoteService): 1.本地服务依附在主进程上而不是独立的进程,这样在一定程度上节约了资源,另外L ...

  3. Android在Service中显示Dialog

    在Service中弹出一个Dialog对话框 第1步:在应用的AndroidManifest.xml中需要添加权限.没有无法显示. <uses-permission android:name=& ...

  4. Android中Service的使用

    我个人的理解是:我们平时使用的android系统的app的后台应用,就是这个原理 可以利用Service实现程序在后台运行,依照这个原理,可以通过Service来实现关键代码的运行与实现. <一 ...

  5. 【Android 】Service 全面总结

    1.Service的种类 按运行地点分类: 类别 区别  优点 缺点   应用 本地服务(Local) 该服务依附在主进程上,  服务依附在主进程上而不是独立的进程,这样在一定程度上节约了资源,另外L ...

  6. Android 保持Service不被Kill掉的方法--双Service守护 && Android实现双进程守护

    本文分为两个部分,第一部分为双Service守护,第二部分为双进程守护 第一部分: 一.Service简介:Java.lang.Object ↳Android.content.Context  ↳an ...

  7. Android 中 Service AIDL使用

         1.创建两个项目创建两个.aidl文件 2.在传递值的类里面创建Service并且返回接口: 服务返回值onBind public IBinder onBind(Intent intent) ...

  8. Android中Service的使用详解和注意点(LocalService)

    Android中Service的使用详解和注意点(LocalService) 原文地址 开始,先稍稍讲一点android中Service的概念和用途吧~ Service分为本地服务(LocalServ ...

  9. Android之Service

    1.自定义Service类 package com.example.mars_2000_service; import android.app.Service; import android.cont ...

随机推荐

  1. EHCache:Eelment刷新后,timeToLiveSeconds失效了?

    个人以为只要设定了timeToLiveSeconds,中间过程不管有没有访问,只要LiveSeconds时间到了,缓存就会失效.但是开发时发现并非如此,经过一番折腾,最终发现自己的理解是正确的,还是使 ...

  2. Mysql --数据的增删改

    插入数据 INSERT 更新数据 UPDATE 删除数据 DELETE 一. 在mysql管理软件中,可以通过SQL语句中的DML语言来实现数据的操作,包括 1.使用insert实现数据的插入 2.u ...

  3. 【原创】大叔经验分享(21)yarn中查看每个应用实时占用的内存和cpu资源

    在yarn中的application详情页面 http://resourcemanager/cluster/app/$applicationId 或者通过application命令 yarn appl ...

  4. python回归分析五部曲

    Python回归分析五部曲(一)—简单线性回归 https://blog.csdn.net/jacky_zhuyuanlu/article/details/78878405?ref=myread Py ...

  5. Python-选择器Xpath,Css,Re

    正则表达式(特殊字符) ^ 开头 '^b.*'----以b开头的任意字符 $ 结尾 '^b.*3$'----以b开头,3结尾的任意字符 * 任意长度(次数),≥0 ? 非贪婪模式,非贪婪模式尽可能少的 ...

  6. Codeforces 809E Surprise me! [莫比乌斯反演]

    洛谷 Codeforces 非常套路的一道题,很适合我在陷入低谷时提升信心-- 思路 显然我们需要大力推式子. 设\(p_{a_i}=i\),则有 \[ \begin{align*} n(n-1)an ...

  7. 初学python之路-day05

    每天一总结,今天学习的是数据类型及其使用方法与可变与不可变类型. 今天了解的数据类型有整型int,浮点型float,字符串类型str,布尔型bool,列表list. 整型int与浮点型float都属于 ...

  8. EurekaClient项目启动报错Invocation of destroy method failed on bean with name 'scopedTarget.eurekaClient': org.springframework.beans.factory.BeanCreationNotAllowedException: Error creating bean with name 'e

    Disconnected from the target VM, address: '127.0.0.1:51233', transport: 'socket' Eureka Client的使用 使用 ...

  9. Intellij Idea调试java文件时 怎么跳过class文件?

    Intellij Idea调试时 java文件时,遇到class文件时它也会反编译该文件,并跳入该class文件内一条条语句执行.这让我烦透了,怎么跳过class文件,继续调试啊? SETTINGS- ...

  10. python设计模式---创建型之工厂模式

    # coding = utf-8 from abc import ABCMeta, abstractmethod # 简单工厂模式 class Animal(metaclass=ABCMeta): @ ...