service开个线程下载文件,并更新notification中的progressbar

activity
public class MainActivity extends Activity {

	Button btn;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btn=(Button) findViewById(R.id.btn_dwonload);
        btn.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent=new Intent(getApplicationContext(),downloadService.class);
				startService(intent);
			}
		});
    }

}
</pre><pre name="code" class="java">下载
<pre name="code" class="java">package Utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import android.util.Log;


public class downloadutils {

	HttpURLConnection conn;
	InputStream is;
	FileOutputStream fos;
	public int downloadFile(String urlString,String dir,String fileName,downloadHandler h) {
		File dirFile,file;
		dirFile=new File(dir);
		if(!dirFile.exists())dirFile.mkdir();
		String fileString=dir+"/"+fileName;
		file=new File(fileString);
		
		try {
			    if(!file.exists())file.createNewFile();
				URL url = new URL(urlString);
				conn=(HttpURLConnection)url.openConnection();
				h.setMax(conn.getContentLength());
				is=conn.getInputStream();
				fos=new FileOutputStream(file);
				byte data[]=new byte[1024];
				while(is.read(data)!=-1){
					fos.write(data);
					h.setProgerss(data.length);
				}	
			} catch (MalformedURLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}finally{
				try {
					is.close();
					fos.flush();
					fos.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		return 1;
	}
	public abstract static class downloadHandler{
		public abstract void setProgerss(int progress);
		public abstract void setMax(int max);
	}
}

 

public class downloadService extends Service{

	static final String URL_STRING="http://10.10.114.4:8080/MusicPlayer/taobao.apk";
	String dirString,fileName;
	NotificationManager manager;
	Notification notifi;
	ProgressBar progerssbar;
	TextView textview;
	int max;
	int progress=0;
	PendingIntent pi;
	RemoteViews view;
	Thread myThread;
	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return null;
	}
	Handler handler=new Handler(){
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:
				max=(Integer) msg.obj;
				view.setProgressBar(R.id.progressbar, max, progress, false);
				notifi.contentView=view;
				manager.notify(0, notifi);
				break;

			case 2:
				if(progress<=max){
	   			    progress+=(Integer)msg.obj;
				    view.setProgressBar(R.id.progressbar, max, progress, false);
				    view.setTextViewText(R.id.tv, progress*100/max+"%");
				    notifi.contentView=view;
			        
				    manager.notify(0, notifi);
				}
				else{ 
					manager.cancel(0);
				    stopSelf();
				    myThread.stop();
				}
				break;
			default:
				break;
			}
		};
	};
	@Override
	public void onCreate() {
		// TODO Auto-generated method stub
		super.onCreate();
		manager=(NotificationManager) getSystemService(Service.NOTIFICATION_SERVICE);
		notifi=new Notification(R.drawable.ic_launcher,"正在下载",System.currentTimeMillis());
		
		Intent intent=new Intent();
		pi=PendingIntent.getActivity(this, 0, intent, 0);
		
	    view =new RemoteViews(getPackageName(), R.layout.notification);
	    
	    notifi.contentIntent=pi;
	}
	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		// TODO Auto-generated method stub
		Log.i("ads", "in service");
		 myThread=new Thread(new Runnable() {
			
			@Override
			public void run() {
				// TODO Auto-generated method stub
				dirString =Environment.getExternalStorageDirectory().getPath()+"/updateDownload";
				fileName="update.apk";
				downloadutils d=new downloadutils();
				int state=d.downloadFile(URL_STRING, dirString, fileName,new downloadHandler() {
					
					@Override
					public void setProgerss(int progress) {
						// TODO Auto-generated method stub
						Message msg=new Message();
						msg.what=2;
						msg.obj=progress;
						handler.sendMessage(msg);
					}

					@Override
					public void setMax(int max) {
						// TODO Auto-generated method stub
						Message msg=new Message();
						msg.what=1;
						msg.obj=max;
						handler.sendMessage(msg);
					}
				} );
				Log.i("ads", state+"");
			}
		});
		myThread.start();
		
		return super.onStartCommand(intent, flags, startId);
	}
}

我也是新手,如有错误欢迎指出。

好像thread这样关闭不太安全.

mainactivity的xml也就一个button;

removeview的一个textview和一个progressbar;

加了个notification好像下载慢了,是错觉吗?


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值