我想在Service
内下载文件
新Thread
中的课程,但我无法停止Thread
。
这是我的代码:
public volatile Thread thread;
@Override
public int onStartCommand(Intent intent,int flags,int startId){
if(intent.getAction().equals(Constants.ACTION.STARTFOREGROUND_ACTION)){
downloadFile();
Intent notificationIntent=new Intent(this,ForegroundService.class);
notificationIntent.setAction(Constants.ACTION.STARTFOREGROUND_ACTION);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
|Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent pendingIntent=PendingIntent.getActivity(this,0,
notificationIntent,0);
Bitmap icon=BitmapFactory.decodeResource(getResources(),
R.mipmap.ic_launcher);
startForeground(Constants.NOTIFICATION_ID.FOREGROUND_SERVICE,
notification);
}
else if(intent.getAction().equals(
Constants.ACTION.STOPFOREGROUND_ACTION)){
thread.interrupt();
stopForeground(true);
stopSelf();
}
return START_STICKY;
}
private void downloadFile(){
thread=new Thread(){
@Override
public void run(){
try{
int count;
URL murl=new URL("http://dl.pop-music.ir/music/1395/Tir/Amir%20Farjam%20- %20Vabastatam.mp3");
URLConnection conection=murl.openConnection();
conection.connect();
// getting file length
int lenghtOfFile=conection.getContentLength();
// input stream to read file - with 8k buffer
InputStream input=new BufferedInputStream(murl.openStream(),8192);
File folder=new File(Environment.getExternalStorageDirectory()+"/Sh_M2");
if(!folder.exists()){
folder.mkdir();
}
// Output stream to write file
OutputStream output=new FileOutputStream("/sdcard/Sh_M2/"+"sag"+".mp3");
byte data[]=new byte[1024];
long total=0;
while((count=input.read(data))!=-1){
total+=count;
// publishing the progress....
// After this onProgressUpdate will be called
int prg=((int)((total*1000)/lenghtOfFile));
// writing data to file
output.write(data,0,count);
}
// flushing output
output.flush();
// closing streams
output.close();
input.close();
}catch(Exception e){
Log.e("Error: ","");
}
}
};
thread.start();
}
@Override
public void onDestroy(){
thread.interrupt();
super.onDestroy();
Log.i(LOG_TAG,"In onDestroy");
}
@Override
public IBinder onBind(Intent intent){
// Used only in case of bound services.
return null;
}
}