Android学习(十四) Service组件
一、定义
运行在后台,没有页面,不可见。优先级高于Activity,当系统内存不足时,会先释放一些Activity。注意,Service同样是运行在主线程中,不能做一些耗时操作。如果一定要做一些耗时的操作,启动一个新的线程,在新的线程中来处理。
二、用途:
播放音乐,记录地理位置的改变,监听某些动作。
三、Sevice分类:
1、本地服务(Local Service):是一种本地服务,一般用于应用程序内部,通过startService方法启动,通过stopService,stopSelf,stopSelfResult方法停止。另一种服务器启动方式:bindService,unbindService。
2、远程服务(Remote Service):Android内部多个应用程序之间。定义Ibinder接口,暴露数据。
四、Service声明周期:

Service声明周期分为两种情况:
1、通过startService方式启动的服务,为左边方式,onCreate-->onStartCommand-->service Running -->stopXXZXOnDestroy;
特点:启动后服务和启动源没有任何联系,无法得到服务对象。
2、通过bind方式启动服务,为右边所示方式,OnCreate--> onBind--> Clients are bound to service --> onUnbind -->onDestroy;
特点:通过Ibinder接口实例,返回一个ServiceConnection对象给启动源。通过ServiceConnection对象的相关方法可以得到Service对象。
示例:
1、start方式声明周期示例
AndroidManifest.xml,首先在配置文件中注册服务,添加服务名称
<service android:name="MyService1"></service>
MyService1.java,创建服务类,继承Service抽象方法,实现onCreate,onStartCommand,onDestroy,onBind方法,
package com.example.servicedemo; import android.app.Service;
import android.content.Intent;
import android.os.IBinder; public class MyService1 extends Service{
@Override //服务创建方法,只启动一次
public void onCreate() {
System.out.println("onCreate");
super.onCreate();
} @Override //服务启动方法
public int onStartCommand(Intent intent, int flags, int startId) {
System.out.println("StartCommand");
return super.onStartCommand(intent, flags, startId);
} @Override //服务销毁方法
public void onDestroy() {
System.out.println("Destroy");
super.onDestroy();
} @Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
} }
main.xml,页面中添加两个按钮startService和stopService。
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"> <TextView
android:id="@+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Start:" /> <Button
android:onClick="doClick"
android:id="@+id/btn_start"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="StartService" /> <Button
android:onClick="doClick"
android:id="@+id/btn_stop"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="StopService" /> </LinearLayout>
main.java,后台代码
package com.example.servicedemo; import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View; public class MainActivity extends Activity {
Intent intent; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
} public void doClick(View v) {
switch (v.getId()) {
case R.id.btn_start:
//创建intent对象
intent = new Intent(MainActivity.this,MyService1.class);
//启动一个服务
startService(intent);
break;
case R.id.btn_stop:
//结束一个服务
stopService(intent);
break;
}
} }
onCreate方法只是第一次被调用,只调用一次,除非Service对象被卸载了,onStartCommand点击一次就调用一次,可以重复点击,onDestory方法销毁方法。
2、bind方式绑定
AndroidManifest.xml,注册服务器对象
<service android:name="com.example.servicedemo2.MyBindService"></service>
main.xml,在页面上放置两个按钮,启动和卸载
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"> <TextView
android:id="@+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="BindService:" /> <Button
android:onClick="doClick"
android:id="@+id/btn_bindstart"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="BindService" /> <Button
android:onClick="doClick"
android:id="@+id/btn_bindstop"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="UnBindService" />
</LinearLayout>
MyBindService.java,创建基于Bind绑定的服务类
package com.example.servicedemo2; import android.app.Service;
import android.content.Intent;
import android.os.IBinder; public class MyBindService extends Service{ @Override //绑定方法
public IBinder onBind(Intent intent) {
System.out.println("Bind_onBind");
return null;
} @Override //创建时调用
public void onCreate() {
System.out.println("Bind_onCreate");
super.onCreate();
} @Override //销毁时调用
public void onDestroy() {
System.out.println("Bind_onDestroy");
super.onDestroy();
} @Override //解绑时调用
public boolean onUnbind(Intent intent) {
System.out.println("Bind_onUnbind");
return super.onUnbind(intent);
} }
main.java,后台Activity代码
package com.example.servicedemo2; import android.app.Activity;
import android.app.Service;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.view.View; public class MainActivity extends Activity { private ServiceConnection conn = new ServiceConnection() { @Override
public void onServiceDisconnected(ComponentName name) { } @Override
public void onServiceConnected(ComponentName name, IBinder service) { }
}; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
} public void doClick(View v){
switch(v.getId()){
case R.id.btn_bindstart:
Intent intent = new Intent(MainActivity.this, MyBindService.class);
bindService(intent, conn,Service.BIND_AUTO_CREATE);
break;
case R.id.btn_bindstop:
unbindService(conn);
break;
}
}
}
启动和结束按钮不能被多次点击,必须启动后才能释放,1对1,启动服务后,退出应用程序,也会报错,必须先释放绑定的服务源对象
3、activity调用service中的方法
main.xml 主页面,定义六个按钮,bind和unbind为绑定service,paly,pause,next,prev为调用service中的四个方法
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"> <TextView
android:id="@+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="BindService:" /> <Button
android:onClick="doClick"
android:id="@+id/btn_bindstart"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="BindService" /> <Button
android:onClick="doClick"
android:id="@+id/btn_bindstop"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="UnBindService" /> <TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="播放器服务" /> <Button
android:onClick="musicClick"
android:id="@+id/btnPlay"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="播放" /> <Button
android:onClick="musicClick"
android:id="@+id/btnPause"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="暂停" /> <Button
android:onClick="musicClick"
android:id="@+id/btnNext"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="下一首" /> <Button
android:onClick="musicClick"
android:id="@+id/btnPrev"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="上一首" /> </LinearLayout>
mybindservice.java 服务方法
package com.example.servicedemo2; import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder; public class MyBindService extends Service{ //继承抽象类Binder
public class MyBinder extends Binder{ //定义获取绑定服务的方法
public MyBindService getService(){
return MyBindService.this;
}
} @Override //绑定方法
public IBinder onBind(Intent intent) {
System.out.println("Bind_onBind");
return new MyBinder();
} @Override //创建时调用
public void onCreate() {
System.out.println("Bind_onCreate");
super.onCreate();
} @Override //销毁时调用
public void onDestroy() {
System.out.println("Bind_onDestroy");
super.onDestroy();
} @Override //解绑时调用
public boolean onUnbind(Intent intent) {
System.out.println("Bind_onUnbind");
return super.onUnbind(intent);
} //添加自定义的方法 //播放方法
public void play(){
System.out.println("Play");
} //暂停方法
public void pause(){
System.out.println("Pause");
} //下一首
public void next(){
System.out.println("Next");
} //上一首
public void prev(){
System.out.println("Prev");
}
}
main.java 后台代码
package com.example.servicedemo2; import com.example.servicedemo2.MyBindService.MyBinder; import android.app.Activity;
import android.app.Service;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.view.View; public class MainActivity extends Activity { MyBinder b; private ServiceConnection conn = new ServiceConnection() { @Override //当启动源和Service的连接意外丢失的时候会调用这个方法
//当Service崩溃了,或者被强行杀死了,如果接触了绑定就不会被调用
public void onServiceDisconnected(ComponentName name) { } //activity和service之间的参数传递。
@Override //当启动源跟Service成功连接之后将会自动调用这个方法
public void onServiceConnected(ComponentName name, IBinder binder) {
b = (MyBindService.MyBinder)binder;
}
}; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
} //声明周期事件
public void doClick(View v){
switch(v.getId()){
case R.id.btn_bindstart:
Intent intent = new Intent(MainActivity.this, MyBindService.class);
bindService(intent, conn,Service.BIND_AUTO_CREATE);
break;
case R.id.btn_bindstop:
unbindService(conn);
break;
}
} public void musicClick(View v){
//通过b.xxx调用service中的方法
switch(v.getId()){
case R.id.btnPlay:
b.getService().play();
break;
case R.id.btnPause:
b.getService().pause();
break;
case R.id.btnNext:
b.getService().next();
break;
case R.id.btnPrev:
b.getService().prev();
break;
}
}
}
AndroidManifest.xml注册service对象
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.servicedemo2"
android:versionCode="1"
android:versionName="1.0" > <uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="18" /> <application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.servicedemo2.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name="com.example.servicedemo2.MyBindService"></service>
</application>
</manifest>
Android学习(十四) Service组件的更多相关文章
- android学习十四(android的接收短信)
收发短信是每一个手机主要的操作,android手机当然也能够接收短信了. android系统提供了一系列的API,使得我们能够在自己的应用程序里接收和发送短信. 事实上接收短信主要是利用我们前面学过的 ...
- android 学习十四 探索安全性和权限
1.部署安全性:应用程序必须使用数字证书才能安装到设备上. 2.执行期间的安全性: 2.1 使用独立进程 2.2 使用固定唯一用户ID 2.3 申明性权限模型 3数字证书 ...
- 五、Android学习第四天补充——Android的常用控件(转)
(转自:http://wenku.baidu.com/view/af39b3164431b90d6c85c72f.html) 五.Android学习第四天补充——Android的常用控件 熟悉常用的A ...
- 四、Android学习第四天——JAVA基础回顾(转)
(转自:http://wenku.baidu.com/view/af39b3164431b90d6c85c72f.html) 四.Android学习第四天——JAVA基础回顾 这才学习Android的 ...
- Bootstrap入门(十四)组件8:媒体对象
Bootstrap入门(十四)组件8:媒体对象 这是一个抽象的样式,用以构建不同类型的组件,这些组件都具有在文本内容的左或右侧对齐的图片(就像博客评论或 Twitter 消息等). 1.基本样式 2. ...
- Android笔记三十四.Service综合实例二
综合实例2:client訪问远程Service服务 实现:通过一个button来获取远程Service的状态,并显示在两个文本框中. 思路:如果A应用须要与B应用进行通信,调用B应用中的getName ...
- android学习日记20--连接组件之Intent和IntentFilter
上次刚了解完Android的四大组件,现在学习组件间通信的Intent和IntentFilter 一.Intent 1.简述 Intent(意图)在应用程序运行时连接两个不同组件,是一种运行时的绑定机 ...
- android学习日记19--四大组件之Services(服务)
一个Android应用主要由四个基本组件组成,Android四大基本组件分别是Activity,Content Provider内容提供者,Service服务,BroadcastReceiver广播接 ...
- Android学习总结(二)——Service基本概念和生命周期
好了,前面我们已经学习了Activity的知识,相信大家也有一定的理解,但是还是不能放松,Android四大组件,我们才学习了一个而已,接下我们继续学习Service.计划总结如下内容: 一.Serv ...
- android学习笔记56——Service
Service四大组件之一,需要在AndroidMainfest.xml中添加相关配置,运行于后台,不与用户进行交换,没有UI... 配置时可通过<intent-filter.../>元素 ...
随机推荐
- 算法详解(LCA&RMQ&tarjan)补坑啦!完结撒花(。◕ˇ∀ˇ◕)
首先,众所周知,求LCA共有3种算法(树剖就不说了,太高级,以后再学..). 1.树上倍增(ST表优化) 2.RMQ&时间戳(ST表优化) 3.tarjan(离线算法)不讲..(后面补坑啦!) ...
- 推送通知iOS客户端编写实现及推送服务器端编写
http://blog.csdn.net/tonny_guan/article/details/8963262 1.iOS客户端编程 推送通知技术在Mac OS X和iOS系统上都可以运行,我们本章主 ...
- linux free 命令 ,讲解得比较好
解释一下Linux上free命令的输出. 下面是free的运行结果,一共有4行.为了方便说明,我加上了列号.这样可以把free的输出看成一个二维数组FO(Free Output).例如: FO[2][ ...
- Python与数据库[2] -> 关系对象映射/ORM[3] -> sqlalchemy 的声明层 ORM 访问方式
sqlalchemy的声明层ORM访问方式 sqlalchemy中可以利用声明层进行表格类的建立,并利用ORM对象进行数据库的操作及访问,另一种方式为显式的 ORM 访问方式. 主要的建立步骤包括: ...
- Codeforces 1009F Dominant Indices
另类解法 将每一个节点拥有的各深度节点数量存在vector中,向上返回,这样不会占用过多的内存,以此判断最多节点相应的深度即可,但正常写最后一个数据会T,毕竟一次复制一个节点,相当于复制了(1+2+3 ...
- [POJ 3378] Crazy Thairs
Link: POJ 3378 传送门 Solution: 按序列长度$dp$, 设$dp[i][j]$为到第$i$个数,符合要求的序列长度为$j$时的序列个数, 易得转移方程:$dp[i][j]=\s ...
- Struts2笔记--Action访问Servlet API
Web应用中通常需要访问的Servlet API就是HttpServletRequest.HttpSession和ServletContext,这三个接口分别代表JSP内置对象中的request.se ...
- Java 并发工具包 java.util.concurrent 用户指南(转)
本文转自http://blog.csdn.net/defonds/article/details/44021605/ 感谢作者 1. java.util.concurrent - Java 并发工具包 ...
- DELPHI7下SUPPEROBJECT遍历子对象的name和value
DELPHI7下SUPPEROBJECT遍历子对象的name和value var ite: TSuperAvlIterator; while ite.MoveNext do begin if ite. ...
- ASP.NET 5基础之中间件
来源https://docs.asp.net/en/latest/fundamentals/middleware.html 一些可以整合进http请求管道的小的应用组件称做中间件.ASP.NET 5集 ...