android service 总结
来源:互联网 发布:tensorflow如何使用 编辑:程序博客网 时间:2024/06/15 04:41
一,service两种启动模式的生命周期的区别
1,startService启动
onCreate -> onStartCommand -> Service Running -> onDestroy
2,bindService启动
onCreate -> onBind -> Service Running -> onDestroy
startService主要用于后台任务,而activity等其他组件可以通过bindService和service进行通信
二,service工作线程
service一般运行在主线程, 可以将一些运算任务或者一些需要长期执行的任务,比如和服务端的心跳连接放在service中执行,当然这时候就需要创建
工作线程
三,service通信机制
有一些任务比较独立的任务可以在新的进程中执行,此时如果需要和service交互,则可以通过binder;
如果是在同一个进程中进行通信,也需要通过binder,但此时binder并没有进行进程通信:
public class MyService extends Service { public static final String TAG = "MyService"; private MyBinder mBinder = new MyBinder(); @Override public void onCreate() { super.onCreate(); Log.d(TAG, "onCreate() executed"); } @Override public int onStartCommand(Intent intent, int flags, int startId) { Log.d(TAG, "onStartCommand() executed"); return super.onStartCommand(intent, flags, startId); } @Override public void onDestroy() { super.onDestroy(); Log.d(TAG, "onDestroy() executed"); } @Override public IBinder onBind(Intent intent) { return mBinder; } class MyBinder extends Binder { public void startDownload() { Log.d("TAG", "startDownload() executed"); // 执行具体的下载任务 } } }
如果是需要进程间通信,则需要通过AIDL文件,创建Binder进行通信:
public class MyService extends Service { ...... @Override public IBinder onBind(Intent intent) { return mBinder; } MyAIDLService.Stub mBinder = new Stub() { @Override public String toUpperCase(String str) throws RemoteException { if (str != null) { return str.toUpperCase(); } return null; } @Override public int plus(int a, int b) throws RemoteException { return a + b; } }; }
在activity中在连接到service后的回调中:
private ServiceConnection connection = new ServiceConnection() { @Override public void onServiceDisconnected(ComponentName name) { } @Override public void onServiceConnected(ComponentName name, IBinder service) { myAIDLService = MyAIDLService.Stub.asInterface(service); try { int result = myAIDLService.plus(3, 5); String upperStr = myAIDLService.toUpperCase("hello world"); Log.d("TAG", "result is " + result); Log.d("TAG", "upperStr is " + upperStr); } catch (RemoteException e) { e.printStackTrace(); } } };
0 0
- 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组件总结
- android service组件总结
- TCP,IP,HTTP,SOCKET区别和联系
- 点击listivew中item的button并在activity中网络请求的,根据网络请求结果更改button状态的解决办法
- WebStorm打造最强React Native IDE
- Unity5 (5.0-5.2) Shader编译机制初探
- 欢迎使用CSDN-markdown编辑器
- android service 总结
- windows平台下实现《简明python教程》第10章的文件备份示例四
- 2016年总结
- leetcode 112. Path Sum
- 数组作为函数参数
- c++11-正则表达式
- CA解扰那点事
- git使用总结
- HTML嵌入到iOS页面的开发