android之IntentService类的实现
16lz
2022-01-23
package com.ghg.MyIntentService;import android.app.Service;import android.content.Intent;import android.os.Handler;import android.os.HandlerThread;import android.os.IBinder;import android.os.Looper;import android.os.Message;/** * IntentService类的精简版,在(main线程)activity启动下载服务类,把需要下载的资源路径传给service,在service中, * 创建handler对象和消息对象,工作进程,然后通过handler对象把消息发送到和handler绑定的消息队列中(工作线程中),下载任务, * 下载结束后,把本次的启动的service关闭; * @author gaohong * */public class MyIntentService extends Service {HandlerThread thread;Handler handler;/** * 初始化工作线程和handler */@Overridepublic void onCreate() {// TODO Auto-generated method stubsuper.onCreate();thread=new HandlerThread("workThread");System.out.println("在"+Thread.currentThread().getName()+"线程中创建工作线程");thread.start();Looper looper=thread.getLooper();handler=new Handler(looper){@Overridepublic void handleMessage(Message msg) {// TODO Auto-generated method stubSystem.out.println("在"+Thread.currentThread().getName()+"中处理消息");onHandleIntent((Intent)msg.obj);stopSelf(msg.arg1);//下载结束后把该次的调用service结束}};}protected void onHandleIntent(Intent intent) {// TODO Auto-generated method stubString uri=intent.getStringExtra("uri");try {thread.sleep(3000);//相当于下载任务;} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}/* * 创建消息,用handler发送 * */@Overridepublic int onStartCommand(Intent intent, int flags, int startId) {// TODO Auto-generated method stubMessage msg=Message.obtain();msg.obj=intent;msg.arg1=startId;System.out.println("在"+Thread.currentThread().getName()+"线程中发送消息");handler.sendMessage(msg);return super.onStartCommand(intent, flags, startId);}@Overridepublic void onDestroy() {// TODO Auto-generated method stubthread.quit();super.onDestroy();}@Overridepublic IBinder onBind(Intent intent) {// TODO Auto-generated method stubreturn null;}}
activity中的代码:
package com.ghg.MyIntentService;import android.app.Activity;import android.content.Intent;import android.os.Bundle;public class Day1305_MyIntentServiceActivity extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Intent intent=new Intent(this, MyIntentService.class); intent.putExtra("uri", "http://192.168.1.162:8080/musiconline/musics/001.mp3"); startService(intent); }}
更多相关文章
- android 多线程下载
- Android(安卓)Activity sleep 自线程更新主线程UI
- Android(安卓)之 ProgressBar用法介绍
- Android(安卓)文件下载与解压缩
- android studio 55[2]线程更新UI handler 2
- android 源码下载与编译(ubuntu11.04)
- 浅析Android中的消息机制
- 如何下载Android(安卓)kernel内核源代码,编译烧写验证
- 最新Android(安卓)ADT, SDK, SDK_tool等官方下载说明(及时更新)