团队博客14
实现异步任务机制---AsyncTask
AsyncTask直接继承与object类:
import android.os.AsyncTask;
实现异步加载音频的一段代码:
//异步加载音频 public class MyVideo extends AsyncTask<String, Integer, ArrayList<MusicInfor>> { @Override protected ArrayList<MusicInfor> doInBackground(String... params) { ArrayList<MusicInfor> lpath=new ArrayList<MusicInfor>(); Uri mVideoUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI; ContentResolver mContentResolver =context.getContentResolver(); Cursor cursor=mContentResolver.query(mVideoUri, null, null, null,null); while(cursor.moveToNext()) { MusicInfor music=new MusicInfor(); //音乐ID int id=cursor.getInt(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media._ID)); //音乐名称 String name=cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DISPLAY_NAME)); //音乐存储路径 String path=cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA)); //音乐修改日期 long updateTime=cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATE_MODIFIED)); updateTime = updateTime*1000; //格式化时间,获取年,月,日 String[] times = common.getTimeInfo(updateTime); String date=times[0]+"年"+times[1]+"月"+times[2]+"日 "+times[3]+":"+times[4]+":"+times[5]; //获取音频长度 long ltime=cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DURATION)); String mtime=common.GetTime(ltime); //获取音频大小 int lsize=cursor.getInt(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.SIZE)); BigDecimal pSize=common.parseApkSize(lsize); long size=pSize.longValue(); music=new MusicInfor(name,path,date,size,mtime); lpath.add(music); } cursor.close(); return lpath; }
在这段代码中,我们重写了doInBackground(String... params)这个方法,这个方法在后台线程中执行,完成异步任务的主要工作,通常需要较长的时间。