android service基础
来源:互联网 发布:白俄罗斯知乎 编辑:程序博客网 时间:2024/06/05 14:41
一、启动/销毁service
//start service
intent = new Intent(context, MtpService.class);
intent.putExtra(UsbManager.USB_FUNCTION_PTP, true);
context.startService(intent);
//destroy service
context.stopService(new Intent(context, MtpService.class));
二、绑定/解绑定
private IMtpService mMtpService;
private final ServiceConnection mMtpServiceConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, android.os.IBinder service) {
synchronized (this) {
mMtpService = IMtpService.Stub.asInterface(service);
}
}
public void onServiceDisconnected(ComponentName className) {
synchronized (this) {
mMtpService = null;
}
}
};
//bind
context.bindService(new Intent(context, MtpService.class), mMtpServiceConnection, Context.BIND_AUTO_CREATE);
当bindService执行之后会自动调用mMtpServiceConnection接口里面的onServiceConnected方法,从而获得mMtpService,
然后在Activity里面就能够通过mMtpService调用IMtpService提供的方法。
//unbind
getContext().unbindService(mMtpServiceConnection);
unbindService之后不会自动调用mMtpServiceConnection接口里面的onServiceDisconnected方法,onServiceDisconnected只会
在Service被停止或者被系统杀死后调用。unbindService只是告诉系统对应的Activity不再使用该服务了,系统内存不足的时候可以优先
杀死这个服务。
Service在开始之后,除非调用stopService()或stopSelf(),否则不会停止。当然,如果内存不足,系统可能自动杀死Service。
三、IMtpService
新建文件IMtpService.aidl
package com.android.providers.media;
interface IMtpService
{
void sendObjectAdded(int objectHandle);
void sendObjectRemoved(int objectHandle);
}
是一个interface,具体实现在MtpService中。
四、MtpService
private final IMtpService.Stub mBinder =
new IMtpService.Stub() {
public void sendObjectAdded(int objectHandle) {
//实现这个方法
}
public void sendObjectRemoved(int objectHandle) {
//实现这个方法
}
};
在MtpService服务的onBind方法中返回这个mBinder。
@Override
public IBinder onBind(Intent intent)
{
return mBinder;
}
- Android基础 : Android Service
- Android基础 : Android Service
- Android基础之Service
- Android (一) Service基础
- Android基础之Service
- 【Android】Service基础学习
- android service基础
- Android基础------Service服务
- Android--Service之基础
- Android--Service之基础
- android Service基础
- Android--Service之基础
- Android基础--Service应用
- Android基础service简介
- [Android基础]Service
- android的service基础
- Android Service基础
- Android Service 基础详解
- linux 文件描述符和库函数FILE文件指针关系
- android中media的datasource
- (转)Android SQLite解析
- Java命令参数说明大全
- Oracle数组,集合
- android service基础
- Ehcache页面缓存的使用
- python扩展:包装C++类
- Linux ===> 实用的8个LINUX命令行监测工具
- C#修饰符之一(常用类)
- (转)Android 应用程序之间数据共享—ContentResolver
- U-Boot与Linux内核的交互
- 《#诗盗#·挨踢威》
- 坚持减肥第三天Mark一下