- 不能在service中直接下载,需要开启子线程
- 在子线程中下载的信息需要传递出来,包括进度,下载完毕什么的,需要一个handler去传递
代码示意:
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import android.app.Activity;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import android.widget.Toast;
public class ImgService extends Service {
private NotificationCompat.Builder builder;
private NotificationManager manager;
private Handler handler = new Handler() {
public void handleMessage(android.os.Message msg) {
switch (msg.what) {
case -2:
Toast.makeText(getApplicationContext(), "-----网络状态异常", 0).show();
break;
case -1:
Toast.makeText(getApplicationContext(), "-----sd卡异常", 0).show();
break;
case 0:
Toast.makeText(getApplicationContext(), "-----下载成功", 0).show();
stopSelf();
break;
case 1:
builder.setProgress(100, msg.arg1, false).setContentText(msg.arg1 + "%");
manager.notify(10090, builder.build());
break;
default:
break;
}
};
};
public void onCreate() {
super.onCreate();
manager = (NotificationManager) getSystemService(Activity.NOTIFICATION_SERVICE);
builder = new NotificationCompat.Builder(getApplicationContext());
builder.setSmallIcon(R.drawable.ic_launcher).setTicker("下载").setContentTitle("数据下载中").setLargeIcon(BitmapFactory.decodeResource(getResources(),R.drawable.ic_launcher)).setWhen(System.currentTimeMillis());
};
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
final String path = intent.getStringExtra("path");
Log.i("---------", "准备");
new Thread() {
public void run() {
down(path);
};
}.start();
return super.onStartCommand(intent, flags, startId);
}
public void down(String path) {
URL url = null;
HttpURLConnection conn = null;
InputStream is = null;
FileOutputStream fos = null;
try {
url = new URL(path);
conn = (HttpURLConnection) url.openConnection();
if (conn.getResponseCode() == 200) {
is = conn.getInputStream();
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
fos = new FileOutputStream(Environment.getExternalStorageDirectory().getAbsoluteFile() + "/my.jpg");
byte[] b = new byte[1024];
int len = 0;
int totalsize = conn.getContentLength();
int temp = 0;
while ((len = is.read(b)) != -1) {
fos.write(b, 0, len);
temp += len;
Message msg = handler.obtainMessage();
msg.arg1 = (temp * 100) / totalsize;
msg.what = 1;
handler.sendMessage(msg);
}
handler.sendEmptyMessage(0);
} else {
handler.sendEmptyMessage(-1);
}
} else {
handler.sendEmptyMessage(-2);
}
is.close();
fos.close();
conn.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
}
}