在service中调用子线程报异常
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
//实例化 MyHandler类
myHandler=new MyHandler();
if(ACTION_START.equals(intent.getAction())){
FileInfo fileInfo=(FileInfo)intent.getSerializableExtra("fileInfo");
//启动初始化线程
Log.d("huefew","正常");
new InitThread(fileInfo).start();
}else if(ACTION_STOP.equals(intent.getAction())){
FileInfo fileInfo=(FileInfo)intent.getSerializableExtra("fileInfo");
if(mTask!=null){
mTask.isPause=true;
}
}
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
}
/*
* 初始化子线程
*/
class InitThread extends Thread{
private FileInfo mFileInfo=null;
public InitThread(FileInfo mfileInfo){
this.mFileInfo=mfileInfo;
}
public void run() {
HttpURLConnection conn=null;
RandomAccessFile raf=null;
try{
//链接网络文件
URL url=new URL(mFileInfo.geturl());
conn=(HttpURLConnection)url.openConnection();
conn.setConnectTimeout(5000);
conn.setRequestMethod("GET");
int length=-1;
if(conn.getResponseCode()==206){
//获得文件长度
length=conn.getContentLength();
}
if(length<=0){
return;
}
//在本地创建文件
File dir=new File(SAVE_PATH);
if(!dir.exists()){
dir.mkdir();
}
File file=new File(dir,mFileInfo.getfileName());
raf=new RandomAccessFile(file,"rwd");
raf.setLength(length);
//设置文件长度,用MyHandler的对象传递Message到被继承的Handler方法中
mFileInfo.setlength(length);
Message message=Message.obtain();
message.what=MSG_INIT;
message.obj=mFileInfo;
myHandler.sendMessage(message);
}catch(Exception e){
e.printStackTrace();
}finally{
try {
raf.close();
conn.disconnect();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}