Android Service详解及示例代码
作者:chino 发布时间:2021-12-24 05:44:17
Android Service 详细介绍:
1、Service的概念
2、Service的生命周期
3、实例:控制音乐播放的Service
一、Service的概念
Service是Android程序中四大基础组件之一,它和Activity一样都是Context的子类,只不过它没有UI界面,是在后台运行的组件。
二、Service的生命周期
Service对象不能自己启动,需要通过某个Activity、Service或者其他Context对象来启动。启动的方法有两种,Context.startService和Context.bindService()。两种方式的生命周期是不同的,具体如下所示。
Context.startService方式的生命周期:
启动时,startService –> onCreate() –> onStart()
停止时,stopService –> onDestroy()
Context.bindService方式的生命周期:
绑定时,bindService -> onCreate() –> onBind()
解绑定时,unbindService –>onUnbind() –> onDestory()
三、实例:控制音乐播放的Service
下面我们用一个可以控制在后台播放音乐的例子来演示刚才所学知识,同学们可以通过该例子可以明显看到通过绑定方式运行的Service在绑定对象被销毁后也被销毁了。
下面把代码分享如下:
1、建立一个新项目名字叫 Lesson14_HelloService,Activity起名叫MainHelloService.java
2、res/layout/main.xml中代码写成
< ?xml version="1.0" encoding="utf-8"?>
<linearlayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent">
<textview android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="音乐播放服务" android:textsize="25sp" android:layout_margintop="10dp">
<button android:text="开启音乐播放服务" android:textsize="20sp" android:id="@+id/Button01" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_margintop="10dp">
</button>
<button android:text="停止音乐播放服务" android:textsize="20sp" android:id="@+id/Button02" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_margintop="10dp">
</button>
<button android:text="绑定音乐播放服务" android:textsize="20sp" android:id="@+id/Button03" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_margintop="10dp">
</button>
<button android:text="解绑定音乐播放服务" android:textsize="20sp" android:id="@+id/Button04" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_margintop="10dp">
</button>
</textview></linearlayout>
3、在res目录中建立一个raw目录,并把一个音乐文件babayetu.mp3拷贝进来3、在Activity的同目录新建一个service文件
MusicService.java
package android.basic.lesson14;
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;
public class MusicService extends Service {
//为日志工具设置标签
String tag ="MusicService";
//定义音乐播放器变量
MediaPlayer mPlayer;
//其他对象通过bindService方法通知该Service时该方法会被调用
@Override
public IBinder onBind(Intent intent) {
Toast.makeText(this,"MusicService onBind()",Toast.LENGTH_SHORT).show();
Log.i(tag, "MusicService onBind()");
mPlayer.start();
return null;
}
//其他对象通过unbindService方法通知该Service时该方法会被调用
@Override
public boolean onUnbind(Intent intent){
Toast.makeText(this, "MusicService onUnbind()", Toast.LENGTH_SHORT).show();
Log.i(tag, "MusicService onUnbind()");
mPlayer.stop();
return false;
}
//该服务不存在需要被创建时被调用,不管startService()还是bindService()都会在启动时调用该方法
@Override
public void onCreate(){
Toast.makeText(this, "MusicService onCreate()", Toast.LENGTH_SHORT).show();
//创建一个音乐播放器对象
mPlayer=MediaPlayer.create(getApplicationContext(), R.raw.babayetu);
//设置可以重复播放
mPlayer.setLooping(true);
Log.i(tag, "MusicService onCreate()");
}
//用startService方法调用该服务时,在onCreate()方法调用之后,会调用改方法
@Override
public void onStart(Intent intent,int startid){
Toast.makeText(this,"MusicService onStart",Toast.LENGTH_SHORT).show();
Log.i(tag, "MusicService onStart()");
mPlayer.start();
}
//该服务被销毁时调用该方法
@Override
public void onDestroy(){
Toast.makeText(this, "MusicService onDestroy()", Toast.LENGTH_SHORT).show();
mPlayer.stop();
Log.i(tag, "MusicService onDestroy()");
}
}
4、MainHelloService.java中的代码:
package android.basic.lesson14;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class MainHelloService extends Activity {
//为日志工具设置标签
String tag = "MusicService";
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//输出Toast消息和日志记录
Toast.makeText(MainHelloService.this, "MainHelloService onCreate", Toast.LENGTH_SHORT).show();
Log.i(tag, "MainHelloService onCreate");
//定义组件对象
Button b1= (Button)findViewById(R.id.Button01);
Button b2= (Button)findViewById(R.id.Button02);
Button b3= (Button)findViewById(R.id.Button03);
Button b4= (Button)findViewById(R.id.Button04);
//定义服务链接对象
final ServiceConnection conn = new ServiceConnection(){
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
Toast.makeText(MainHelloService.this, "ServiceConnection onServiceConnected", Toast.LENGTH_SHORT).show();
Log.i(tag, "ServiceConnection onServiceConnected");
}
@Override
public void onServiceDisconnected(ComponentName name) {
Toast.makeText(MainHelloService.this, "ServiceConnection onServiceDisconnected", Toast.LENGTH_SHORT).show();
Log.i(tag, "ServiceConnection onServiceDisconnected");
}};
//定义点击 *
OnClickListener ocl= new OnClickListener(){
@Override
public void onClick(View v) {
//显示指定intent所指的对象是个Service
Intent intent = new Intent(MainHelloService.this,android.basic.lesson14.MusicService.class);
switch(v.getId()){
case R.id.Button01:
//开始服务
startService(intent);
break;
case R.id.Button02:
//停止服务
stopService(intent);
break;
case R.id.Button03:
//绑定服务
bindService(intent,conn,Context.BIND_AUTO_CREATE);
break;
case R.id.Button04:
//解除绑定
unbindService(conn);
break;
}
}
};
//绑定点击 *
b1.setOnClickListener(ocl);
b2.setOnClickListener(ocl);
b3.setOnClickListener(ocl);
b4.setOnClickListener(ocl);
}
@Override
public void onDestroy(){
super.onDestroy();
Toast.makeText(MainHelloService.this, "MainHelloService onDestroy", Toast.LENGTH_SHORT).show();
Log.i(tag, "MainHelloService onDestroy");
}
}


猜你喜欢
- 一、单文件压缩 场景,文件可能比较大,需要压缩传输,比如上传和下载/// <summary&g
- 一.字符串函数1. 求字符串长度的strlensize_t strlen ( const char * str );字符串以 ‘\0'
- 在spring的注解 @RequestMapping 之下可以直接获取 HttpServletRequest 来获得诸如request he
- 一、使用QueryByExampleExecutor1. 继承MongoRepositorypublic interface Student
- SpringBoot运行Test时报错运行Test时的报错信息:SpringBoot Unable to find a @SpringBoo
- 一、Shader基础知识1.1、什么是Shader在讲什么是Shader之前我们先看看下面两段代码 这两段代码实现的功能都是提取
- 线程组线程组可以批量管理线程和线程组对象。一级关联例子如下,建立一级关联。public class MyThread43 implement
- 本文实例讲述了Android控件之CheckBox、RadioButton用法。分享给大家供大家参考。具体如下:CheckBox和Radio
- 准备:(1) IDEA 2021(2)Java 1.8(3)数据库 MySQL 5.7 (SQLyog 或 Navicat)在 MySQL
- 一、内部类介绍1.定义:一个类内部又嵌套了一个类,被嵌套的类就是内部类(inner class),嵌套其他类的称为外部类(outer cla
- 先给大家展示下效果图,感觉不错请参考实例代码。实现思路在flutter中,如果想实现上面的页面切换效果,必然会想到pageView。page
- 本文实例讲述了Java面向对象程序设计:类的定义,静态变量,成员变量,构造函数,封装与私有,this概念与用法。分享给大家供大家参考,具体如
- MS的CMD命令行是一种重要的操作界面,一些在C#中不那么方便完成的功能,在CMD中几个简单的命令或许就可以轻松搞定,如果能在C#中能完成C
- Java集合框架集合概念:对象的容器,定义了对多个对象进行操作的常用方法。可实现数组的功能。集合和数组的区别:数组长度固定,集合长度不固定数
- 默认情况下,插件 spring-boot-maven-plugin 会把整个项目打包成一个可运行的Jar包(即所谓的Flat Jar),导致
- 本文实例为大家分享了android TextView跑马灯效果的具体代码,供大家参考,具体内容如下一、要点设置四个属性android:sin
- 概述从今天开始, 小白我将带大家开启 Jave 数据结构 & 算法的新篇章.栈栈 (Stack) 是一种运算受限的线性表, 遵循先进
- 一、效果图二、代码public class TextSubView extends TextView {private TextPaint
- 前言在实现红黑树之前,我们先来了解一下符号表。符号表的描述借鉴了Algorithms第四版,详情在:https://algs4.cs.pri
- 前言更新都写完了,但是要更新文件要怎么操作呢?连接服务器然后上传上去,修改下xml的版本号当然也是可以的,但是还是没有写个程序使用起来方便,