昨天学习了服务(Service),没太弄清楚,先记下来吧,后面还是要复习的。
service是实现程序后台运行的解决方案,服务并不运行于独立的进程之外,而是依赖所创建的服务,当进程被杀死的时候,服务也随之停止运行。服务不会自动开启线程,我们需要在服务内部手动创建子线程。
需要注意的是我们如果要更新程序中的UI元素,必须在主线程中进行,否则会出现异常。
多线程:
为了更方便的在子线程中对UI进行操作,android提供了一些好用的工具,像AsyncTask。
AsyncTask是抽象类,所以需要子类去继承它,继承时可以为其指定三个泛型参数
1,Params,执行AsyncTask时传入的参数,用于后台中的任务。
2,Progress,后台执行时若需要显示当前的进度,则可以使用指定的泛型作为进度单位
3,Result,任务执行完毕,若要对结果进行返回,则使用指定的泛型类型作为返回值类型
之后还需要重写AsyncTask中的几个方法
1,onPreExecute(),这个方法会在任务开始之前调用,用于界面的初始化。
2,doInBackground(Params),这个方法的所有代码都会在子线程中运行,任务完成就通过return语句将任务执行的结果返回。但是这个方法是不进行UI操作的,若要进行UI操作,可以调用publishProgress(Progress)方法。
3,onProgressUpdate(Progress),当后台调用了publishProgress(Progress)方法后,这个方法就会被调用,参数就是上面的。这个方法是可以对UI进行操作
4,onPostExecute(Result),后台任务执行完毕通过return返回时,调用这个方法。
即:doInBackground(Params)执行具体的耗时任务,onProgressUpdate(Progress)进行UI更新,onPostExecute(Result)执行任务的收尾工作。当然要先启动这个任务,通过:
new DownloadTask().execute(),新建一个类继承AsyncTask然后.execute();
服务:
在这篇文章中写的比较详细,http://blog.youkuaiyun.com/t12x3456/article/details/7695719
前台服务:
与普通服务最大的区别就是正在运行的图标在系统的状态栏,类似通知
public class MyService extends Service {
public void onCreate() {
super.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, "title", "contentText", pendingIntent);
startForeground(1, notification);
}
}
与通知不同,没有使用NotificationManager将通知显示出来,而是调用startForeground()方法,之后就会让MyService变成一个前台服务,并在系统的状态栏中显示出来。
IntentService:
创建了一个异步的,会自动停止的服务,Android提供了IntentService类
public class MyIntentService extends IntentService {
public MyIntentService() {
super("MyIntentService");
}
@Override
protected void onHandleIntent(Intent intent) {
Log.d("MyIntentService", "Thread id is"+Thread.currentThread().getId());
}
private void onDestory() {
super.onDestroy();
Log.d("MyIntentService", "onDestory executed");
}
}
首先提供一个无参的构造函数,并且在内部调用父类的有参构造函数,在子类中实现onHandleIntent()抽象方法,在这个方法中处理一些具体的逻辑,这些都是自动运行在子线程当中,根据IntentService的特性,服务会在运行结束后自动停止,所以重写onDestory()方法。