(IntentService在执行时会开启工作线程执行耗时操作,具体在onHandleIntent方法中,但是service不行)
1:IntentService onHandleIntent()方法中执行耗时任务:
//创建IntentService
public class MyService extends IntentService {
public MyService() {
super("workThread");
}
public void onCreate() {
super.onCreate();
}
public void onDestroy() {
super.onDestroy();
}
public int onStartCommand(Intent intent, int flags, int startId) {
return super.onStartCommand(intent, flags, startId);
}
protected void onHandleIntent(Intent intent) {
String path = intent.getStringExtra("path");
for (int i = 1; i <= 3; i++) {
Log.i("info", Thread.currentThread().getName() + "线程中执行任务:" + path+ ",i=" + i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
//Activity中启动service并传递数据:
String path = "img/" + new Random().nextInt(100000) + ".jpg";
Intent intent = new Intent(this, MyService.class);
intent.putExtra("path", path);
startService(intent);
2:IntentService onHandleIntent()方法中执行耗时下载任务:
//创建IntentService
public class MusicService extends IntentService {
public void onCreate() {
......
}
protected void onHandleIntent(Intent intent) {
// 从intent中获取音乐下载路径
String path = intent.getStringExtra("path");
// 下载
File savePath = new File("/mnt/sdcard/" + path);
if (savePath.exists()) {
Message msg = Message.obtain();
msg.what = MSG_TAG_FILE_EXISTS;
msg.obj = savePath;
handler.sendMessage(msg);
return;
}
......
}
}
//Activity中启动service并传递数据:
Intent intent = new Intent(this, MusicService.class);
intent.putExtra("path", m.getMusicPath());
startService(intent);
3:service中可以自己开启工作线程执行耗时任务并发送广播通知并在UI的广播接收处理器更新UI:
//继承service:
public class MusicPlayService extends Service {
public void play() {}
public void pause() {}
public void previous() {}
public void next() {}
public void seekTo(int position) {
..............
/ 创建工作线程并发送广播.
isLoop = true;
needUpdate = true;
thread = new Thread() {
public void run() {
while (isLoop) {
if (needUpdate && player.isPlaying()) {
// 发送更新进度条广播.让滚动条动起来.在这里发广播是因为播放引起的滚动条移动就是在这里发生的.
Intent intent = new Intent(
GlobalUtils.ACTION_UPDATE_PROGRESS);
intent.putExtra(GlobalUtils.EXTRA_PROGRESS, player
.getCurrentPosition());
intent.putExtra(GlobalUtils.EXTRA_DURATION, player
.getDuration());
intent.putExtra(GlobalUtils.EXTRA_MUSIC_NAME, app
.getMusics().get(app.getCurrentIndex())
.getName());
sendBroadcast(intent);
try {
sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
} else {
synchronized (this) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
};
thread.start();
}
}
//在MusicPlayerActivity启动MusicPlayService:
Intent intent = new Intent(this, MusicPlayService.class);
startService(intent);// 启动服务.