import android.app.Notification;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.widget.ImageView;
import android.widget.Toast;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class DownloadService extends Service {
public static final String URL_PATH =
"DownloadService_URL";
private Notification.Builder notificationBuilder;
private NotificationManager notificationManager;
private ImageView imageView;
private Handler handler =
new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
if(msg.what ==
1){
stopSelf();
Bundle bundle = msg.getData();
byte[] data= bundle.getByteArray(
"data");
Toast.makeText(getApplicationContext(),
"下载完成" + data, Toast.LENGTH_LONG).show();
}
}
};
public DownloadService() {
}
@Override
public IBinder
onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notificationBuilder =
new Notification.Builder(getApplicationContext());
notificationBuilder.setSmallIcon(R.drawable.nav_task).setTicker(
"下载").setContentTitle(
"加载网络数据").setContentText(
"正在加载中…").setAutoCancel(
true);
}
@Override
public int onStartCommand(Intent intent,
int flags,
int startId) {
final String PATH = intent.getStringExtra(URL_PATH);
new Thread(
new Runnable() {
@Override
public void run() {
HttpURLConnection connection =
null;
ByteArrayOutputStream arrayOutputStream =
new ByteArrayOutputStream();
int len =
0;
int len_data =
0;
byte[] data =
new byte[
128];
try {
URL url =
new URL(PATH);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod(
"GET");
connection.setConnectTimeout(
8000);
connection.setReadTimeout(
8000);
InputStream inputStream = connection.getInputStream();
int len_long = connection.getContentLength();
while ((len = inputStream.read(data)) != -
1) {
arrayOutputStream.write(data,
0, data.length);
len_data += len;
int progress_value = (
int) ((len_data / (
float) len_long) *
100);
notificationBuilder.setProgress(
100, progress_value,
false);
notificationManager.notify(
1000, notificationBuilder.build());
}
notificationBuilder.setContentText(
"下载完成!");
notificationManager.notify(
1000, notificationBuilder.build());
Bundle bundle =
new Bundle();
bundle.putByteArray(
"data",arrayOutputStream.toByteArray());
Message msg =
new Message();
msg.setData(bundle);
msg.what =
1;
handler.sendMessage(msg);
}
catch (Exception e) {
e.printStackTrace();
}
}
}).start();
return START_REDELIVER_INTENT;
}
@Override
public void onDestroy() {
super.onDestroy();
}
}
转载请注明原文地址: https://ju.6miu.com/read-6249.html