开启服务:
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可以正常工作