1:什么是服务?
服务:在后台运行,主要是执行不需要于用户交互,长期在后台执行。
2: Android的多线程编程:
2.1 线程的基本用法:
方法一: class MyThread extends Thread {
重写run方法:
启动线程: new Thread().start();
方法二: new Thread (new Runnable()
重写run方法:
}) .start();
3:在子线程中更新UI;
Android的UI是线程不安全的,更新UI必须在主线程中进行,否则会出现异常(Android不允许在子线程中跟新UI)。
***解决方案1:
(有时必须在子线程中做一些耗时操作)通过异步消息处理机制,解决了在子线程中更新UI的问题。
异步消息处理有4个部分组成:
Message : Message 是在线程之间传递消息,携带少量信息在不同线程之间传递,Message.what , 使用obj字段携带一个Object对象。
Handler : 处理者,用于发送和处理消息,
MessageQueue : 消息队列,存放Handler发送的消息
Looper : 管理MessageQueue 。
***解决方案2:
AsyncTask 是一个抽象类,使用时继承AsyncTask 。
class MyloadTask extends AsyncTask <Void , Integet , Boolean> { ......} .
三个参数:
Params :
Progress:
Result:
四个方法:
onPreExecute() : 后台任务执行前调用,界面初始化,显示进度条,对话框。
doInBackground(): 执行耗时任务。
onProgressUpdate(): 更新UI。
onPostExecute(Result): 提醒任务执行结果,关闭进度条对话框。
4: 服务的基本用法:
4.1 定义一个服务:
class MyService extends Service {
重写onBind()方法:
onCreate()方法: 服务 创建时调用
onStartCommand()方法: 服务启动时调用
onDestory()方法: 服务销毁时调用
4.2 服务的启动于停止:
在OnCreate():
启动服务: Intent startIntent = new Intent(this,MyService.class);
startService(startIntent );
停止服务:
Intent stopIntent = new Intent(this,MyService.class);
stopService(stopIntent );
5:活动和服务进行通信:
6:活动的生命周期:
onCreate()方法: 服务 创建时调用
onStartCommand()方法: 服务启动时调用
onBind()方法():
onDestory()方法: 服务销毁时调用
7:服务的更多技巧:
7.1 使用前台服务:
class MyService extends Service {
onCreate()方法中:
7.2 : 使用IntentService:
class MyIntentServiceextends IntentService {
public MyIntentService(){
super("MyIntentService");
明天接着写。