Android -- service的开启方式, start开启和绑定开启服务,调用服务的的方法, aidl调用远程服务
1. 概述
bindService() 绑定服务 可以得到服务的代理人对象,间接调用服务里面的方法.
绑定服务: 间接调用服务里面的方法.
如果调用者activity被销毁了, 服务也会跟着销毁
(不求同时生,但求同时挂)
开启服务: 不可以调用服务里面的方法.
如果调用者activity退出了, 服务还会长期的在后台运行
生命周期:
1.单独调用 startService() - oncreate
stopService() ondestroy
-----------------------------------
bind ->oncreate -> onbind
unbind -> onunbind ->ondestroy
服务只能被解绑一次,多次的解除绑定服务 应用程序会报错.
混合调用.
需求: 既要保证服务长期的在后台运行,又想去调用服务里面的方法.
技巧: 1.先开启服务 2.绑定服务.
步骤:1.开启服务 startService()- oncreate();
2.绑定服务 bindService() - onbind();
3.关闭程序 ,调用者退出, 服务被解绑.
4.stopService() 停止服务.
2. 示意图
3. 示例代码
MainActivity.java 开启服务
public class MainActivity extends Activity {
//步骤4: 在activity里面得到服务 ibinder对象的引用.
private IService myBinder;
private MyConn conn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
/**
* 开启服务
*
* @param view
*/
public void start(View view) {
Intent intent = new Intent(this, CungeService.class);
// 采用api 创建 服务 ,服务对象是被系统(框架 )new 出来
startService(intent);
}
/**
* 停止服务
*/
public void stop(View view) {
Intent intent = new Intent(this, CungeService.class);
stopService(intent);
}
public void bind(View view){
Intent intent = new Intent(this, CungeService.class);
//intent 激活服务的意图
// conn 代理人 中间人对象 用来跟服务建立联系 不能为空
// BIND_AUTO_CREATE 在绑定服务的时候 如果服务不存在 就自动的创建
//步骤1: 采用绑定服务的方式 开启服务
conn = new MyConn();
bindService(intent,conn , BIND_AUTO_CREATE);
}
//接触绑定服务的方法
public void unbind(View view){
unbindService(conn);
}
@Override
protected void onDestroy() {
try{
unbindService(conn);
}catch (Exception e) {
}
super.onDestroy();
}
private class MyConn implements ServiceConnection{
// 在服务被成功绑定的时候 调用的方法
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
System.out.println("春哥把代理人返回回来了...");
//步骤3: 服务返回的ibinder对象 会被传递给 MyConn 的回调方法
System.out.println(service);
myBinder = (IService) service;
}
// 在服务失去绑定的时候 调用的方法 只有程序异常 终止,
@Override
public void onServiceDisconnected(ComponentName name) {
}
}
/**
* 调用服务里面的方法 ,换首歌
*/
public void change(View view) {
// 由于系统框架在创建服务的时候 会创建与之对应的上下文,
// 下面的代码 是直接new对象 .
// CungeService service = new CungeService();
// service.changeSing("月亮之上");
//步骤5: 利用ibinder 对象 间接的调用了服务里面的方法
myBinder.callChangeSing("月亮之上");
}
}
CungeService.java 服务代码
/**
* 在后台长期运行的组件 唱歌
* @author Administrator
*
*/
public class CungeService extends Service { @Override
public void onCreate() {
super.onCreate();
System.out.println("onCreate 服务开始了 ,春哥 开始唱歌");
} @Override
public IBinder onBind(Intent intent) {
System.out.println(" onBind 春哥服务被成功的绑定了...."); //步骤2: 服务在成功绑定的时候 会调用onbind方法 返回一个ibinder对象.
//返回自定义的代理人对象
MyBinder mybinder = new MyBinder();
System.out.println(mybinder.toString());
return mybinder;
} /**
* 更改唱的歌曲
* @param singName
*/
public void changeSing(String singName){
Toast.makeText(getApplicationContext(), "开始唱"+singName, 0).show();
} private class MyBinder extends Binder implements IService{
//间接的利用代理人 调用了春哥的方法
//内部类为private, 通过IService接口只暴露所需的方法
public void callChangeSing(String name){
changeSing(name);
} public void peiCungeWatchTV(){ }
public void peiCungeCountMoney(){ }
} @Override
public boolean onUnbind(Intent intent) {
System.out.println("onunbind");
return super.onUnbind(intent);
} @Override
public void onDestroy() {
super.onDestroy();
System.out.println("onDestroy 服务销毁了 ,春哥停止唱歌");
} }
IService.java ,Binder接口,限制暴露出来的方法个数
//春哥代理人的接口
public interface IService {
public void callChangeSing(String name);
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.itheima.testservice"
android:versionCode="1"
android:versionName="1.0" > <uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" /> <application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.itheima.testservice.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=".CungeService"></service>
</application> </manifest>
activity_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"
tools:context=".MainActivity" > <Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="start"
android:text="开启服务" /> <Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="stop"
android:text="停止服务" /> <Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="bind"
android:text="绑定服务" /> <Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="unbind"
android:text="解除绑定服务" /> <Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="change"
android:text="调用服务里面的方法,换首歌" /> </LinearLayout>
4. aidl调用远程服务
绑定服务: 绑定服务不仅可以绑定本地的服务 还可以绑定远程(调用者和服务在不同的进程)服务,一个app调用另一个app的服务。
被调服务仍然是上面的服务, 只需要做两个修改
(1. 将 IService.java 文件改为 IService.aidl , 并将里面的public去掉
(2. 配置文件注册的时候添加action
<service android:name=".RemoteService" >
<intent-filter>
<action android:name="com.kevin.remoteservice" >
</action>
</intent-filter>
</service>
另一个app调用时操作也类似,
(1. 将IService.aidl 连同包名一起拷贝到当前app工程, 一定要连同包名拷贝
(2. MainActivity.java 开启服务
public class MainActivity extends Activity {
private IService iService;
private MyConn conn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void bind(View view){
Intent intent = new Intent();
intent.setAction("com.kevin.remoteservice");
conn = new MyConn();
bindService(intent,conn , BIND_AUTO_CREATE);
}
public void call(View view){
try {
iService.callMethodInService();
} catch (RemoteException e) {
e.printStackTrace();
}
}
private class MyConn implements ServiceConnection{
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
//Iservice 远程调用API
iService = IService.Stub.asInterface(service);
}
@Override
public void onServiceDisconnected(ComponentName name) {
}
}
}
Android -- service的开启方式, start开启和绑定开启服务,调用服务的的方法, aidl调用远程服务的更多相关文章
- android service两种启动方式
android service的启动方式有以下两种: 1.Context.startService()方式启动,生命周期如下所示,启动时,startService->onCreate()-> ...
- Android Service 详解
一个Service也是一种应用程序组件,它运行在后台以提供某种服务,通常不具有可见的用户界面.其它的应用程序组件可以启动一个 Service,即使在用户切换到另外一个应用程序后,这个Service还是 ...
- Android Service总结01 目录
Android Service总结01 目录 1 Android Service总结01 目录 2 Android Service总结02 service介绍 介绍了“4种service 以及 它们的 ...
- 18_Android中Service的生命周期,远程服务,绑定远程服务,aidl服务调用,综合服务案例,编写一个应用程序调用远程支付宝远程服务场景
============================================================================ 服务的生命周期: 一.采用start的方式开始 ...
- Android service ( 一 ) 三种开启服务方法
一. Service简介 Service是android 系统中的四大组件之一(Activity.Service.BroadcastReceiver.ContentProvider),它跟 Activ ...
- 安卓服务(Service)的两种开启方式以及服务的生命周期
安卓中服务的开启方式 一:採用start的方式开启服务 调用函数:startService(Intent)->onCreate()->onStart()/onStartCommand()- ...
- Android -- Service的开启关闭与生命周期
Service是Android 系统中的四大组件之一,是在一段不定的时间运行在后台,不和用户交互应用组件. service可以在很多场合的应用中使用,比如播放多媒体的时候用户启动了其他Activity ...
- Android service的开启和绑定,以及调用service的方法
界面: <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android= ...
- [android] 绑定方式开启服务&调用服务的方法
需求:后台开启一个唱歌服务,这个服务里面有个方法切换歌曲 新建一个SingService继承系统Service 重写onCreate()和onDestory()方法 填一个自定义的方法changeSi ...
随机推荐
- Unity3D笔记三 物理引擎
一.物理引擎 1.物理引擎就是模拟真实世界中物体碰撞.跌落等反应,通过Ballance.愤怒的小鸟来理解什么是物理引擎.Unity的物理引擎使用的是NviDIA的PhysX.2.选中一个游戏对象,主菜 ...
- 阅读笔记:A Few useful things to Know About machine Learning
这是Machine Learning领域的经典论文,文中提到了ML相关的12个keys,并自称这些keys是“black art”,我觉得有点像ML的“最佳实践”. 网上有此文的中文翻译,写得很详细, ...
- Webservice实践(七)CXF 与Spring结合+tomcat发布
上一节介绍了如何使用CXF 来发布服务,但是没有介绍使用web 容器来发布,很多项目需要用tomcat 这样的容器来发布.另外本节将介绍CXF 与spring 结合的方法. 一 目标: 1.利用spi ...
- Linux下批量管理工具pssh使用记录
pssh是一款开源的软件,使用python实现,用于批量ssh操作大批量机器:pssh是一个可以在多台服务器上执行命令的工具,同时支持拷贝文件,是同类工具中很出色的:比起for循环的做法,我更推荐使用 ...
- Django权限系统auth模块详解
转自:原文出处 auth模块是Django提供的标准权限管理系统,可以提供用户身份认证, 用户组和权限管理. auth可以和admin模块配合使用, 快速建立网站的管理系统. 在INSTALLED_A ...
- Windows:子线程中创建窗口
一般来讲,UI的所有操作都必须在主线程,否则会出现未知错误.但有时候我们会需要一个功能比较单一的窗口,同时希望他在一个单独的线程运行.并不影响主线程的效率. 下面说明一下新建子线程创建的新窗口的方法, ...
- Openstack(三)Haproxy+Keepalived双机
3.1部署keepalived 3.1.1下载keepalived源码包,并解压 # wget http://www.keepalived.org/software/keepalived-1.4.2. ...
- MapReduce的几个实现
1.倒排索引的实现 import java.io.IOException; import java.util.StringTokenizer; import org.apache.hadoop.con ...
- Android初体验之Monkey和MonkeyRunner
原文地址https://blog.csdn.net/mad1989/article/details/38087737 Monkey 什么是Monkey Monkey是Android中的一个命令行工具, ...
- 为什么要同时重写equals和hashcode
原文地址https://blog.csdn.net/tiantiandjava/article/details/46988461 原文地址https://blog.csdn.net/lijiecao0 ...