Procházet zdrojové kódy

下载模块。后台下载

zhaoyi před 8 roky
rodič
revize
ba9de44ee7

+ 1 - 0
app/build.gradle

@@ -35,6 +35,7 @@ dependencies {
     compile 'com.squareup.okhttp3:okhttp:3.9.1'
     compile 'org.greenrobot:eventbus:3.1.1'
     compile 'com.zhy:base-adapter:3.0.3'
+    compile 'com.liulishuo.filedownloader:library:1.6.9'
     debugCompile 'com.readystatesoftware.chuck:library:1.1.0'
     releaseCompile 'com.readystatesoftware.chuck:library-no-op:1.1.0'
 }

+ 6 - 0
app/src/main/java/com/jiuyan/sheep_children/SheepApp.java

@@ -3,6 +3,11 @@ package com.jiuyan.sheep_children;
 import android.app.Application;
 import android.content.Context;
 
+import com.liulishuo.filedownloader.FileDownloader;
+import com.liulishuo.filedownloader.connection.FileDownloadUrlConnection;
+
+import java.net.Proxy;
+
 /**
  * Created by kemllor on 2017/12/21.
  */
@@ -15,5 +20,6 @@ public class SheepApp extends Application {
     public void onCreate() {
         super.onCreate();
         mContext = getApplicationContext();
+        FileDownloader.setup(this);
     }
 }

+ 29 - 0
app/src/main/java/com/jiuyan/sheep_children/download/DownloadService.java

@@ -0,0 +1,29 @@
+package com.jiuyan.sheep_children.download;
+
+import android.app.Service;
+import android.content.Intent;
+import android.os.IBinder;
+import android.support.annotation.IntDef;
+import android.support.annotation.Nullable;
+
+/**
+ * Created by kemllor on 2017/12/26.
+ */
+
+public class DownloadService extends Service {
+    @Nullable
+    @Override
+    public IBinder onBind(Intent intent) {
+        return null;
+    }
+
+    @Override
+    public void onCreate() {
+        super.onCreate();
+    }
+
+    @Override
+    public int onStartCommand(Intent intent, int flags, int startId) {
+        return super.onStartCommand(intent, flags, startId);
+    }
+}

+ 3 - 1
app/src/main/java/com/jiuyan/sheep_children/net/Url.java

@@ -12,4 +12,6 @@ public class Url {
     public static String BIND_WX = Config.instance().mBaseUrl + "/v1/user/bindWx";
     public static String USER_INFO=Config.instance().mBaseUrl + "/v1/user/getUserInfo";
     public static String USER_COMMIT=Config.instance().mBaseUrl + "/v1/user/getDoneTask";
-}
+    public static String USER_CHECK_REGISTER=Config.instance().mBaseUrl + "/v1/task_publish/getRegisterTask";
+    public static String USER_REGISTER_TASK=Config.instance().mBaseUrl + "/v1/task_publish/registerTask";
+}

+ 89 - 139
app/src/main/java/com/jiuyan/sheep_children/page/DownloadActivity.java

@@ -12,17 +12,28 @@ import android.support.v4.content.FileProvider;
 import android.system.Os;
 import android.text.TextUtils;
 import android.view.View;
+import android.widget.ImageView;
 import android.widget.ProgressBar;
 import android.widget.TextView;
 
+import com.bumptech.glide.Glide;
 import com.jiuyan.sheep_children.R;
+import com.jiuyan.sheep_children.SheepApp;
 import com.jiuyan.sheep_children.base.BaseActivity;
 import com.jiuyan.sheep_children.net.NetManager;
+import com.jiuyan.sheep_children.page.entry.TaskPublish;
+import com.jiuyan.sheep_children.utils.FileUtil;
+import com.liulishuo.filedownloader.BaseDownloadTask;
+import com.liulishuo.filedownloader.FileDownloadListener;
+import com.liulishuo.filedownloader.FileDownloader;
+import com.liulishuo.filedownloader.connection.FileDownloadConnection;
+import com.liulishuo.filedownloader.services.DownloadMgrInitialParams;
 
 import java.io.File;
 import java.io.FileOutputStream;
 import java.io.IOException;
 import java.io.OutputStream;
+import java.io.Serializable;
 import java.nio.file.Path;
 import java.util.Date;
 
@@ -32,38 +43,30 @@ import okhttp3.OkHttpClient;
 import okhttp3.Request;
 import okhttp3.Response;
 
-import static com.jiuyan.sheep_children.page.DownloadActivity.DownloadState.DONE;
-import static com.jiuyan.sheep_children.page.DownloadActivity.DownloadState.DOWNLOADING;
-import static com.jiuyan.sheep_children.page.DownloadActivity.DownloadState.PAUSE;
-import static com.jiuyan.sheep_children.page.DownloadActivity.DownloadState.PENDING;
-
 
 /**
  * 下载界面
  * Created by kemllor on 2017/12/14.
  */
 
-public class DownloadActivity extends BaseActivity implements View.OnClickListener {
-
-
-    private static final String DOWNLOAD_URL = "https://qiniu.kuaifazs.com/fszhskp_12493_haowan_2.1.2.apk";
-
-    private OkHttpClient mClint;
+public class DownloadActivity extends BaseActivity {
 
 
-    private int mTotal;
+    private String DOWNLOAD_URL = "https://qiniu.kuaifazs.com/fszhskp_12493_haowan_2.1.2.apk";
 
-    private static final int DELTA = 4 * 1024 * 1024;
 
-    private OutputStream mDstOutputStream;
-
-    private int mCurrentDownload;
-
-    private TextView mTvDownload;
+    //    private TextView mTvDownload;
     private ProgressBar mPbDownload;
+    private ImageView mImgIcon;
+    private TextView mTvDesc;
+    private TextView mTvTitle;
+    private View mBack;
+    private TextView mTvPercent;
+
 
-    private DownloadState mState = PENDING;
     private String mPath;
+    private String mApkPath;
+    private BaseDownloadTask mDownloadTask;
 
     @Override
     protected void onCreate(@Nullable Bundle savedInstanceState) {
@@ -77,157 +80,104 @@ public class DownloadActivity extends BaseActivity implements View.OnClickListen
 
     @Override
     public void initListener() {
-        mTvDownload.setOnClickListener(this);
+        mBack.setOnClickListener(new View.OnClickListener() {
+            @Override
+            public void onClick(View v) {
+                finish();
+            }
+        });
     }
 
     @Override
     public void initData() {
-
+        mTvTitle.setText("任务下载");
+        Intent intent = getIntent();
+        TaskPublish task = (TaskPublish) intent.getSerializableExtra("data");
+        mPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/"
+                + SheepApp.mContext.getPackageName();
+        mApkPath = new File(mPath, SystemClock.currentThreadTimeMillis() + "_sheepTask.apk").getAbsolutePath();
+        if (task != null) {
+            DOWNLOAD_URL = task.getTask().getDownLoadUrl();
+            mTvDesc.setText(task.getTask().getTitle());
+            Glide.with(this)
+                    .load(task.getTask().getIcon())
+                    .placeholder(R.drawable.icon)
+                    .dontAnimate()
+                    .into(mImgIcon);
+            File file = new File(mPath);
+            if (file.exists()) {
+                FileUtil.deleteFile(file);
+            }
+            file.mkdirs();
+        }
+        startDownload();
     }
 
     @Override
     public void initView() {
-        initClient();
         findViews();
     }
 
-    private void initClient() {
-        if (mClint == null) {
-            mClint = NetManager.getInstancce(getApplicationContext());
-        }
-    }
 
     private void findViews() {
-        mTvDownload = (TextView) findViewById(R.id.tv_download);
+        mTvPercent = (TextView) findViewById(R.id.tv_percent);
         mPbDownload = (ProgressBar) findViewById(R.id.pb_download);
+        mImgIcon = (ImageView) findViewById(R.id.img_icon);
+        mTvDesc = (TextView) findViewById(R.id.tv_desc);
+        mTvTitle = (TextView) findViewById(R.id.tv_title);
+        mBack = findViewById(R.id.img_back);
     }
 
-    @Override
-    public void onClick(View v) {
-        if (R.id.tv_download == v.getId()) {
-            switch (mState) {
-                case PENDING:
-                    startDownloadSelf();
-                    mState = DOWNLOADING;
-                    break;
-                case DOWNLOADING:
-                    mState = PAUSE;
-                    break;
-                case PAUSE:
-                    mState = DOWNLOADING;
-                    downloadRange(mCurrentDownload);
-                    break;
-                case DONE:
-                    if (!TextUtils.isEmpty(mPath)) {
-                        installApk(mPath);
-                    }
-                    break;
-            }
-            refreshButton();
-        }
-    }
 
-    public enum DownloadState {
-        PENDING,
-        DOWNLOADING,
-        PAUSE,
-        DONE
-    }
-
-
-    private void refreshButton() {
-        switch (mState) {
-            case DOWNLOADING:
-                mTvDownload.setText(R.string.pause);
-                break;
-            case PENDING:
-                mTvDownload.setText(R.string.start_download);
-                break;
-            case PAUSE:
-                mTvDownload.setText(R.string.resume);
-                break;
-            case DONE:
-                mTvDownload.setText(R.string.done);
-                break;
-        }
-    }
-
-    //开始下载
-    private void startDownloadSelf() {
-        getFileLength(DOWNLOAD_URL, new Callback() {
-            @Override
-            public void onFailure(Call call, IOException e) {
+    private void startDownload() {
+        if (mDownloadTask == null)
+            mDownloadTask = FileDownloader.getImpl()
+                    .create(DOWNLOAD_URL)
+                    .setPath(mApkPath, false)
+                    .setCallbackProgressTimes(300)
+                    .setMinIntervalUpdateSpeed(400)
+                    .setListener(new FileDownloadListener() {
+                        @Override
+                        protected void pending(BaseDownloadTask task, int soFarBytes, int totalBytes) {
+                        }
 
-            }
+                        @Override
+                        protected void progress(BaseDownloadTask task, int soFarBytes, int totalBytes) {
+                            int percent = (int) ((double) soFarBytes / (double) totalBytes * 100);
+                            mPbDownload.setProgress(percent);
+                            mTvPercent.setText(percent + "%");
+                        }
 
-            @Override
-            public void onResponse(Call call, Response response) throws IOException {
-                if (response.isSuccessful()) {
-                    //获取下载文件长度
-                    mTotal = Integer.valueOf(response.header("Content-Length"));
-                    mPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
-                            .getAbsolutePath() + "/" + SystemClock.currentThreadTimeMillis() + "sheepTask.apk";
-                    mDstOutputStream = new FileOutputStream(mPath);
-                    downloadRange(0);
-                }
-            }
-        });
-    }
+                        @Override
+                        protected void blockComplete(BaseDownloadTask task) {
 
-    //获取文件大小
-    private void getFileLength(String url, Callback callback) {
-        Request request = new Request.Builder()
-                .url(url)
-                .method("HEAD", null).build();
+                        }
 
-        mClint.newCall(request).enqueue(callback);
-    }
+                        @Override
+                        protected void completed(BaseDownloadTask task) {
+                            installApk(mApkPath);
+                            mTvPercent.setText("100%");
+                        }
 
-    private void downloadRange(int start) {
-        Request request = new Request.Builder()
-                .url(DOWNLOAD_URL)
-                .addHeader("range", "bytes=" + start + "-" + Math.min(start + DELTA, mTotal)).build();
+                        @Override
+                        protected void paused(BaseDownloadTask task, int soFarBytes, int totalBytes) {
 
-        mClint.newCall(request).enqueue(new Callback() {
-            @Override
-            public void onFailure(Call call, IOException e) {
+                        }
 
-            }
+                        @Override
+                        protected void error(BaseDownloadTask task, Throwable e) {
+                            e.printStackTrace();
+                        }
 
-            @Override
-            public void onResponse(Call call, Response response) throws IOException {
-                if (response.isSuccessful() && mState == DOWNLOADING) {
-                    final byte[] bytes = response.body().bytes();
-                    mDstOutputStream.write(bytes);
-                    mCurrentDownload += bytes.length;
-                    mPbDownload.post(new Runnable() {
                         @Override
-                        public void run() {
-                            int progress = (int) (mCurrentDownload * 1.0 / mTotal * 100);
-                            mPbDownload.setProgress(progress);
-
-                            if (100 == progress) {
-                                mState = DONE;
-                                refreshButton();
-                                if (!TextUtils.isEmpty(mPath)) {
-                                    installApk(mPath);
-                                }
-                            }
+                        protected void warn(BaseDownloadTask task) {
                         }
                     });
 
-                    if (mCurrentDownload >= mTotal) {
-                        mDstOutputStream.flush();
-                        mDstOutputStream.close();
-                        return;
-                    }
-
-                    downloadRange(mCurrentDownload);
-                }
-            }
-        });
+        mDownloadTask.start();
     }
 
+
     public void installApk(String path) {
         File file = new File(path);
         Intent intent = new Intent(Intent.ACTION_VIEW);

+ 62 - 5
app/src/main/java/com/jiuyan/sheep_children/page/MainActivity.java

@@ -2,6 +2,7 @@ package com.jiuyan.sheep_children.page;
 
 import android.Manifest;
 import android.app.Activity;
+import android.content.DialogInterface;
 import android.content.Intent;
 import android.content.pm.PackageManager;
 import android.graphics.Point;
@@ -10,9 +11,11 @@ import android.os.Bundle;
 import android.provider.Settings;
 import android.support.v4.app.ActivityCompat;
 import android.support.v4.content.ContextCompat;
+import android.support.v7.app.AlertDialog;
 import android.support.v7.widget.AppCompatAutoCompleteTextView;
 import android.support.v7.widget.LinearLayoutManager;
 import android.support.v7.widget.RecyclerView;
+import android.text.TextUtils;
 import android.view.LayoutInflater;
 import android.view.View;
 import android.view.ViewGroup;
@@ -66,6 +69,8 @@ public class MainActivity extends BaseActivity implements View.OnClickListener {
     private TextView mHostry;
     private TextView mToday;
     private ImageView mDown;
+    private AlertDialog mDialog;
+    private TaskPublish mClickItem;
 
 
     @Override
@@ -135,9 +140,8 @@ public class MainActivity extends BaseActivity implements View.OnClickListener {
         mAdapter.setClickCallBack(new TaskAdapter.ItemClickCallBack<TaskPublish>() {
             @Override
             public void onItemClick(TaskPublish pos) {
-                Intent intent = new Intent(MainActivity.this, DownloadActivity.class);
-                intent.putExtra("data", pos.getTask().getDownLoadUrl());
-                startActivity(intent);
+                mClickItem = pos;
+                checkUserTask();
             }
         });
         mRecyclerView.setAdapter(mAdapter);
@@ -156,6 +160,59 @@ public class MainActivity extends BaseActivity implements View.OnClickListener {
         mRecyclerView.setLoadingMoreEnabled(false);
     }
 
+    private void checkUserTask() {
+        HashMap<String, String> map = new HashMap<>();
+        map.put("wx_open_id", SpUtils.getOpenId(this));
+        NetManager.get(Url.USER_CHECK_REGISTER, map, getApplicationContext(), new SheepCallback<String>(this) {
+            @Override
+            public void success(String ok) {
+                if (TextUtils.equals(ok, "ok")) {
+                    showDialog("是否接受任务?");
+                } else {
+                    showDialog("你有任务正在进行,是否取消,接受新任务?");
+                }
+            }
+        });
+    }
+
+    private void showDialog(String msg) {
+        if (mDialog == null) {
+            mDialog = new AlertDialog.Builder(MainActivity.this)
+                    .setMessage(msg)
+                    .setNegativeButton("取消", new DialogInterface.OnClickListener() {
+                        @Override
+                        public void onClick(DialogInterface dialog, int which) {
+                            mDialog.dismiss();
+                        }
+                    }).setPositiveButton("确认", new DialogInterface.OnClickListener() {
+                        @Override
+                        public void onClick(DialogInterface dialog, int which) {
+                            registerTask();
+                        }
+                    }).create();
+            mDialog.show();
+        } else {
+            mDialog.setMessage(msg);
+            mDialog.show();
+        }
+    }
+
+    //获取任务
+    private void registerTask() {
+        HashMap<String, String> map = new HashMap<>();
+        map.put("wx_open_id", SpUtils.getOpenId(this));
+        map.put("task_id", mClickItem.getTask().getId() + "");
+        NetManager.get(Url.USER_REGISTER_TASK, map, getApplicationContext(), new SheepCallback<String>(this) {
+            @Override
+            public void success(String o) {
+                initData();
+                Intent intent = new Intent(MainActivity.this, DownloadActivity.class);
+                intent.putExtra("data", mClickItem);
+                startActivity(intent);
+            }
+        });
+    }
+
     private void requestPermission() {
         boolean has = PremissUtils.hasPermission(this);
         if (!has) {
@@ -216,9 +273,9 @@ public class MainActivity extends BaseActivity implements View.OnClickListener {
                 break;
             case R.id.img_down:
                 if (SpUtils.isLogin(getApplicationContext())) {
-                    intent = new Intent(MainActivity.this, UserCenterActivity.class);
-                } else {
                     intent = new Intent(MainActivity.this, DownloadActivity.class);
+                } else {
+                    intent = new Intent(MainActivity.this, LoginActivity.class);
                 }
                 startActivity(intent);
                 break;

+ 24 - 0
app/src/main/java/com/jiuyan/sheep_children/utils/FileUtil.java

@@ -0,0 +1,24 @@
+package com.jiuyan.sheep_children.utils;
+
+import java.io.File;
+
+/**
+ * Created by kemllor on 2017/12/26.
+ */
+
+public class FileUtil {
+
+    public static void deleteFile(File file) {
+        if (file.exists()) { // 判断文件是否存在
+            if (file.isFile()) { // 判断是否是文件
+                file.delete(); // delete()方法 你应该知道 是删除的意思;
+            } else if (file.isDirectory()) { // 否则如果它是一个目录
+                File files[] = file.listFiles(); // 声明目录下所有的文件 files[];
+                for (int i = 0; i < files.length; i++) { // 遍历目录下所有的文件
+                    deleteFile(files[i]); // 把每个文件 用这个方法进行迭代
+                }
+            }
+            file.delete();
+        }
+    }
+}

binární
app/src/main/res/drawable-hdpi/down_load.png


+ 21 - 12
app/src/main/res/layout/download_activity.xml

@@ -4,9 +4,13 @@
               android:layout_height="match_parent"
               android:orientation="vertical">
 
+    <include
+        layout="@layout/title"/>
+
     <RelativeLayout
         android:layout_width="match_parent"
-        android:layout_height="70dp">
+        android:layout_height="50dp"
+        android:layout_marginTop="10dp">
 
 
         <ImageView
@@ -15,29 +19,38 @@
             android:layout_height="50dp"
             android:layout_centerVertical="true"
             android:layout_marginLeft="10dp"
-            android:src="@drawable/icon"/>
+            />
 
         <TextView
-            android:layout_centerVertical="true"
             android:id="@+id/tv_desc"
             android:layout_width="wrap_content"
             android:layout_height="wrap_content"
+            android:layout_centerVertical="true"
             android:layout_marginLeft="5dp"
             android:layout_toRightOf="@id/img_icon"
-            android:text="某某游戏"
             android:textColor="@color/black_dark"/>
 
+        <!-- <TextView
+             android:id="@+id/tv_download"
+             android:layout_width="wrap_content"
+             android:layout_height="wrap_content"
+             android:layout_alignParentRight="true"
+             android:layout_centerVertical="true"
+             android:layout_marginRight="10dp"
+             android:background="@color/theme"
+             android:padding="5dp"
+             android:text="下载"
+             android:textColor="@color/white"/>-->
         <TextView
-            android:id="@+id/tv_download"
+            android:id="@+id/tv_percent"
             android:layout_width="wrap_content"
             android:layout_height="wrap_content"
+            android:layout_alignParentBottom="true"
             android:layout_alignParentRight="true"
             android:layout_centerVertical="true"
             android:layout_marginRight="10dp"
-            android:background="@color/theme"
             android:padding="5dp"
-            android:text="下载"
-            android:textColor="@color/white"/>
+            android:textColor="@color/theme"/>
     </RelativeLayout>
 
 
@@ -49,8 +62,4 @@
         android:layout_marginLeft="10dp"
         android:layout_marginRight="10dp"/>
 
-    <include
-        layout="@layout/line_h_1px"/>
-
-
 </LinearLayout>

+ 5 - 4
app/src/main/res/layout/task_head.xml

@@ -14,8 +14,8 @@
             android:id="@+id/tv_withdraw"
             android:layout_width="wrap_content"
             android:layout_height="wrap_content"
-            android:layout_alignParentBottom="true"
             android:layout_alignParentRight="true"
+            android:layout_centerVertical="true"
             android:layout_marginBottom="10dp"
             android:layout_marginRight="5dp"
             android:text="提现"
@@ -24,12 +24,13 @@
 
         <ImageView
             android:id="@+id/img_down"
-            android:layout_width="wrap_content"
-            android:layout_height="wrap_content"
+            android:layout_width="30dp"
+            android:layout_height="30dp"
             android:layout_alignParentRight="true"
             android:layout_marginTop="5dp"
             android:padding="5dp"
-            android:src="@android:drawable/stat_sys_download"/>
+            android:visibility="gone"
+            android:src="@drawable/down_load"/>
 
         <TextView
             android:id="@+id/title"

+ 3 - 2
app/src/main/res/layout/task_item.xml

@@ -11,9 +11,10 @@
         android:background="@color/backgroud">
 
         <ImageView
+            android:layout_margin="5dp"
             android:id="@+id/img_icon"
-            android:layout_width="55dp"
-            android:layout_height="55dp"
+            android:layout_width="50dp"
+            android:layout_height="50dp"
             android:layout_centerVertical="true"
             android:src="@drawable/icon"/>
 

+ 1 - 1
app/src/main/res/values/colors.xml

@@ -2,7 +2,7 @@
 <resources>
     <color name="colorPrimary">#3F51B5</color>
     <color name="colorPrimaryDark">#303F9F</color>
-    <color name="colorAccent">#FF4081</color>
+    <color name="colorAccent">#ff842c</color>
     <color name="theme">#ff842c</color>
     <color name="translate">#00ffffff</color>
     <color name="white">#ffffff</color>