Android的Service的创建与使用

时间:2022-03-27 04:50:04

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服务&lpar;Service&rpar;研究

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

  2. Android中Service 使用详解(LocalService &plus; 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守护 &amp&semi;&amp&semi; 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. ArcGIS图层介绍

    什么是图层 图层是用来在 ArcGIS 产品套件中显示地理数据集的机制.每个图层代表一种数据集(可以是地图服务.图形或是矢量数据),并指定该数据集是如何描绘使用一组属性的. 包含一个地图控件的每个应用 ...

  2. SharePoint2010新特性:InfoPath定义创建列表的界面

    在SharePoint2007的时候,自定义的列表可以使用CAML修改其展示页面,但是对于创建列表的页面,不容易自定义.现在在SharePoint2010中,增强了InfoPath Form Serv ...

  3. css 选择器优先级的计算过程

    以下转自互联网 下面看看官方对选择器的定义:一个选择器的优先级由四个数字a,b,c,d确定.当比较两个选择器时,先比较a,a值大的优先级高,如果a相等则比较b,b值大的优先级高,以此类推.因此,无论b ...

  4. &lbrack;转&rsqb; PostgreSQL学习手册&lpar;数据表&rpar;

    from: http://www.cnblogs.com/stephen-liu74/archive/2012/04/23/2290803.html 一.表的定义: 对于任何一种关系型数据库而言,表都 ...

  5. meta标签使360浏览器默认极速模式

    在head标签中添加一行代码: <html> <head> <meta name=”renderer” content=”webkit|ie-comp|ie-stand” ...

  6. js中的arguments用法

    //arguments对象并不是一个数组,但是访问单个参数的方式与访问数组元素的方式相同 function show(){ console.log(arguments); //arguments.pu ...

  7. 归并排序&lpar;Merging Sort&rpar;

    body, table{font-family: 微软雅黑; font-size: 13.5pt} table{border-collapse: collapse; border: solid gra ...

  8. django Models cross file ---- 跨app引用文件

    一.django 的跨app引用文件是通过import 来实现的,但是import 的路径查找和标准的import 不太一样,django里面更加方便了 二.例子 1.project 结构说明 [ji ...

  9. nmcli日常用法

    一.nmcli日常用法nmcli dev status //查看系统现有网络设备的连接状态nmcli conn show //查看已有连接nmcli conn delete UUID1 UUID2 U ...

  10. 初尝微信小程序2-基本框架

    基本框架: .wxml :页面骨架 .wxss :页面样式 .js :页面逻辑    描述一些行为 .json :页面配置 创建一个小程序之后,app.js,app.json,app.wxss是必须的 ...