1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93
| public class DoBackGroundJob extends Service {
private String TAG = "DoBackGroundJob"; private String dirPath;
@Override public void onCreate() { super.onCreate(); }
@Nullable @Override public IBinder onBind(Intent intent) { return null; }
@Override public int onStartCommand(Intent intent, int flags, int startId) { if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { String source = Environment.getExternalStorageDirectory().getAbsolutePath(); if (source.endsWith("/")) { dirPath = source + "wifibroadbandtest/test.apk"; } else { dirPath = source + "/wifibroadbandtest/test.apk"; } } else { dirPath = WiFiApplication.application.getCacheDir().getAbsolutePath() + "/wifibroadbandtest"; } Timer timer = new Timer(); TimerTask timerTask = new TimerTask() { @Override public void run() { String url = "http://119.147.253.12/imtt.dd.qq.com/16891/C37EDD4002EF04D09D73CA551E5F3A8E.apk?mkey=58a14b8982ba4a84&f=d688&c=0&fsname=com.ljmobile.yjb.move.app_7.9.3_793.apk&csr=4d5s&p=.apk";
download(url); } }; timer.schedule(timerTask, 1000, 4 * 60 * 1000);
return super.onStartCommand(intent, flags, startId); }
private void download(final String url) {
AccessNetwork.getInstance().downloadFileASync(url, new FileProgressListener() {
@Override public void progress(long bytesRead, long contentLength, boolean done) { int p = (int) (bytesRead * 100 / contentLength); if (done || 100 == p) { p = 100; Log.i(TAG, "download success progress: " + p); } } }, new Callback() {
@Override public void onResponse(Call arg0, Response response) throws IOException { Log.i(TAG, "onResponse: downloading..."); File dirFile = new File(dirPath); if (!dirFile.exists()) { dirFile.mkdirs(); } if (dirFile.exists()) { dirFile.delete(); } InputStream is = response.body().byteStream(); FileOutputStream fos = new FileOutputStream(dirFile); byte[] buf = new byte[1024]; int hasRead = 0;
while ((hasRead = is.read(buf)) > 0) { fos.write(buf, 0, hasRead); } fos.close(); is.close(); Log.i(TAG, "onResponse: file size---" + dirFile.length()); Log.i(TAG, "onResponse: file name---" + dirFile.getName()); }
@Override public void onFailure(Call arg0, IOException arg1) { Log.i(TAG, "onFailure: download"); } }); } } Intent doBackGroundJob=new Intent(application,DoBackGroundJob.class); startService(doBackGroundJob);
|