Android开发学习之路-- 关于服务Service
来源:互联网 发布:淘宝注册账号打电话 编辑:程序博客网 时间:2024/06/05 18:05
开启服务:
Intent intent = new Intent(this,MyService.class);
startService(intent);
关闭服务:
Intent intent = new Intent(this,MyService.class);
stopService(intent);
绑定服务:
//MySerVice.DownloadBinder是在服务中自定义的类:实现了要完成的功能(方法)
private ServiceConntction connection = new ServiceConnection(){
onServiceDisconnected(){ ... ... }
onServiceConnected(ComponentNane name,IBinder service){
MySerVice.DownloadBinder downloadBinder = (...)service;
//接下来就可以使用downloadBinder来调用服务中的方法了
}
};
Intent intent = new Intent(this,MyService.class);
bindService(intent,connection,BIND_AUTO_CREATE);
解绑服务:
unbindService(connection);
1.使用前台服务
前台服务和普通服务的最大区别在于,它会一直有一个正在运行的图标在系统的状态栏中显示,下拉状态栏后可以看到更加详细的信息,非常类似于通知的效果
在自定义Service的onCreate()添加如下代码就可以创建一个前台服务:
Notification notification = new Notification(R.drawable.ic_launcher,”Notification comes”,System.currentTimeMillis());
Intent notificationIntent = new Intent(this,MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this,0,notificationIntent,0);
notification.setLatestEventInfo(this,”this is title”,”this is content”,pendingIntent);
startForeground(1,notification); //将一个Service变成一个前台服务
2.使用IntentService解决ANR问题
因为服务的代码默认是运行在主线程的,如果直接在服务里去处理一些耗时的逻辑,就很容易出现ANR(Application Not Responding)的情况
这时候就需要用掉Android的多线程编程技术了,我们应该在服务的每一个具体的方法里开启一个子线程,然后在这里去处理那些耗时的逻辑。
实例:
public class MyService extends Service{
...
Public int onStartCommand(Intent intent,int flags,int startId){
new Thread(new Runnable(){
public void run(){
//处理具体逻辑
... ...
stopSelf(); //服务开启就一直处于运行状态,要调用该方法停止
}
}).start();
}
使用IntentService类可以创建一个异步的、会自动停止的服务:
1)新建一个类,继承自IntentService
2)提供一个无参构造方法,并且必须在其内部调用父类的有参构造函数
3)实现onHandleIntent()抽象方法,用于处理耗时操作而无需担心ANR,因为该方法已经在子线程中运行了
4)使用的时候直接startService(intentService);就可以了
另外根据IntentService的特性,这个服务会在运行结束后自动停止
3.后台执行定时任务:
1)Java API中的Timer类:不适用于需要长期在后台运行的定时任务,原因是手机的休眠策略会自动让CPU进入到休眠状态,导致定时任务无法正常运行
2)Android的Alarm机制:它具有唤醒CPU(不同于唤醒屏幕)功能,可以保证每次需要执行定时任务的时候CPU可以正常工作
- 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学习之本地服务
- golang(cgo)---如何在两个不同的package中使用同样的自定义数据类型?
- 插入排序及思想引用
- session匹配错误
- 图片匹配技术之巴氏距离
- hdu-2199-Can you solve this equation?
- Android开发学习之路-- 关于服务Service
- HTML 学习(一)之 简介
- 自定义view教你如何打造圆形的seekbar
- 好文章
- 在ubuntu linux下搭建Java Web开发环境
- hdu4465
- 公共子序列的个数
- bzoj 4569: [Scoi2016]萌萌哒 (st表+并查集)
- 使用友盟SDK提交Appstore审核被拒的常见解决方法