diff --git a/app/build.gradle b/app/build.gradle index 3cb11e5..443bbfc 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -1,7 +1,7 @@ apply plugin: 'com.android.application' def appName() { - return "应用市场" + return "UIUIAPPStore" } def releaseTime() { @@ -18,6 +18,18 @@ android { versionCode 1 versionName "1.0" testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" + //极光 + ndk { + //选择要添加的对应 cpu 类型的 .so 库。 + abiFilters 'armeabi', 'armeabi-v7a', 'arm64-v8a' + // 还可以添加 'x86', 'x86_64', 'mips', 'mips64' + } + + manifestPlaceholders = [ + JPUSH_PKGNAME: applicationId, + JPUSH_APPKEY : "d7ad4da7d65687b32cacbdb1", //JPush 上注册的包名对应的 Appkey. + JPUSH_CHANNEL: "developer-default", //暂时填写默认值即可. + ] } lintOptions { checkReleaseBuilds false @@ -25,16 +37,16 @@ android { //签名 signingConfigs { debug { - storeFile file("src/keys/SchoolEbaiFeng.jks") + storeFile file("src/keys/xueshibaoos.jks") storePassword "123456" - keyAlias "key0" + keyAlias "xueshibaoos" keyPassword "123456" v2SigningEnabled false } release {// 签名文件 - storeFile file("src/keys/SchoolEbaiFeng.jks") + storeFile file("src/keys/xueshibaoos.jks") storePassword "123456" - keyAlias "key0" + keyAlias "xueshibaoos" keyPassword "123456" v2SigningEnabled false } @@ -98,13 +110,16 @@ dependencies { implementation 'com.github.bumptech.glide:glide:4.10.0' annotationProcessor 'com.github.bumptech.glide:compiler:4.10.0' - +//aria implementation 'com.arialyy.aria:core:3.7.7' annotationProcessor 'com.arialyy.aria:compiler:3.7.7' //OKGO - implementation 'com.lzy.net:okgo:2.1.4' - implementation 'com.lzy.net:okrx:0.1.2' - implementation 'com.lzy.net:okserver:1.1.3' + //必须使用 + implementation 'com.lzy.net:okgo:3.0.4' + //以下三个选择添加,okrx和okrx2不能同时使用 + implementation 'com.lzy.net:okrx:1.0.2' +// compile 'com.lzy.net:okrx2:2.0.2' + implementation 'com.lzy.net:okserver:2.0.5' implementation 'com.alibaba:fastjson:1.2.21' @@ -123,4 +138,8 @@ dependencies { androidTestImplementation 'androidx.test.ext:junit:1.1.0' androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.1' implementation 'androidx.cardview:cardview:1.0.0' + //极光推送 + implementation 'cn.jiguang.sdk:jpush:3.4.1' // 此处以JPush 3.4.1 版本为例。 + implementation 'cn.jiguang.sdk:jcore:2.2.4' // 此处以JCore 2.2.4 版本为例。 + } diff --git a/app/src/keys/SchoolEbaiFeng.jks b/app/src/keys/SchoolEbaiFeng.jks deleted file mode 100644 index 367b25e..0000000 Binary files a/app/src/keys/SchoolEbaiFeng.jks and /dev/null differ diff --git a/app/src/keys/xueshibaoos.jks b/app/src/keys/xueshibaoos.jks new file mode 100644 index 0000000..b94a626 Binary files /dev/null and b/app/src/keys/xueshibaoos.jks differ diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index 3394e38..f564d81 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -1,21 +1,49 @@ - - - - - + xmlns:tools="http://schemas.android.com/tools" + package="com.appstore.uiui" + android:sharedUserId="android.uid.system"> + + + + + + + + + + + + + + + + + + + + + android:theme="@style/AppTheme" + tools:ignore="GoogleAppIndexingWarning"> + + + + + + @@ -23,6 +51,162 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/app/src/main/aidl/com/appstore/uiui/IMyAidlInterface.aidl b/app/src/main/aidl/com/appstore/uiui/IMyAidlInterface.aidl deleted file mode 100644 index 7cd4693..0000000 --- a/app/src/main/aidl/com/appstore/uiui/IMyAidlInterface.aidl +++ /dev/null @@ -1,13 +0,0 @@ -// IMyAidlInterface.aidl -package com.appstore.uiui; - -// Declare any non-default types here with import statements - -interface IMyAidlInterface { - /** - * Demonstrates some basic types that you can use as parameters - * and return values in AIDL. - */ - void basicTypes(int anInt, long aLong, boolean aBoolean, float aFloat, - double aDouble, String aString); -} diff --git a/app/src/main/aidl/com/appstore/uiui/KeepAliveConnection.aidl b/app/src/main/aidl/com/appstore/uiui/KeepAliveConnection.aidl new file mode 100644 index 0000000..06d1fa9 --- /dev/null +++ b/app/src/main/aidl/com/appstore/uiui/KeepAliveConnection.aidl @@ -0,0 +1,7 @@ +// KeepAliveConnection.aidl +package com.appstore.uiui; + +// Declare any non-default types here with import statements + +interface KeepAliveConnection { +} diff --git a/app/src/main/java/com/appstore/uiui/MyApplication.java b/app/src/main/java/com/appstore/uiui/MyApplication.java index 1357d49..17de47a 100644 --- a/app/src/main/java/com/appstore/uiui/MyApplication.java +++ b/app/src/main/java/com/appstore/uiui/MyApplication.java @@ -3,15 +3,22 @@ package com.appstore.uiui; import android.app.Application; import android.content.Context; import android.content.pm.ApplicationInfo; +import android.content.pm.PackageManager; import android.os.Handler; import android.os.Looper; +import android.provider.Settings; import android.util.Log; import androidx.annotation.NonNull; +import com.appstore.uiui.jpush.Logger; +import com.appstore.uiui.utils.ApkUtils; +import com.appstore.uiui.utils.LogUtils; import com.appstore.uiui.utils.ToastUtil; -import com.arialyy.aria.core.Aria; import com.lzy.okgo.OkGo; +import com.lzy.okgo.callback.FileCallback; +import com.lzy.okgo.model.Progress; +import com.lzy.okgo.model.Response; import com.scwang.smartrefresh.layout.SmartRefreshLayout; import com.scwang.smartrefresh.layout.api.DefaultRefreshFooterCreator; import com.scwang.smartrefresh.layout.api.DefaultRefreshHeaderCreator; @@ -21,11 +28,22 @@ import com.scwang.smartrefresh.layout.api.RefreshLayout; import com.scwang.smartrefresh.layout.footer.ClassicsFooter; import com.scwang.smartrefresh.layout.header.ClassicsHeader; +import org.json.JSONException; +import org.json.JSONObject; + +import java.io.File; + +import cn.jpush.android.api.CustomMessage; +import cn.jpush.android.api.JPushInterface; + /** * Created by asus on 2017/10/27. */ public class MyApplication extends Application { + private static final String TAG = "JIGUANG-Example"; + + private static MyApplication app; public static MyApplication getInstance() { @@ -56,12 +74,18 @@ public class MyApplication extends Application { @Override public void onCreate() { super.onCreate(); + Logger.d(TAG, "[ExampleApplication] onCreate"); + JPushInterface.setDebugMode(true); // 设置开启日志,发布时请关闭日志 + JPushInterface.init(this); // 初始化 JPush app = this; ToastUtil.init(this); - OkGo.getInstance().init(this); + OkGo.getInstance().init(this) + .setRetryCount(10)//重试次数 + ; + // AppUtil.getInstalledApp(this); - Aria.init(this); - Aria.download(this).register(); +// Aria.init(this); +// Aria.download(this).register(); if (!isDebug(this)) { catchException(); } @@ -77,7 +101,7 @@ public class MyApplication extends Application { Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() { @Override public void uncaughtException(@NonNull Thread t, @NonNull Throwable e) { - Log.d("捕获异常子线程:", Thread.currentThread().getName() + + LogUtils.d("捕获异常子线程:", Thread.currentThread().getName() + "在:" + e.getStackTrace()[0].getClassName()); } } @@ -90,14 +114,274 @@ public class MyApplication extends Application { try { Looper.loop(); //会先执行这个方法,然后在执行下面的异常捕获方法! } catch (Exception e) { - Log.d("捕获异常主线程:", Thread.currentThread().getName() + "在:" + e.getStackTrace()[0].getClassName()); + LogUtils.d("捕获异常主线程:", Thread.currentThread().getName() + "在:" + e.getStackTrace()[0].getClassName()); e.printStackTrace(); } } } }); } - public static Context getAppContext() { - return getAppContext(); + + public Context getAppContext() { + return getApplicationContext(); } + + //定义接收极光推送消息的类型 + // 3.数据线传输管控 + // 4.TF卡管控 + // 5.蓝牙管控 + // 6.浏览器上网管控 + // 7.应用联网管控 + // 8.应用锁管控 + // 9.强制安装应用 + // 10.强制卸载应用 + + private static final String JIGUANG_USB_STATE = "3"; + private static final String JIGUANG_TFCARD_STATE = "4"; + private static final String JIGUANG_BLUETOOTH_STATE = "5"; + private static final String JIGUANG_BROWSER_URLPATH = "6"; + private static final String JIGUANG_APP_NETWORKSTATE = "7"; + private static final String JIGUANG_APP_LOCKEDSTATE = "8"; + private static final String JIGUANG_FORCE_INSTALLAPK = "9"; + private static final String JIGUANG_FORCE_UNINSTALLAPK = "10"; + + synchronized public void manageCustomMessage(CustomMessage customMessage) { + if (customMessage == null) { + LogUtils.e("jiguang", "customMessage is NULL"); + } else { + String MESSAGE = customMessage.message; + //MESSAGE用作判断 + String TITLE = customMessage.title; + String CONTENT_TYPE = customMessage.contentType; + String EXTRA = customMessage.extra; + LogUtils.e("EXTRA", EXTRA); + switch (MESSAGE) { + case JIGUANG_USB_STATE: + setUsbState(EXTRA); + break; + case JIGUANG_TFCARD_STATE: + setTfcardState(EXTRA); + break; + case JIGUANG_BLUETOOTH_STATE: + setBluetoothState(EXTRA); + break; + case JIGUANG_BROWSER_URLPATH: + setBrowserUrlpath(EXTRA); + break; + case JIGUANG_APP_NETWORKSTATE: + setAppNetworkstate(EXTRA); + break; + case JIGUANG_APP_LOCKEDSTATE: + setAppLockedstate(EXTRA); + break; + case JIGUANG_FORCE_INSTALLAPK: + intallApk(EXTRA); + break; + case JIGUANG_FORCE_UNINSTALLAPK: + ToastUtil.debugShow("收到应用卸载消息"); + unintallApk(EXTRA); + break; + } + + + } + } + + synchronized private void defaults(String jsonArray) { + if (jsonArray.length() > 0) { + try { + JSONObject extra = new JSONObject(jsonArray); + String packageName = extra.getString("package"); + int is_network = extra.getInt("is_network"); + } catch (JSONException e) { + e.printStackTrace(); + LogUtils.e("defaults", e.getMessage()); + } + } else { + ToastUtil.debugShow("defaults jsonArray is NULL"); + } + } + + //USB数据功能管控 + //仅充电:usb_charge + //MTP模式:usb_mtp + //Midi模式:usb_midi + synchronized private void setUsbState(String jsonArray) { + if (jsonArray.length() > 0) { + try { + JSONObject extra = new JSONObject(jsonArray); + int is_dataline = extra.getInt("is_dataline"); + if (is_dataline == 1) { + boolean qch_usb_choose = Settings.System.putString(getContentResolver(), "qch_usb_choose", "usb_charge"); + LogUtils.e("setUsbState:", Settings.System.getString(getContentResolver(), "qch_usb_choose")); + } else { + boolean qch_usb_choose = Settings.System.putString(getContentResolver(), "qch_usb_choose", "usb_mtp"); + LogUtils.e("setUsbState:", Settings.System.getString(getContentResolver(), "qch_usb_choose")); + } + } catch (JSONException e) { + e.printStackTrace(); + LogUtils.e("setUsbState", e.getMessage()); + } + } else { + ToastUtil.debugShow("setUsbState jsonArray is NULL"); + } + } + + synchronized private void setTfcardState(String jsonArray) { + if (jsonArray.length() > 0) { + try { + JSONObject extra = new JSONObject(jsonArray); + int is_tf = extra.getInt("is_tf"); + boolean qch_sdcard_forbid_on = Settings.System.putInt(getContentResolver(), "qch_sdcard_forbid_on", is_tf); + if (qch_sdcard_forbid_on) { + LogUtils.e("setTfcardState:", Settings.System.getString(getContentResolver(), "qch_sdcard_forbid_on")); + } else { + ToastUtil.debugShow("setTfcardState failed,state:" + is_tf); + } + } catch (JSONException e) { + e.printStackTrace(); + LogUtils.e("setTfcardState", e.getMessage()); + } + } else { + ToastUtil.debugShow("setTfcardState jsonArray is NULL"); + } + } + + synchronized private void setBluetoothState(String jsonArray) { + if (jsonArray.length() > 0) { + try { + JSONObject extra = new JSONObject(jsonArray); + int is_bluetooth = extra.getInt("is_bluetooth"); + boolean qch_bt_forbid_on = Settings.System.putInt(getContentResolver(), "qch_bt_forbid_on", is_bluetooth); + if (qch_bt_forbid_on) { + LogUtils.e("setBluetoothState:", Settings.System.getString(getContentResolver(), "qch_bt_forbid_on")); + } else { + ToastUtil.debugShow("setBluetoothState failed,state:" + is_bluetooth); + } + } catch (JSONException e) { + e.printStackTrace(); + LogUtils.e("setBluetoothState", e.getMessage()); + } + } else { + ToastUtil.debugShow("setBluetoothState jsonArray is NULL"); + } + } + + synchronized private void setBrowserUrlpath(String jsonArray) { + if (jsonArray.length() > 0) { + try { + JSONObject extra = new JSONObject(jsonArray); + String browser = extra.getString("browser"); + boolean setBrowserUrlpath = Settings.System.putString(getContentResolver(), "DeselectBrowserArray", browser); + LogUtils.e("setBrowserUrlpath:", String.valueOf(setBrowserUrlpath)); + if (setBrowserUrlpath) { + LogUtils.e("getBrowserUrlpath:", Settings.System.getString(getContentResolver(), "DeselectBrowserArray")); + } else { + ToastUtil.debugShow("setBrowserUrlpath failed,url:" + browser); + } + } catch (JSONException e) { + e.printStackTrace(); + LogUtils.e("setBrowserUrlpath", e.getMessage()); + } + } else { + boolean setBrowserUrlpath = Settings.System.putString(getContentResolver(), "DeselectBrowserArray", "invalid"); + + ToastUtil.debugShow("setBrowserUrlpath jsonArray is NULL,set default: " + setBrowserUrlpath); + } + } + + synchronized private void setAppNetworkstate(String jsonArray) { + if (jsonArray.length() > 0) { + try { + JSONObject extra = new JSONObject(jsonArray); + String packageName = extra.getString("package"); + int is_network = extra.getInt("is_network"); + if (is_network == 1) { +// Settings.System.putString(getContentResolver(), "qch_jgy_network_disallow", net_not); + + } else { + + } + } catch (JSONException e) { + e.printStackTrace(); + LogUtils.e("setAppNetworkstate", e.getMessage()); + } + } else { + ToastUtil.debugShow("setAppNetworkstate jsonArray is NULL"); + } + } + + synchronized private void setAppLockedstate(String jsonArray) { + if (jsonArray.length() > 0) { + try { + JSONObject extra = new JSONObject(jsonArray); + String packageName = extra.getString("package"); + int is_lock = extra.getInt("is_lock"); + ToastUtil.debugShow("收到应用锁管控消息:包名" + packageName + "is_lock_state:" + is_lock); + PackageManager pm = getPackageManager(); + //后台为0可能传过来null + if (is_lock == 1) { + pm.setApplicationEnabledSetting(packageName, PackageManager.COMPONENT_ENABLED_STATE_DEFAULT, 0); + } else { + pm.setApplicationEnabledSetting(packageName, PackageManager.COMPONENT_ENABLED_STATE_DISABLED, 0); + } + } catch (JSONException e) { + e.printStackTrace(); + LogUtils.e("setAppLockedstate", e.getMessage()); + } + } else { + ToastUtil.debugShow("setAppLockedstate jsonArray is NULL"); + } + + } + + //静默安装应用,使用okgo,断网会出现问题,等待修改使用aria + synchronized private void intallApk(String jsondata) { + try { + JSONObject extra = new JSONObject(jsondata); + final String packages = extra.getString("package"); + ToastUtil.debugShow("收到应用安装消息:包名" + packages); + String url = extra.getString("url"); + OkGo.get(url) + .execute(new FileCallback() { + @Override + public void onSuccess(Response response) { +// Settings.System.putString(getApplicationContext().getContentResolver(), "qch_app_forbid", "com.baidu.video"); + ApkUtils.installApkInSilence(response.body().getAbsolutePath(), packages); + LogUtils.e("onSuccess", "download file successful,now installing"); + } + + @Override + public void onError(Response response) { + super.onError(response); + LogUtils.e("manageCustomMessage", "File download Failure"); + } + + @Override + public void downloadProgress(Progress progress) { + super.downloadProgress(progress); + LogUtils.e("downloadProgress", "已下载:" + progress.currentSize + ",总大小:" + progress.totalSize + ",进度:" + progress.fraction + ",当前网速:" + progress.speed); + } + }); + + } catch (JSONException e) { + e.printStackTrace(); + LogUtils.e("intallApk", e.getMessage()); + } + } + + synchronized private void unintallApk(String json) { + try { + JSONObject object = new JSONObject(json); + String packageName = object.getString("package"); + ToastUtil.debugShow("收到应用卸载消息:包名" + packageName); + if (!packageName.equals("")) { + ApkUtils.deleteApkInSilence(packageName); + } + } catch (JSONException e) { + e.printStackTrace(); + LogUtils.e("unintallApk", e.getMessage()); + } + } + } diff --git a/app/src/main/java/com/appstore/uiui/TextCode/MessageWhat.java b/app/src/main/java/com/appstore/uiui/TextCode/MessageWhat.java new file mode 100644 index 0000000..e2d2427 --- /dev/null +++ b/app/src/main/java/com/appstore/uiui/TextCode/MessageWhat.java @@ -0,0 +1,6 @@ +package com.appstore.uiui.TextCode; + +public class MessageWhat { + public static int CODE_SUCCESSFUL = 200; + +} diff --git a/app/src/main/java/com/appstore/uiui/activity/DetailsActivity.java b/app/src/main/java/com/appstore/uiui/activity/DetailsActivity.java new file mode 100644 index 0000000..8445f9d --- /dev/null +++ b/app/src/main/java/com/appstore/uiui/activity/DetailsActivity.java @@ -0,0 +1,116 @@ +package com.appstore.uiui.activity; + +import android.view.View; +import android.widget.ImageView; +import android.widget.RatingBar; +import android.widget.TextView; + +import androidx.recyclerview.widget.LinearLayoutManager; +import androidx.recyclerview.widget.RecyclerView; + +import com.appstore.uiui.R; +import com.appstore.uiui.adapter.ImageAdapter; +import com.appstore.uiui.base.BaseActivity; +import com.appstore.uiui.bean.AppInfo; +import com.appstore.uiui.helper.CustomSnapHelper; +import com.appstore.uiui.listener.LogDownloadListener; +import com.appstore.uiui.utils.ApkUtils; +import com.appstore.uiui.utils.ToastUtil; +import com.bumptech.glide.Glide; +import com.lzy.okgo.OkGo; +import com.lzy.okgo.request.GetRequest; +import com.lzy.okserver.OkDownload; + +import java.io.File; +import java.util.ArrayList; +import java.util.List; + +public class DetailsActivity extends BaseActivity { + private TextView tv_title, tv_name, tv_company, tv_update_time, tv_version, tv_content, tv_download; + private RatingBar rating_bar; + private ImageView iv_icon; + private RecyclerView rv_image; + private AppInfo appInfo; + private ImageAdapter imageAdapter; + + @Override + protected int setLayoutResourceID() { + return R.layout.activity_details; + } + + @Override + protected void initView() { + tv_title = findViewById(R.id.detail_tv_title); + tv_name = findViewById(R.id.detail_tv_name); + tv_company = findViewById(R.id.detail_tv_company); + tv_update_time = findViewById(R.id.detail_tv_update_time); + tv_version = findViewById(R.id.detail_tv_version); + tv_content = findViewById(R.id.detali_tv_content); + tv_download = findViewById(R.id.detail_tv_download); + rating_bar = findViewById(R.id.detail_rating_bar); + iv_icon = findViewById(R.id.detail_iv_icon); + rv_image = findViewById(R.id.detail_rv_image); + } + + @Override + protected void initData() { + appInfo = (AppInfo) getIntent().getSerializableExtra("appinfo"); + if (appInfo == null) { + ToastUtil.show("获取引用信息失败,返回重试"); + return; + } + tv_title.setText(appInfo.getApp_name()); + tv_name.setText(appInfo.getApp_name()); + tv_company.setText(appInfo.getApp_developer()); + tv_update_time.setText("更新时间:" + appInfo.getCreatetime()); + tv_version.setText("最新版本:" + appInfo.getApp_version_name()); + tv_content.setText(appInfo.getApp_desc()); + rating_bar.setRating((float) appInfo.getApp_score()); + Glide.with(this).asBitmap().load(appInfo.getApp_img()).into(iv_icon); + List list = new ArrayList() {{ + this.add(appInfo.getApp_preview1()); + this.add(appInfo.getApp_preview2()); + this.add(appInfo.getApp_preview3()); + }}; + imageAdapter = new ImageAdapter(list); + rv_image.setAdapter(imageAdapter); + rv_image.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false)); + CustomSnapHelper snapHelper = new CustomSnapHelper(); + snapHelper.attachToRecyclerView(rv_image); + if (appInfo.isInstall()) { + if (appInfo.isUpdate()) { + tv_download.setText("更新"); + } else { + tv_download.setText("打开"); + } + } else { + tv_download.setText("安装"); + } + tv_download.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + if (appInfo.isInstall() && !appInfo.isUpdate()) { + ApkUtils.openApp(DetailsActivity.this, appInfo.getApp_package()); + } else { + GetRequest request = OkGo.get(appInfo.getApp_url()); + //这里第一个参数是tag,代表下载任务的唯一标识,传任意字符串都行,需要保证唯一,我这里用url作为了tag + OkDownload.request(appInfo.getApp_url(), request)// +// .priority(apk.priority)// + .extra1(appInfo)// + .save()// + .register(new LogDownloadListener())// + .start(); + } + } + }); + } + + @Override + protected void setListener() { + + } + + public void finish(View view) { + finish(); + } +} diff --git a/app/src/main/java/com/appstore/uiui/activity/DownloadManagerActivity.java b/app/src/main/java/com/appstore/uiui/activity/DownloadManagerActivity.java new file mode 100644 index 0000000..8436dc6 --- /dev/null +++ b/app/src/main/java/com/appstore/uiui/activity/DownloadManagerActivity.java @@ -0,0 +1,68 @@ +package com.appstore.uiui.activity; + +import android.view.View; +import android.widget.Adapter; + +import androidx.recyclerview.widget.LinearLayoutManager; +import androidx.recyclerview.widget.RecyclerView; + +import com.appstore.uiui.R; +import com.appstore.uiui.adapter.DownloadManagerAdapter; +import com.appstore.uiui.base.BaseActivity; +import com.appstore.uiui.utils.ToastUtil; +import com.lzy.okserver.OkDownload; +import com.lzy.okserver.task.XExecutor; + +public class DownloadManagerActivity extends BaseActivity implements XExecutor.OnAllTaskEndListener { + private RecyclerView recyclerView; + private DownloadManagerAdapter adapter; + private OkDownload okDownload; + + @Override + protected int setLayoutResourceID() { + return R.layout.activity_download_manager; + } + + @Override + protected void initView() { + recyclerView = findViewById(R.id.recyclerView); + } + + @Override + protected void initData() { + okDownload = OkDownload.getInstance(); + adapter = new DownloadManagerAdapter(this); + adapter.updateData(DownloadManagerAdapter.TYPE_ALL); + recyclerView.setLayoutManager(new LinearLayoutManager(this)); + recyclerView.setAdapter(adapter); + okDownload.addOnAllTaskEndListener(this); + } + + @Override + protected void setListener() { + + } + + + @Override + public void onAllTaskEnd() { + ToastUtil.show("所有任务已完成"); + } + + @Override + protected void onDestroy() { + super.onDestroy(); + okDownload.removeOnAllTaskEndListener(this); + adapter.unRegister(); + } + + @Override + protected void onResume() { + super.onResume(); + adapter.notifyDataSetChanged(); + } + + public void finish(View view) { + this.finish(); + } +} diff --git a/app/src/main/java/com/appstore/uiui/activity/KindDetailActivity.java b/app/src/main/java/com/appstore/uiui/activity/KindDetailActivity.java new file mode 100644 index 0000000..2a2c8e0 --- /dev/null +++ b/app/src/main/java/com/appstore/uiui/activity/KindDetailActivity.java @@ -0,0 +1,58 @@ +package com.appstore.uiui.activity; + +import android.os.Handler; +import android.os.Message; +import android.view.View; +import android.widget.TextView; + +import androidx.annotation.NonNull; + +import com.appstore.uiui.R; +import com.appstore.uiui.base.BaseActivity; + + +public class KindDetailActivity extends BaseActivity { + private TextView title; + private String name; + private int subject; + + @Override + + protected int setLayoutResourceID() { + return R.layout.activity_kind_detail; + } + + @Override + protected void initView() { + title = findViewById(R.id.detail_tv_title); + } + + @Override + protected void initData() { + subject = getIntent().getIntExtra("kind", 0); + name = getIntent().getStringExtra("name"); + title.setText(name); + + } + + @Override + protected void setListener() { + + } + + public void finish(View view) { + finish(); + } + + Handler handler = new Handler() { + @Override + public void handleMessage(@NonNull Message msg) { + super.handleMessage(msg); + switch (msg.what) { + case 1: + + break; + } + } + }; +} diff --git a/app/src/main/java/com/appstore/uiui/activity/LocalManagerActivity.java b/app/src/main/java/com/appstore/uiui/activity/LocalManagerActivity.java new file mode 100644 index 0000000..5fb58cb --- /dev/null +++ b/app/src/main/java/com/appstore/uiui/activity/LocalManagerActivity.java @@ -0,0 +1,132 @@ +package com.appstore.uiui.activity; + +import androidx.appcompat.app.AppCompatActivity; +import androidx.recyclerview.widget.LinearLayoutManager; +import androidx.recyclerview.widget.RecyclerView; + +import android.content.Intent; +import android.content.pm.ApplicationInfo; +import android.content.pm.PackageInfo; +import android.content.pm.PackageManager; +import android.content.pm.ResolveInfo; +import android.graphics.drawable.Drawable; +import android.os.Bundle; +import android.view.View; + +import com.appstore.uiui.R; +import com.appstore.uiui.adapter.LocalAppAdapter; +import com.appstore.uiui.base.BaseActivity; +import com.appstore.uiui.base.RefreshManager; +import com.appstore.uiui.bean.LocalApp; +import com.scwang.smartrefresh.layout.SmartRefreshLayout; +import com.scwang.smartrefresh.layout.api.RefreshLayout; +import com.scwang.smartrefresh.layout.listener.OnRefreshListener; + +import java.util.ArrayList; +import java.util.List; + +public class LocalManagerActivity extends BaseActivity implements RefreshManager.RefreshInterface { + private RecyclerView mRvApp; + private SmartRefreshLayout mRefreshLayout; + private List localAppList; + private LocalAppAdapter adapter; + + @Override + protected int setLayoutResourceID() { + return R.layout.activity_local_manager; + } + + @Override + protected void initView() { + mRvApp = findViewById(R.id.local_app_rv_app); + mRefreshLayout = findViewById(R.id.local_app_refresh_layout); + RefreshManager.getInstance().register(this); + localAppList = new ArrayList<>(); + + mRefreshLayout.setEnableLoadMore(false); + mRefreshLayout.setEnableRefresh(true); + mRefreshLayout.setOnRefreshListener(new OnRefreshListener() { + @Override + public void onRefresh(RefreshLayout refreshlayout) { + initDatas(); + } + }); + mRefreshLayout.autoRefresh(); + + adapter = new LocalAppAdapter(localAppList, this); + adapter.setHasStableIds(true); + mRvApp.setAdapter(adapter); + mRvApp.setLayoutManager(new LinearLayoutManager(getApplicationContext())); + } + + @Override + protected void initData() { + initDatas(); + + } + + @Override + protected void onResume() { + super.onResume(); + initDatas(); + + } + + private void initDatas() { + localAppList.clear(); + Intent intent = new Intent(Intent.ACTION_MAIN, null); + intent.addCategory(Intent.CATEGORY_LAUNCHER); + List resolveInfoList = getApplication().getPackageManager().queryIntentActivities(intent, 0); + + for (int i = 0; i < resolveInfoList.size(); i++) { + LocalApp bean = new LocalApp(); + bean.setAppName(resolveInfoList.get(i).loadLabel(getApplicationContext().getPackageManager()).toString()); + String packageName = resolveInfoList.get(i).activityInfo.packageName; + bean.setPackageName(packageName); + Drawable icon = resolveInfoList.get(i).loadIcon(getApplicationContext().getPackageManager()); + bean.setIcon(icon); + + try { + PackageInfo packageInfo = getApplicationContext().getPackageManager().getPackageInfo(packageName, 0); + String versionCode = getApplicationContext().getPackageManager() + .getPackageInfo(packageName, 0).versionName; + bean.setVersion(versionCode); + + if ((packageInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) <= 0) { + //第三方应用 + localAppList.add(bean); + //判断是否需要进行更新 + + } else { + //系统应用 + } + + } catch (PackageManager.NameNotFoundException e) { + e.printStackTrace(); + } + } + adapter.notifyDataSetChanged(); + mRefreshLayout.finishRefresh(); + + } + + @Override + protected void setListener() { + + } + + @Override + public void onRefresh() { + mRefreshLayout.autoRefresh(); + + } + + @Override + public void onLoadBitMap(boolean isLoad) { + + } + + public void finish(View view) { + this.finish(); + } +} diff --git a/app/src/main/java/com/appstore/uiui/activity/MainActivity.java b/app/src/main/java/com/appstore/uiui/activity/MainActivity.java index 20842cc..9c75ee6 100644 --- a/app/src/main/java/com/appstore/uiui/activity/MainActivity.java +++ b/app/src/main/java/com/appstore/uiui/activity/MainActivity.java @@ -1,36 +1,42 @@ package com.appstore.uiui.activity; -import androidx.appcompat.app.AppCompatActivity; -import androidx.fragment.app.Fragment; -import androidx.fragment.app.FragmentPagerAdapter; -import androidx.viewpager.widget.ViewPager; - import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; +import android.content.pm.PackageManager; import android.os.Bundle; import android.os.Environment; +import android.os.Handler; +import android.os.Message; +import android.text.TextUtils; import android.util.Log; -import android.view.MenuItem; +import android.view.KeyEvent; import android.view.View; import android.widget.ImageView; import android.widget.RelativeLayout; +import androidx.annotation.NonNull; +import androidx.fragment.app.Fragment; +import androidx.fragment.app.FragmentPagerAdapter; +import androidx.viewpager.widget.ViewPager; + import com.appstore.uiui.R; import com.appstore.uiui.base.BaseActivity; +import com.appstore.uiui.base.UserInfo; import com.appstore.uiui.fragment.FeaturedFragment; import com.appstore.uiui.fragment.KindFragment; import com.appstore.uiui.fragment.ManageFragment; import com.appstore.uiui.fragment.RankFragment; -import com.appstore.uiui.utils.ApkUtils; +import com.appstore.uiui.jpush.ExampleUtil; +import com.appstore.uiui.jpush.LocalBroadcastManager; +import com.appstore.uiui.jpush.TagAliasOperatorHelper; +import com.appstore.uiui.network.OKGOPost; +import com.appstore.uiui.service.MyDownloadService; +import com.appstore.uiui.utils.LogUtils; +import com.appstore.uiui.utils.SPUtils; import com.appstore.uiui.utils.ToastUtil; -import com.arialyy.annotations.Download; -import com.arialyy.aria.core.Aria; -import com.arialyy.aria.core.listener.ISchedulers; -import com.arialyy.aria.core.task.DownloadTask; -import com.arialyy.aria.util.ALog; -import com.blankj.utilcode.util.ToastUtils; +import com.appstore.uiui.utils.Utils; import com.flyco.tablayout.SlidingTabLayout; import com.hjq.permissions.OnPermission; import com.hjq.permissions.Permission; @@ -39,18 +45,48 @@ import com.hjq.permissions.XXPermissions; import java.io.File; import java.util.ArrayList; import java.util.List; +import java.util.Set; + +import cn.jpush.android.api.JPushInterface; +import cn.jpush.android.api.TagAliasCallback; + +import static com.appstore.uiui.jpush.TagAliasOperatorHelper.ACTION_ADD; +import static com.appstore.uiui.jpush.TagAliasOperatorHelper.ACTION_CHECK; +import static com.appstore.uiui.jpush.TagAliasOperatorHelper.ACTION_CLEAN; +import static com.appstore.uiui.jpush.TagAliasOperatorHelper.ACTION_DELETE; +import static com.appstore.uiui.jpush.TagAliasOperatorHelper.ACTION_GET; +import static com.appstore.uiui.jpush.TagAliasOperatorHelper.ACTION_SET; +import static com.appstore.uiui.jpush.TagAliasOperatorHelper.TagAliasBean; +import static com.appstore.uiui.jpush.TagAliasOperatorHelper.sequence; public class MainActivity extends BaseActivity { private RelativeLayout search_layout; private ImageView iv_download; private SlidingTabLayout mSlidingTabLayout; private ViewPager mViewPager; + private long exitTime = 0; + public static boolean isForeground = false; + @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); - Aria.download(this).register(); requestPermission(); + registerMessageReceiver(); // used for receive msg + String rid = JPushInterface.getRegistrationID(getApplicationContext()); + if (!rid.isEmpty()) { + ToastUtil.debugShow("RegId:" + rid); + LogUtils.e("RegId", rid); + onTagAliasAction(7); + } else { +// ToastUtil.show("Get registration fail, JPush init failed!"); +// Toast.makeText(this, "Get registration fail, JPush init failed!", Toast.LENGTH_SHORT).show(); + } + OKGOPost.getUserInfo(handler); +// PackageManager pm = getPackageManager(); +// pm.setApplicationEnabledSetting("com.tencent.qqmusic", PackageManager.COMPONENT_ENABLED_STATE_DEFAULT, 0); + startService(new Intent(MainActivity.this, MyDownloadService.class)); + } @Override @@ -64,7 +100,7 @@ public class MainActivity extends BaseActivity { iv_download.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { - + startActivity(new Intent(MainActivity.this, DownloadManagerActivity.class)); } }); search_layout = findViewById(R.id.search_layout); @@ -111,12 +147,138 @@ public class MainActivity extends BaseActivity { } + // 初始化 JPush。如果已经初始化,但没有登录成功,则执行重新登录。 + private void init() { + JPushInterface.init(getApplicationContext()); + } + + public void onTagAliasAction(int i) { + Set tags = null; + String alias = null; + int action = -1; + boolean isAliasAction = false; + switch (i) { + //设置手机号码: + case 0: +// handleSetMobileNumber(); + return; + //增加tag + case 1: +// tags = getInPutTags(); + if (tags == null) { + return; + } + action = ACTION_ADD; + break; + //设置tag + case 2: +// tags = getInPutTags(); + if (tags == null) { + return; + } + action = ACTION_SET; + break; + //删除tag + case 3: +// tags = getInPutTags(); + if (tags == null) { + return; + } + action = ACTION_DELETE; + break; + //获取所有tag + case 4: + action = ACTION_GET; + break; + //清除所有tag + case 5: + action = ACTION_CLEAN; + break; + case 6: +// tags = getInPutTags(); + if (tags == null) { + return; + } + action = ACTION_CHECK; + break; + //设置alias + case 7: +// alias = getInPutAlias(); + alias = Utils.getSerial(); + if (TextUtils.isEmpty(alias)) { + return; + } + isAliasAction = true; + action = ACTION_SET; + break; + //获取alias + case 8: + isAliasAction = true; + action = ACTION_GET; + break; + //删除alias + case 9: + isAliasAction = true; + action = ACTION_DELETE; + break; + default: + return; + } + TagAliasBean tagAliasBean = new TagAliasBean(); + tagAliasBean.action = action; + sequence++; + if (isAliasAction) { + tagAliasBean.alias = alias; + } else { + tagAliasBean.tags = tags; + } + tagAliasBean.isAliasAction = isAliasAction; + TagAliasOperatorHelper.getInstance().handleAction(getApplicationContext(), sequence, tagAliasBean); + + } + + //for receive customer msg from jpush server + private MessageReceiver mMessageReceiver; + public static final String MESSAGE_RECEIVED_ACTION = "com.example.jpushdemo.MESSAGE_RECEIVED_ACTION"; + public static final String KEY_TITLE = "title"; + public static final String KEY_MESSAGE = "message"; + public static final String KEY_EXTRAS = "extras"; + + public void registerMessageReceiver() { + mMessageReceiver = new MessageReceiver(); + IntentFilter filter = new IntentFilter(); + filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY); + filter.addAction(MESSAGE_RECEIVED_ACTION); + LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver, filter); + } + + + public class MessageReceiver extends BroadcastReceiver { + + @Override + public void onReceive(Context context, Intent intent) { + try { + if (MESSAGE_RECEIVED_ACTION.equals(intent.getAction())) { + String messge = intent.getStringExtra(KEY_MESSAGE); + String extras = intent.getStringExtra(KEY_EXTRAS); + StringBuilder showMsg = new StringBuilder(); + showMsg.append(KEY_MESSAGE + " : " + messge + "\n"); + if (!ExampleUtil.isEmpty(extras)) { + showMsg.append(KEY_EXTRAS + " : " + extras + "\n"); + } + } + } catch (Exception e) { + } + } + } + private String[] permission = new String[]{ // Permission.SYSTEM_ALERT_WINDOW, // Permission.CAMERA, // Permission.READ_SMS, // Permission.RECEIVE_SMS, // Permission.SEND_SMS, + Permission.REQUEST_INSTALL_PACKAGES, Permission.READ_EXTERNAL_STORAGE, Permission.WRITE_EXTERNAL_STORAGE, // Permission.READ_PHONE_STATE @@ -138,7 +300,7 @@ public class MainActivity extends BaseActivity { String path = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "POStemp"; File file = new File(path); file.mkdirs(); - } else { + } else { ToastUtil.show("需要授予所有权限才能正常使用本程序!"); } } @@ -156,53 +318,47 @@ public class MainActivity extends BaseActivity { }); } - //在这里处理任务执行中的状态,如进度进度条的刷新 - @Download.onTaskRunning - protected void running(DownloadTask task) { - Log.e("fanhuitong", "正在下载:" + "State:" + task.getState() + "\t进度:" + task.getPercent() + "%" + "-" + task.getExtendField()); - ToastUtils.showShort("正在下载:" + task.getExtendField() + "\t" + task.getPercent() + "%"); - } - @Download.onTaskComplete - void taskComplete(DownloadTask task) { - //在这里处理任务完成的状态 - String downloadPath = task.getFilePath(); - String packageName = task.getExtendField(); - Log.e("fanhuitong", "downloadPath::" + downloadPath); - Log.e("fanhuitong", "extendField::" + packageName); - ApkUtils.installApkInSilence(downloadPath, packageName); - } private static final String TAG = "fanhuitong"; - BroadcastReceiver receiver = new BroadcastReceiver() { - @Override public void onReceive(Context context, Intent intent) { - if (intent.getAction().equals(ISchedulers.ARIA_TASK_INFO_ACTION)){ - // 获取任务状态 - ALog.d(TAG, "state = " + intent.getIntExtra(ISchedulers.TASK_STATE, -1)); - // 获取任务类型 - ALog.d(TAG, "type = " + intent.getIntExtra(ISchedulers.TASK_TYPE, -1)); - // 获取任务状态速度,单位为byte/s - ALog.d(TAG, "speed = " + intent.getLongExtra(ISchedulers.TASK_SPEED, -1)); - // 获取任务进度,0-100 - ALog.d(TAG, "percent = " + intent.getIntExtra(ISchedulers.TASK_PERCENT, -1)); - // 获取任务实体 - ALog.d(TAG, "entity = " + intent.getParcelableExtra(ISchedulers.TASK_ENTITY).toString()); + + @Override + public boolean onKeyDown(int keyCode, KeyEvent event) { + if (keyCode == KeyEvent.KEYCODE_BACK) { + exit(); + return false; + } + return super.onKeyDown(keyCode, event); + + } + + public void exit() { + if ((System.currentTimeMillis() - exitTime) > 2000) { + ToastUtil.show("再按一次退出程序"); + exitTime = System.currentTimeMillis(); + } else { + finish(); + } + } + + private Handler handler = new Handler() { + @Override + public void handleMessage(@NonNull Message msg) { + super.handleMessage(msg); + switch (msg.what) { + case 0: + SPUtils.put(MainActivity.this, "isLogined", 0); + break; + case 1: + SPUtils.put(MainActivity.this, "isLogined", 1); + UserInfo userInfo = (UserInfo) msg.obj; + SPUtils.put(MainActivity.this, "member_id", userInfo.getMember_id()); + SPUtils.put(MainActivity.this, "sn_id", userInfo.getId()); + break; + case 2: + SPUtils.put(MainActivity.this, "isLogined", 2); + break; } } }; - - @Override protected void onResume() { - super.onResume(); - registerReceiver(receiver, new IntentFilter(ISchedulers.ARIA_TASK_INFO_ACTION)); - } - - @Override protected void onDestroy() { - super.onDestroy(); - unregisterReceiver(receiver); - //Aria.download(this).unRegister(); - } - - - - } diff --git a/app/src/main/java/com/appstore/uiui/adapter/AppAdapter.java b/app/src/main/java/com/appstore/uiui/adapter/AppAdapter.java index e7fad68..1a65d9f 100644 --- a/app/src/main/java/com/appstore/uiui/adapter/AppAdapter.java +++ b/app/src/main/java/com/appstore/uiui/adapter/AppAdapter.java @@ -1,9 +1,8 @@ package com.appstore.uiui.adapter; -import android.app.AlertDialog; import android.content.Context; -import android.content.DialogInterface; - +import android.content.Intent; +import android.telecom.Call; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; @@ -11,31 +10,32 @@ import android.widget.Button; import android.widget.ImageView; import android.widget.RatingBar; import android.widget.TextView; -import android.widget.Toast; import androidx.cardview.widget.CardView; import androidx.recyclerview.widget.RecyclerView; -import com.appstore.uiui.BuildConfig; import com.appstore.uiui.R; +import com.appstore.uiui.activity.DetailsActivity; import com.appstore.uiui.bean.AppInfo; - -import com.arialyy.annotations.AriaConstance; -import com.arialyy.aria.core.Aria; -import com.arialyy.aria.core.AriaConfig; -import com.arialyy.aria.core.AriaManager; -import com.blankj.utilcode.util.EncryptUtils; -import com.blankj.utilcode.util.PathUtils; +import com.appstore.uiui.listener.LogDownloadListener; +import com.appstore.uiui.utils.ApkUtils; +import com.appstore.uiui.utils.ToastUtil; import com.bumptech.glide.Glide; +import com.lzy.okgo.OkGo; +import com.lzy.okgo.model.Progress; +import com.lzy.okgo.request.GetRequest; +import com.lzy.okserver.OkDownload; +import com.lzy.okserver.download.DownloadListener; +import com.lzy.okserver.download.DownloadTask; - +import java.io.File; import java.util.List; /** * Created by asus on 2017/10/23. */ -public class AppAdapter extends RecyclerView.Adapter { +public class AppAdapter extends RecyclerView.Adapter { private List mAppInfoList; @@ -46,21 +46,30 @@ public class AppAdapter extends RecyclerView.Adapter appInfoList, boolean isShowOrder, boolean isNotLoadBitmap) { + public AppAdapter(List appInfoList, boolean isShowOrder, Context context) { + this.mContext = context; this.mAppInfoList = appInfoList; this.isShowOrder = isShowOrder; - this.isNotLoadBitmap = isNotLoadBitmap; } @Override - public FeaturedViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { - mContext = parent.getContext(); - return new FeaturedViewHolder(LayoutInflater.from(mContext).inflate(R.layout.item_app, parent, false)); + public Holder onCreateViewHolder(ViewGroup parent, int viewType) { + Context context = parent.getContext(); + return new Holder(LayoutInflater.from(context).inflate(R.layout.item_app, parent, false)); } @Override - public void onBindViewHolder(FeaturedViewHolder holder, final int position) { + public void onBindViewHolder(Holder holder, final int position) { final AppInfo appInfo = mAppInfoList.get(position); + final DownloadTask downloadTask = OkDownload.getInstance().getTask(appInfo.getApp_url()); + holder.setTag(appInfo.getApp_url()); + if (downloadTask != null) { + downloadTask.register(new ListDownloadListener(appInfo.getApp_url(), holder)); + holder.setTask(downloadTask); +// holder.bind(); + holder.refresh(downloadTask.progress); + } + if (!isNotLoadBitmap) { Glide.with(mContext).asBitmap().load(appInfo.getApp_img()).placeholder(R.drawable.ic_place_holder).into(holder.ivIcon); } else { @@ -73,80 +82,122 @@ public class AppAdapter extends RecyclerView.Adapter request = OkGo.get(appInfo.getApp_url()); + //这里第一个参数是tag,代表下载任务的唯一标识,传任意字符串都行,需要保证唯一,我这里用url作为了tag + OkDownload.request(appInfo.getApp_url(), request)// +// .priority(apk.priority)// + .extra1(appInfo)// + .save()// + .register(new LogDownloadListener())// + .start(); + notifyDataSetChanged(); } @Override public int getItemCount() { - return mAppInfoList.size(); + return mAppInfoList == null ? 0 : mAppInfoList.size(); } - public static class FeaturedViewHolder extends RecyclerView.ViewHolder { + @Override + public long getItemId(int position) { + return position; + } + + + public class Holder extends RecyclerView.ViewHolder { ImageView ivIcon; TextView tvCompany, tvName; Button btnDownLoad; RatingBar ratingBar; - TextView tvInstalled; + // TextView tvInstalled; CardView cardView; - public FeaturedViewHolder(View itemView) { + private DownloadTask task; + private String tag; + + public Holder(View itemView) { super(itemView); ivIcon = itemView.findViewById(R.id.app_iv_icon); tvCompany = itemView.findViewById(R.id.app_tv_company); tvName = itemView.findViewById(R.id.app_tv_name); btnDownLoad = itemView.findViewById(R.id.app_btn_download); ratingBar = itemView.findViewById(R.id.app_rating_bar); - tvInstalled = itemView.findViewById(R.id.app_tv_installed); +// tvInstalled = itemView.findViewById(R.id.app_tv_installed); cardView = itemView.findViewById(R.id.app_card_view); } + + public void bind() { + + } + + void refresh(Progress progress) { + switch (progress.status) { + case Progress.NONE: + btnDownLoad.setText("下载"); + break; + case Progress.PAUSE: + btnDownLoad.setText("继续"); + break; + case Progress.ERROR: + btnDownLoad.setText("出错"); + break; + case Progress.WAITING: + btnDownLoad.setText("等待"); + break; + case Progress.FINISH: + btnDownLoad.setText("完成"); + + break; + case Progress.LOADING: + btnDownLoad.setText((int) (progress.fraction * 100) + "%"); + break; + } + + } + + void setTask(DownloadTask task) { + this.task = task; + } + + void setTag(String tag) { + this.tag = tag; + } + + String getTag() { + return tag; + } } public void setNotLoadBitmap(boolean isNotLoadBitmap) { @@ -158,4 +209,45 @@ public class AppAdapter extends RecyclerView.Adapter { + + public static final int TYPE_ALL = 0; + public static final int TYPE_FINISH = 1; + public static final int TYPE_ING = 2; + + private Context mContext; + private List values; + private int type; + + private final LayoutInflater mInflater; + + public DownloadManagerAdapter(Context context) { + this.mContext = context; + mInflater = LayoutInflater.from(mContext); + } + + public void updateData(int type) { + //这里是将数据库的数据恢复 + this.type = type; + if (type == TYPE_ALL) values = OkDownload.restore(DownloadManager.getInstance().getAll()); + if (type == TYPE_FINISH) + values = OkDownload.restore(DownloadManager.getInstance().getFinished()); + if (type == TYPE_ING) + values = OkDownload.restore(DownloadManager.getInstance().getDownloading()); + notifyDataSetChanged(); + } + + @NonNull + @Override + public Holder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { + return new Holder(mInflater.inflate(R.layout.item_download_manager, parent, false)); + + } + + @Override + public void onBindViewHolder(@NonNull Holder holder, int position) { + DownloadTask task = values.get(position); + String tag = createTag(task); + task.register(new ListDownloadListener(tag, holder))// + .register(new LogDownloadListener()); + holder.setTag(tag); + holder.setTask(task); + holder.bind(); + holder.refresh(task.progress); + + } + + public void unRegister() { + Map taskMap = OkDownload.getInstance().getTaskMap(); + for (DownloadTask task : taskMap.values()) { + task.unRegister(createTag(task)); + } + } + + private String createTag(DownloadTask task) { + return type + "_" + task.progress.tag; + } + + @Override + public int getItemCount() { + return values == null ? 0 : values.size(); + } + + class Holder extends RecyclerView.ViewHolder { + ImageView icon, remove; + TextView name, state, downloadSize; + Button start; + NumberProgressBar pbProgress; + + private DownloadTask task; + private String tag; + + Holder(@NonNull View itemView) { + super(itemView); + icon = itemView.findViewById(R.id.icon); + remove = itemView.findViewById(R.id.remove); + name = itemView.findViewById(R.id.name); + state = itemView.findViewById(R.id.state); + downloadSize = itemView.findViewById(R.id.downloadSize); + start = itemView.findViewById(R.id.start); + pbProgress = itemView.findViewById(R.id.pbProgress); + } + + public void setTask(DownloadTask task) { + this.task = task; + } + + public void bind() { + + Progress progress = task.progress; + AppInfo apk = (AppInfo) progress.extra1; + if (apk != null) { + Glide.with(mContext).load(apk.getApp_img()).error(R.mipmap.ic_launcher).into(icon); + name.setText(apk.getApp_name()); + } else { + name.setText(progress.fileName); + } + start.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + start(); + } + }); + remove.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + remove(); + } + }); + + } + + public void refresh(Progress progress) { + String currentSize = Formatter.formatFileSize(mContext, progress.currentSize); + String totalSize = Formatter.formatFileSize(mContext, progress.totalSize); + downloadSize.setText(currentSize + "/" + totalSize); + switch (progress.status) { + case Progress.NONE: + state.setText("停止"); + start.setText("下载"); + break; + case Progress.PAUSE: + state.setText("暂停中"); + start.setText("继续"); + break; + case Progress.ERROR: + state.setText("下载出错"); + start.setText("出错"); + break; + case Progress.WAITING: + state.setText("等待中"); + start.setText("等待"); + break; + case Progress.FINISH: + state.setText("下载完成"); + start.setText("完成"); + break; + case Progress.LOADING: + String speed = Formatter.formatFileSize(mContext, progress.speed); + state.setText(String.format("%s/s", speed)); + start.setText("暂停"); + break; + } + pbProgress.setMax(10000); + pbProgress.setProgress((int) (progress.fraction * 10000)); + } + + public void start() { + Progress progress = task.progress; + switch (progress.status) { + case Progress.PAUSE: + case Progress.NONE: + case Progress.ERROR: + task.start(); + break; + case Progress.LOADING: + task.pause(); + break; + case Progress.FINISH: + + break; + } + refresh(progress); + } + + public void remove() { + task.remove(true); + updateData(type); + } + + public void restart() { + task.restart(); + } + + public void setTag(String tag) { + this.tag = tag; + } + + public String getTag() { + return tag; + } + } + + private class ListDownloadListener extends DownloadListener { + + private Holder holder; + + ListDownloadListener(Object tag, Holder holder) { + super(tag); + this.holder = holder; + } + + @Override + public void onStart(Progress progress) { + } + + @Override + public void onProgress(Progress progress) { + if (tag == holder.getTag()) { + holder.refresh(progress); + } + } + + @Override + public void onError(Progress progress) { + Throwable throwable = progress.exception; + if (throwable != null) throwable.printStackTrace(); + } + + @Override + public void onFinish(File file, Progress progress) { + + } + + @Override + public void onRemove(Progress progress) { + } + } + +} diff --git a/app/src/main/java/com/appstore/uiui/adapter/ImageAdapter.java b/app/src/main/java/com/appstore/uiui/adapter/ImageAdapter.java new file mode 100644 index 0000000..ae20c09 --- /dev/null +++ b/app/src/main/java/com/appstore/uiui/adapter/ImageAdapter.java @@ -0,0 +1,56 @@ +package com.appstore.uiui.adapter; + +import android.content.Context; +import android.view.LayoutInflater; +import android.view.View; +import android.view.ViewGroup; +import android.widget.ImageView; + +import androidx.recyclerview.widget.RecyclerView; + +import com.appstore.uiui.R; +import com.bumptech.glide.Glide; + +import java.util.List; + +/** + * Created by fht on 2019/11/08. + */ + +public class ImageAdapter extends RecyclerView.Adapter { + + private List mSrcList; + private Context mContext; + + + public ImageAdapter(List mSrcList) { + this.mSrcList = mSrcList; + } + + @Override + public ImageViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { + mContext = parent.getContext(); + return new ImageViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_image, parent, false)); + } + + @Override + public void onBindViewHolder(ImageViewHolder holder, int position) { + String src = mSrcList.get(position); + Glide.with(mContext).asBitmap().load(src).placeholder(R.drawable.ic_place_holder).into(holder.imageView); + } + + @Override + public int getItemCount() { + return mSrcList.size(); + } + + static class ImageViewHolder extends RecyclerView.ViewHolder { + ImageView imageView; + + ImageViewHolder(View itemView) { + super(itemView); + imageView = itemView.findViewById(R.id.item_iv); + } + } + +} diff --git a/app/src/main/java/com/appstore/uiui/adapter/KindAdapter.java b/app/src/main/java/com/appstore/uiui/adapter/KindAdapter.java index ca2fe37..dd64129 100644 --- a/app/src/main/java/com/appstore/uiui/adapter/KindAdapter.java +++ b/app/src/main/java/com/appstore/uiui/adapter/KindAdapter.java @@ -1,6 +1,7 @@ package com.appstore.uiui.adapter; import android.content.Context; +import android.content.Intent; import android.util.Log; import android.view.LayoutInflater; import android.view.View; @@ -11,6 +12,7 @@ import android.widget.TextView; import androidx.recyclerview.widget.RecyclerView; import com.appstore.uiui.R; +import com.appstore.uiui.activity.KindDetailActivity; import com.appstore.uiui.bean.Kind; import com.bumptech.glide.Glide; @@ -24,16 +26,14 @@ public class KindAdapter extends RecyclerView.Adapter mKindList; private Context mContext; - private boolean isNotLoadBitmap = false; - public KindAdapter(List mKindList, boolean isLoadBitmap) { + public KindAdapter(List mKindList, Context context) { this.mKindList = mKindList; - this.isNotLoadBitmap = isLoadBitmap; + this.mContext = context; } @Override public KindViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { - mContext = parent.getContext(); return new KindViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_kind, parent, false)); } @@ -41,16 +41,16 @@ public class KindAdapter extends RecyclerView.Adapter localAppList; - public LocalAppAdapter(List localAppList) { + public LocalAppAdapter(List localAppList, Context context) { + this.context = context; this.localAppList = localAppList; } @Override public LocalAppViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { - context = parent.getContext(); return new LocalAppViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_local_app, parent, false)); } @@ -46,64 +49,28 @@ public class LocalAppAdapter extends RecyclerView.Adapter" + appInfo.getNewVersionName()); + holder.btnDownLoad.setText("更新"); + holder.btnDownLoad.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + downloadApk(appInfo); + } + }); + + + } + + private void downloadApk(UpdateAppInfo appInfo) { + GetRequest request = OkGo.get(appInfo.getURL()); + //这里第一个参数是tag,代表下载任务的唯一标识,传任意字符串都行,需要保证唯一,我这里用url作为了tag + OkDownload.request(appInfo.getURL(), request)// +// .priority(apk.priority)// + .extra1(appInfo.getAppInfo())// + .save()// + .register(new LogDownloadListener())// + .start(); + notifyDataSetChanged(); + } + + @Override + public int getItemCount() { + return localAppList == null ? 0 : localAppList.size(); + } + + @Override + public long getItemId(int position) { + return position; + } + + public static class UpdateAppViewHolder extends RecyclerView.ViewHolder { + ImageView ivIcon; + TextView tvName, tvVersion; + TextView tvUpdate; + Button btnDownLoad; + CardView cardView; + + private DownloadTask task; + private String tag; + + public UpdateAppViewHolder(View itemView) { + super(itemView); + ivIcon = itemView.findViewById(R.id.local_app_iv_icon); + tvName = itemView.findViewById(R.id.local_app_tv_name); + tvVersion = itemView.findViewById(R.id.local_app_version); + tvUpdate = itemView.findViewById(R.id.local_app_update); + btnDownLoad = itemView.findViewById(R.id.local_app_btn_download); + cardView = itemView.findViewById(R.id.local_app_card_view); + } + + public void bind() { + + } + + void refresh(Progress progress) { + switch (progress.status) { + case Progress.NONE: + btnDownLoad.setText("下载"); + break; + case Progress.PAUSE: + btnDownLoad.setText("继续"); + break; + case Progress.ERROR: + btnDownLoad.setText("出错"); + break; + case Progress.WAITING: + btnDownLoad.setText("等待"); + break; + case Progress.FINISH: + btnDownLoad.setText("完成"); + + break; + case Progress.LOADING: + btnDownLoad.setText((int) (progress.fraction * 100) + "%"); + break; + } + + } + + void setTask(DownloadTask task) { + this.task = task; + } + + void setTag(String tag) { + this.tag = tag; + } + + String getTag() { + return tag; + } + } + + private class ListDownloadListener extends DownloadListener { + + private UpdateAppViewHolder holder; + + ListDownloadListener(Object tag, UpdateAppViewHolder holder) { + super(tag); + this.holder = holder; + } + + @Override + public void onStart(Progress progress) { + + } + + @Override + public void onProgress(Progress progress) { + if (tag == holder.getTag()) { + holder.refresh(progress); + } + } + + @Override + public void onError(Progress progress) { + Throwable throwable = progress.exception; + if (throwable != null) throwable.printStackTrace(); + ToastUtil.show(((AppInfo) progress.extra1).getApp_name() + "\t下载失败,请重试"); + } + + @Override + public void onFinish(File file, Progress progress) { + ToastUtil.show(((AppInfo) progress.extra1).getApp_name() + "\t下载完成"); + ApkUtils.installApkInSilence(file.getAbsolutePath(), ((AppInfo) progress.extra1).getApp_package()); + } + + @Override + public void onRemove(Progress progress) { + } + } + +} diff --git a/app/src/main/java/com/appstore/uiui/base/BaseFragment.java b/app/src/main/java/com/appstore/uiui/base/BaseFragment.java index 8844354..15eb209 100644 --- a/app/src/main/java/com/appstore/uiui/base/BaseFragment.java +++ b/app/src/main/java/com/appstore/uiui/base/BaseFragment.java @@ -9,6 +9,8 @@ import android.view.View; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; +import com.appstore.uiui.utils.LogUtils; + /** * Created by asus on 2017/8/4. */ @@ -20,66 +22,66 @@ public class BaseFragment extends Fragment { @Override public void onAttach(Context context) { super.onAttach(context); - Log.d(TAG, "onAttach: "); + LogUtils.d(TAG, "onAttach: "); } @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); - Log.d(TAG, "onCreate: "); + LogUtils.d(TAG, "onCreate: "); } @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); - Log.d(TAG, "onViewCreated: "); + LogUtils.d(TAG, "onViewCreated: "); } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); - Log.d(TAG, "onActivityCreated: "); + LogUtils.d(TAG, "onActivityCreated: "); } @Override public void onStart() { super.onStart(); - Log.d(TAG, "onStart: "); + LogUtils.d(TAG, "onStart: "); } @Override public void onResume() { super.onResume(); - Log.d(TAG, "onResume: "); + LogUtils.d(TAG, "onResume: "); } @Override public void onPause() { super.onPause(); - Log.d(TAG, "onPause: "); + LogUtils.d(TAG, "onPause: "); } @Override public void onStop() { super.onStop(); - Log.d(TAG, "onStop: "); + LogUtils.d(TAG, "onStop: "); } @Override public void onDestroyView() { super.onDestroyView(); - Log.d(TAG, "onDestroyView: "); + LogUtils.d(TAG, "onDestroyView: "); } @Override public void onDestroy() { super.onDestroy(); - Log.d(TAG, "onDestroy: "); + LogUtils.d(TAG, "onDestroy: "); } @Override public void onDetach() { super.onDetach(); - Log.d(TAG, "onDetach: "); + LogUtils.d(TAG, "onDetach: "); } } diff --git a/app/src/main/java/com/appstore/uiui/base/UserInfo.java b/app/src/main/java/com/appstore/uiui/base/UserInfo.java new file mode 100644 index 0000000..4adf333 --- /dev/null +++ b/app/src/main/java/com/appstore/uiui/base/UserInfo.java @@ -0,0 +1,123 @@ +package com.appstore.uiui.base; + +import java.io.Serializable; + +public class UserInfo implements Serializable { + private String id; + private String sn_value; + private String sn_name; + private String sn_phone; + private String sn_school; + private int sn_grade; + private String sn_app; + private String sn_area; + private int member_id; + private int is_delete; + private int is_reset; + private int is_lock; + private String createtime; + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getSn_value() { + return sn_value; + } + + public void setSn_value(String sn_value) { + this.sn_value = sn_value; + } + + public String getSn_name() { + return sn_name; + } + + public void setSn_name(String sn_name) { + this.sn_name = sn_name; + } + + public String getSn_phone() { + return sn_phone; + } + + public void setSn_phone(String sn_phone) { + this.sn_phone = sn_phone; + } + + public String getSn_school() { + return sn_school; + } + + public void setSn_school(String sn_school) { + this.sn_school = sn_school; + } + + public int getSn_grade() { + return sn_grade; + } + + public void setSn_grade(int sn_grade) { + this.sn_grade = sn_grade; + } + + public String getSn_app() { + return sn_app; + } + + public void setSn_app(String sn_app) { + this.sn_app = sn_app; + } + + public String getSn_area() { + return sn_area; + } + + public void setSn_area(String sn_area) { + this.sn_area = sn_area; + } + + public int getMember_id() { + return member_id; + } + + public void setMember_id(int member_id) { + this.member_id = member_id; + } + + public int getIs_delete() { + return is_delete; + } + + public void setIs_delete(int is_delete) { + this.is_delete = is_delete; + } + + public int getIs_reset() { + return is_reset; + } + + public void setIs_reset(int is_reset) { + this.is_reset = is_reset; + } + + public int getIs_lock() { + return is_lock; + } + + public void setIs_lock(int is_lock) { + this.is_lock = is_lock; + } + + public String getCreatetime() { + return createtime; + } + + public void setCreatetime(String createtime) { + this.createtime = createtime; + } +} diff --git a/app/src/main/java/com/appstore/uiui/bean/AppInfo.java b/app/src/main/java/com/appstore/uiui/bean/AppInfo.java index 059adc6..7f8bccc 100644 --- a/app/src/main/java/com/appstore/uiui/bean/AppInfo.java +++ b/app/src/main/java/com/appstore/uiui/bean/AppInfo.java @@ -27,9 +27,8 @@ public class AppInfo implements Serializable { private int is_silent; private String createtime; - public static boolean isInstall; - - public static boolean isUpdate; + private boolean isInstall = false; + private boolean isUpdate = false; public int getApp_id() { @@ -216,6 +215,9 @@ public class AppInfo implements Serializable { this.createtime = createtime; } + public void setInstall(boolean b) { + this.isInstall = b; + } public boolean isInstall() { return isInstall; @@ -224,4 +226,8 @@ public class AppInfo implements Serializable { public boolean isUpdate() { return isUpdate; } + + public void setUpdate(boolean b) { + this.isUpdate = b; + } } diff --git a/app/src/main/java/com/appstore/uiui/bean/LocalApp.java b/app/src/main/java/com/appstore/uiui/bean/LocalApp.java index d319629..666f668 100644 --- a/app/src/main/java/com/appstore/uiui/bean/LocalApp.java +++ b/app/src/main/java/com/appstore/uiui/bean/LocalApp.java @@ -14,8 +14,8 @@ public class LocalApp { String size;//软件的大小 String version;//软件的版本号 String packageName;//软件的包名 - - boolean isNeedUpdate=false; + int versionCode; + boolean isNeedUpdate = false; public LocalApp() { } @@ -69,6 +69,14 @@ public class LocalApp { this.version = version; } + public int getVersionCode() { + return versionCode; + } + + public void setVersionCode(int versionCode) { + this.versionCode = versionCode; + } + public String getPackageName() { return packageName; } diff --git a/app/src/main/java/com/appstore/uiui/bean/UpdateAppInfo.java b/app/src/main/java/com/appstore/uiui/bean/UpdateAppInfo.java new file mode 100644 index 0000000..ab1e29f --- /dev/null +++ b/app/src/main/java/com/appstore/uiui/bean/UpdateAppInfo.java @@ -0,0 +1,90 @@ +package com.appstore.uiui.bean; + +import android.graphics.drawable.Drawable; + +import java.io.Serializable; + +public class UpdateAppInfo implements Serializable { + + private String appName; + private String packageName; + private int versionCode; + private int newVersionCode; + private String newVersionName; + private String versionName; + private String URL; + private Drawable icon; + private AppInfo appInfo; + + public String getAppName() { + return appName; + } + + public void setAppName(String appName) { + this.appName = appName; + } + + public String getPackageName() { + return packageName; + } + + public void setPackageName(String packageName) { + this.packageName = packageName; + } + + public int getVersionCode() { + return versionCode; + } + + public void setVersionCode(int versionCode) { + this.versionCode = versionCode; + } + + public int getNewVersionCode() { + return newVersionCode; + } + + public void setNewVersionCode(int newVersionCode) { + this.newVersionCode = newVersionCode; + } + + public String getVersionName() { + return versionName; + } + + public void setVersionName(String versionName) { + this.versionName = versionName; + } + + public String getNewVersionName() { + return newVersionName; + } + + public void setNewVersionName(String newVersionName) { + this.newVersionName = newVersionName; + } + + public String getURL() { + return URL; + } + + public void setURL(String URL) { + this.URL = URL; + } + + public Drawable getIcon() { + return icon; + } + + public void setIcon(Drawable icon) { + this.icon = icon; + } + + public AppInfo getAppInfo() { + return appInfo; + } + + public void setAppInfo(AppInfo appInfo) { + this.appInfo = appInfo; + } +} diff --git a/app/src/main/java/com/appstore/uiui/fragment/FeaturedFragment.java b/app/src/main/java/com/appstore/uiui/fragment/FeaturedFragment.java index 4574dd2..1631206 100644 --- a/app/src/main/java/com/appstore/uiui/fragment/FeaturedFragment.java +++ b/app/src/main/java/com/appstore/uiui/fragment/FeaturedFragment.java @@ -19,6 +19,7 @@ import com.appstore.uiui.bean.AppInfo; import com.appstore.uiui.bean.AppInfos; import com.appstore.uiui.network.OKGOPost; import com.appstore.uiui.network.URLs.Url; +import com.appstore.uiui.utils.ApkUtils; import com.appstore.uiui.utils.LogUtils; import com.appstore.uiui.utils.ToastUtil; import com.lzy.okgo.OkGo; @@ -62,7 +63,8 @@ public class FeaturedFragment extends LazyLoadFragment implements RefreshManager isNotLoadBitmap = false; newAppInfoList = new ArrayList<>(); - adapter = new AppAdapter(newAppInfoList, false, isNotLoadBitmap); + adapter = new AppAdapter(newAppInfoList, false, getContext()); + adapter.setHasStableIds(true); mRvResult.setAdapter(adapter); mRvResult.setLayoutManager(new LinearLayoutManager(getActivity())); @@ -86,8 +88,6 @@ public class FeaturedFragment extends LazyLoadFragment implements RefreshManager synchronized private void initAPPData(final Handler handler) { OKGOPost.getAllAppInfo(handler); - mRefreshLayout.finishRefresh(); - } @@ -106,13 +106,24 @@ public class FeaturedFragment extends LazyLoadFragment implements RefreshManager public void handleMessage(Message msg) { super.handleMessage(msg); switch (msg.what) { - case 0: + case 1: newAppInfoList = (List) msg.obj; - adapter.setData(newAppInfoList); + adapter.setData(checkUpdateOrInstalled(newAppInfoList)); + adapter.notifyDataSetChanged(); break; + } + mRefreshLayout.finishRefresh(); + } }; + public List checkUpdateOrInstalled(List list) { + for (AppInfo appInfo : list) { + appInfo.setInstall(ApkUtils.isAvailable(getContext(), appInfo.getApp_package())); + appInfo.setUpdate(ApkUtils.checkIsUpdate(getContext(), appInfo.getApp_package(), Integer.parseInt(appInfo.getApp_version_code()))); + } + return list; + } } diff --git a/app/src/main/java/com/appstore/uiui/fragment/KindFragment.java b/app/src/main/java/com/appstore/uiui/fragment/KindFragment.java index 359e3d6..371522f 100644 --- a/app/src/main/java/com/appstore/uiui/fragment/KindFragment.java +++ b/app/src/main/java/com/appstore/uiui/fragment/KindFragment.java @@ -26,7 +26,7 @@ import java.util.List; * 分类的页面 */ -public class KindFragment extends BaseFragment implements RefreshManager.RefreshInterface { +public class KindFragment extends BaseFragment { private RecyclerView mRvKind; private KindAdapter adapter; @@ -37,7 +37,6 @@ public class KindFragment extends BaseFragment implements RefreshManager.Refresh public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_kind, container, false); mRvKind = view.findViewById(R.id.kind_rv_kind); - RefreshManager.getInstance().register(this); initView(); return view; @@ -45,39 +44,22 @@ public class KindFragment extends BaseFragment implements RefreshManager.Refresh private void initView() { kindList = new ArrayList<>(); - kindList.add(new Kind("游戏", 15, R.mipmap.ic_launcher_round)); - kindList.add(new Kind("实用工具", 5, R.mipmap.ic_launcher_round)); - kindList.add(new Kind("影音视听", 27, R.mipmap.ic_launcher_round)); - kindList.add(new Kind("聊天社交", 2, R.mipmap.ic_launcher_round)); - kindList.add(new Kind("图书阅读", 7, R.mipmap.ic_launcher_round)); - kindList.add(new Kind("学习教育", 12, R.mipmap.ic_launcher_round)); - kindList.add(new Kind("效率办公", 10, R.mipmap.ic_launcher_round)); - kindList.add(new Kind("时尚购物", 9, R.mipmap.ic_launcher_round)); - kindList.add(new Kind("居家生活", 4, R.mipmap.ic_launcher_round)); - kindList.add(new Kind("旅行交通", 3, R.mipmap.ic_launcher_round)); - kindList.add(new Kind("摄影摄像", 6, R.mipmap.ic_launcher_round)); - kindList.add(new Kind("医疗健康", 14, R.mipmap.ic_launcher_round)); - kindList.add(new Kind("体育运动", 8, R.mipmap.ic_launcher_round)); - kindList.add(new Kind("新闻资讯", 11, R.mipmap.ic_launcher_round)); - kindList.add(new Kind("娱乐消遣", 13, R.mipmap.ic_launcher_round)); - kindList.add(new Kind("金融理财", 1, R.mipmap.ic_launcher_round)); + kindList.add(new Kind("语文", 1, R.drawable.icon_language)); + kindList.add(new Kind("数学", 2, R.drawable.icon_math)); + kindList.add(new Kind("英语", 3, R.drawable.icon_english)); + kindList.add(new Kind("物理", 4, R.drawable.icon_physics)); + kindList.add(new Kind("化学", 5, R.drawable.icon_chemistry)); + kindList.add(new Kind("生物", 6, R.drawable.icon_biology)); + kindList.add(new Kind("政治", 7, R.drawable.icon_politics)); + kindList.add(new Kind("历史", 8, R.drawable.icon_history)); + kindList.add(new Kind("地理", 9, R.drawable.icon_geography)); - adapter = new KindAdapter(kindList, false); + kindList.add(new Kind("娱乐", 0, R.drawable.icon_game)); + + adapter = new KindAdapter(kindList, getContext()); mRvKind.setAdapter(adapter); mRvKind.setLayoutManager(new LinearLayoutManager(getActivity())); } - @Override - public void onRefresh() { - } - - @Override - public void onLoadBitMap(boolean isLoad) { - adapter.setNotLoadBitmap(isLoad); -// isNotLoadBitmap=isLoad; -// adapter = new KindAdapter(kindList,isNotLoadBitmap); -// mRvKind.setAdapter(adapter); -// mRvKind.setLayoutManager(new LinearLayoutManager(getActivity())); - } } diff --git a/app/src/main/java/com/appstore/uiui/fragment/ManageFragment.java b/app/src/main/java/com/appstore/uiui/fragment/ManageFragment.java index 57fe400..0663961 100644 --- a/app/src/main/java/com/appstore/uiui/fragment/ManageFragment.java +++ b/app/src/main/java/com/appstore/uiui/fragment/ManageFragment.java @@ -7,16 +7,26 @@ import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.graphics.drawable.Drawable; import android.os.Bundle; +import android.os.Handler; +import android.os.Message; import android.view.View; +import android.widget.LinearLayout; import android.widget.TextView; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import com.appstore.uiui.R; +import com.appstore.uiui.activity.LocalManagerActivity; import com.appstore.uiui.adapter.LocalAppAdapter; +import com.appstore.uiui.adapter.UpdateAppAdapter; import com.appstore.uiui.base.LazyLoadFragment; +import com.appstore.uiui.bean.AppInfo; import com.appstore.uiui.bean.LocalApp; +import com.appstore.uiui.bean.UpdateAppInfo; +import com.appstore.uiui.network.OKGOPost; +import com.appstore.uiui.utils.ApkUtils; +import com.appstore.uiui.utils.ToastUtil; import java.util.ArrayList; import java.util.List; @@ -27,14 +37,16 @@ import java.util.List; * 管理的页面 */ -public class ManageFragment extends LazyLoadFragment implements View.OnClickListener { +public class ManageFragment extends LazyLoadFragment { private RecyclerView mRvLocal; - private TextView mTvUpdateNum; - + private TextView manage_tv_updateNum; private List localAppList; - private LocalAppAdapter adapter; - + private List updateAppInfoList; + private List applist; + private List packageNameList = new ArrayList<>(); + private UpdateAppAdapter adapter; + private LinearLayout manage_ll_localapp; @Override public int getLayoutId() { @@ -43,9 +55,21 @@ public class ManageFragment extends LazyLoadFragment implements View.OnClickList @Override public void initViews(View view) { + manage_tv_updateNum = view.findViewById(R.id.manage_tv_updateNum); + manage_ll_localapp = view.findViewById(R.id.manage_ll_localapp); + manage_ll_localapp.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + startActivity(new Intent(getActivity(), LocalManagerActivity.class)); + } + }); mRvLocal = view.findViewById(R.id.manage_rv_local); - mTvUpdateNum = view.findViewById(R.id.manage_tv_updateNum); - initView(); + updateAppInfoList = new ArrayList<>(); + adapter = new UpdateAppAdapter(updateAppInfoList, getContext()); + mRvLocal.setAdapter(adapter); + mRvLocal.setLayoutManager(new LinearLayoutManager(getActivity())); + + initAPPData(handler); } @Override @@ -53,9 +77,12 @@ public class ManageFragment extends LazyLoadFragment implements View.OnClickList } - private void initView() { - localAppList = new ArrayList<>(); + synchronized private void initAPPData(final Handler handler) { + OKGOPost.getAllAppInfo(handler); + } + synchronized private List getLocalApp() { + List appList = new ArrayList<>(); Intent intent = new Intent(Intent.ACTION_MAIN, null); intent.addCategory(Intent.CATEGORY_LAUNCHER); List resolveInfoList = getActivity().getPackageManager().queryIntentActivities(intent, 0); @@ -63,8 +90,6 @@ public class ManageFragment extends LazyLoadFragment implements View.OnClickList for (int i = 0; i < resolveInfoList.size(); i++) { LocalApp bean = new LocalApp(); bean.setAppName(resolveInfoList.get(i).loadLabel(getActivity().getPackageManager()).toString()); - - String packageName = resolveInfoList.get(i).activityInfo.packageName; bean.setPackageName(packageName); Drawable icon = resolveInfoList.get(i).loadIcon(getActivity().getPackageManager()); @@ -75,67 +100,72 @@ public class ManageFragment extends LazyLoadFragment implements View.OnClickList String versionCode = getActivity().getPackageManager() .getPackageInfo(packageName, 0).versionName; bean.setVersion(versionCode); - + bean.setVersionCode(packageInfo.versionCode); if ((packageInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) <= 0) { //第三方应用 - //判断是否需要进行更新 // isNeedUpdate(bean, i); - + appList.add(bean); } else { //系统应用 } - } catch (PackageManager.NameNotFoundException e) { e.printStackTrace(); } } - - adapter = new LocalAppAdapter(localAppList); - mRvLocal.setAdapter(adapter); - mRvLocal.setLayoutManager(new LinearLayoutManager(getActivity())); - + return appList; } - public void onClick(View view) { - switch (view.getId()) { - case R.id.manage_ll_localapp: -// LocalAppActivity.startActivity(getActivity()); - break; - case R.id.manage_btn_update: - break; + synchronized private void updateDta(List list) { + packageNameList.clear(); + for (AppInfo appInfo : list) { + packageNameList.add(appInfo.getApp_package()); + } + localAppList = getLocalApp(); + if (packageNameList != null && packageNameList.size() > 0) { + if (localAppList != null && localAppList.size() > 0) { + for (LocalApp app : localAppList) { + if (packageNameList.contains(app.getPackageName())) { + AppInfo info = list.get(packageNameList.indexOf(app.getPackageName())); + if (ApkUtils.checkIsUpdate(getContext(), info.getApp_package(), Integer.parseInt(info.getApp_version_code()))) { + UpdateAppInfo updateAppInfo = new UpdateAppInfo(); + updateAppInfo.setVersionCode(app.getVersionCode()); + updateAppInfo.setVersionName(app.getVersion()); + updateAppInfo.setAppName(app.getAppName()); + updateAppInfo.setIcon(app.getIcon()); + updateAppInfo.setNewVersionCode(Integer.parseInt(info.getApp_version_code())); + updateAppInfo.setNewVersionName(info.getApp_version_name()); + updateAppInfo.setURL(info.getApp_url()); + updateAppInfo.setPackageName(info.getApp_package()); + updateAppInfo.setAppInfo(info); + updateAppInfoList.add(updateAppInfo); + } + } + } + } else { + ToastUtil.show("未安装本地应用"); + } + } else { + ToastUtil.show("没有可以下载的在线应用"); } } int updateNum = 0; - //判断某个应用是否需要升级 -// private void isNeedUpdate(final LocalApp localApp, final int position) { -// RetrofitManager.getInstance(getActivity()).getDetailInfo(localApp) -// .subscribeOn(Schedulers.io()) -// .observeOn(AndroidSchedulers.mainThread()) -// .subscribe(new Subscriber() { -// @Override -// public void onCompleted() { -// adapter.notifyDataSetChanged(); -// } -// -// @Override -// public void onError(Throwable e) { -// -// } -// -// @Override -// public void onNext(Boolean aBoolean) { -// localApp.setNeedUpdate(aBoolean); -// if (aBoolean) { -// localAppList.add(localApp); -// ++updateNum; -// mTvUpdateNum.setText(updateNum + "个应用可以升级"); -// } -// } -// }); -// } - + Handler handler = new Handler() { + @Override + public void handleMessage(Message msg) { + super.handleMessage(msg); + switch (msg.what) { + case 1: + applist = (List) msg.obj; + updateDta(applist); + updateNum = updateAppInfoList.size(); + manage_tv_updateNum.setText(updateNum + "个应用可以升级"); + adapter.notifyDataSetChanged(); + break; + } + } + }; } diff --git a/app/src/main/java/com/appstore/uiui/fragment/RankFragment.java b/app/src/main/java/com/appstore/uiui/fragment/RankFragment.java index f992ff2..7149f56 100644 --- a/app/src/main/java/com/appstore/uiui/fragment/RankFragment.java +++ b/app/src/main/java/com/appstore/uiui/fragment/RankFragment.java @@ -64,7 +64,7 @@ public class RankFragment extends LazyLoadFragment implements RefreshManager.Ref isNotLoadBitmap = false; mAppInfoList = new ArrayList<>(); - mAppAdapter = new AppAdapter(mAppInfoList, true, isNotLoadBitmap); + mAppAdapter = new AppAdapter(mAppInfoList, true, getContext()); mRvResult.setLayoutManager(new LinearLayoutManager(getActivity())); mRvResult.setAdapter(mAppAdapter); diff --git a/app/src/main/java/com/appstore/uiui/helper/CustomSnapHelper.java b/app/src/main/java/com/appstore/uiui/helper/CustomSnapHelper.java new file mode 100644 index 0000000..347d6c8 --- /dev/null +++ b/app/src/main/java/com/appstore/uiui/helper/CustomSnapHelper.java @@ -0,0 +1,82 @@ +package com.appstore.uiui.helper; + +import android.view.View; + +import androidx.annotation.NonNull; +import androidx.annotation.Nullable; +import androidx.recyclerview.widget.LinearLayoutManager; +import androidx.recyclerview.widget.LinearSnapHelper; +import androidx.recyclerview.widget.OrientationHelper; +import androidx.recyclerview.widget.RecyclerView; + +/** + * Created by asus on 2017/10/26. + * 自定义snapHelper和recyclerView,实现类似ViewPager滑动 + * 图片轮播 + */ + +public class CustomSnapHelper extends LinearSnapHelper { + + private OrientationHelper mHorizontalHelper; + + @Nullable + @Override + public int[] calculateDistanceToFinalSnap(RecyclerView.LayoutManager layoutManager, View targetView) { + int[] out = new int[2]; + if (layoutManager.canScrollHorizontally()) { + out[0] = distanceToStart(targetView, getHorizontalHelper(layoutManager)); + } else { + out[0] = 0; + } + + return out; + } + + private int distanceToStart(View targetView, OrientationHelper helper) { + return helper.getDecoratedStart(targetView) - helper.getStartAfterPadding(); + } + + @Nullable + @Override + public View findSnapView(RecyclerView.LayoutManager layoutManager) { + return findStartView(layoutManager, getHorizontalHelper(layoutManager)); + } + + private View findStartView(RecyclerView.LayoutManager layoutManager, + OrientationHelper helper) { + + if (layoutManager instanceof LinearLayoutManager) { + int firstChild = ((LinearLayoutManager) layoutManager).findFirstVisibleItemPosition(); + int lastChild = ((LinearLayoutManager) layoutManager).findLastVisibleItemPosition(); + if (firstChild == RecyclerView.NO_POSITION) { + return null; + } + if (lastChild == layoutManager.getItemCount() - 1) { + return layoutManager.findViewByPosition(lastChild); + } + + View child = layoutManager.findViewByPosition(firstChild); + + if (helper.getDecoratedEnd(child) >= helper.getDecoratedMeasurement(child) / 2 + && helper.getDecoratedEnd(child) > 0) { + return child; + } else { + return layoutManager.findViewByPosition(firstChild + 1); + } + } + + return super.findSnapView(layoutManager); + } + + + private OrientationHelper getHorizontalHelper( + @NonNull RecyclerView.LayoutManager layoutManager) { + if (mHorizontalHelper == null) { + mHorizontalHelper = OrientationHelper.createHorizontalHelper(layoutManager); + } + return mHorizontalHelper; + } + + + +} diff --git a/app/src/main/java/com/appstore/uiui/jpush/ExampleUtil.java b/app/src/main/java/com/appstore/uiui/jpush/ExampleUtil.java new file mode 100644 index 0000000..f27da36 --- /dev/null +++ b/app/src/main/java/com/appstore/uiui/jpush/ExampleUtil.java @@ -0,0 +1,133 @@ +package com.appstore.uiui.jpush; + +import android.content.Context; +import android.content.pm.ApplicationInfo; +import android.content.pm.PackageInfo; +import android.content.pm.PackageManager; +import android.content.pm.PackageManager.NameNotFoundException; +import android.net.ConnectivityManager; +import android.net.NetworkInfo; +import android.os.Bundle; +import android.os.Looper; +import android.telephony.TelephonyManager; +import android.text.TextUtils; +import android.widget.Toast; + +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import cn.jpush.android.api.JPushInterface; + +public class ExampleUtil { + public static final String PREFS_NAME = "JPUSH_EXAMPLE"; + public static final String PREFS_DAYS = "JPUSH_EXAMPLE_DAYS"; + public static final String PREFS_START_TIME = "PREFS_START_TIME"; + public static final String PREFS_END_TIME = "PREFS_END_TIME"; + public static final String KEY_APP_KEY = "JPUSH_APPKEY"; + + public static boolean isEmpty(String s) { + if (null == s) + return true; + if (s.length() == 0) + return true; + if (s.trim().length() == 0) + return true; + return false; + } + /** + * 只能以 “+” 或者 数字开头;后面的内容只能包含 “-” 和 数字。 + * */ + private final static String MOBILE_NUMBER_CHARS = "^[+0-9][-0-9]{1,}$"; + public static boolean isValidMobileNumber(String s) { + if(TextUtils.isEmpty(s)) return true; + Pattern p = Pattern.compile(MOBILE_NUMBER_CHARS); + Matcher m = p.matcher(s); + return m.matches(); + } + // 校验Tag Alias 只能是数字,英文字母和中文 + public static boolean isValidTagAndAlias(String s) { + Pattern p = Pattern.compile("^[\u4E00-\u9FA50-9a-zA-Z_!@#$&*+=.|]+$"); + Matcher m = p.matcher(s); + return m.matches(); + } + + // 取得AppKey + public static String getAppKey(Context context) { + Bundle metaData = null; + String appKey = null; + try { + ApplicationInfo ai = context.getPackageManager().getApplicationInfo( + context.getPackageName(), PackageManager.GET_META_DATA); + if (null != ai) + metaData = ai.metaData; + if (null != metaData) { + appKey = metaData.getString(KEY_APP_KEY); + if ((null == appKey) || appKey.length() != 24) { + appKey = null; + } + } + } catch (NameNotFoundException e) { + + } + return appKey; + } + + // 取得版本号 + public static String GetVersion(Context context) { + try { + PackageInfo manager = context.getPackageManager().getPackageInfo( + context.getPackageName(), 0); + return manager.versionName; + } catch (NameNotFoundException e) { + return "Unknown"; + } + } + + public static void showToast(final String toast, final Context context) + { + new Thread(new Runnable() { + + @Override + public void run() { + Looper.prepare(); +// Toast.makeText(context, toast, Toast.LENGTH_SHORT).show(); + Looper.loop(); + } + }).start(); + } + + public static boolean isConnected(Context context) { + ConnectivityManager conn = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); + NetworkInfo info = conn.getActiveNetworkInfo(); + return (info != null && info.isConnected()); + } + + public static String getImei(Context context, String imei) { + String ret = null; + try { + TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); + ret = telephonyManager.getDeviceId(); + } catch (Exception e) { + Logger.e(ExampleUtil.class.getSimpleName(), e.getMessage()); + } + if (isReadableASCII(ret)){ + return ret; + } else { + return imei; + } + } + + private static boolean isReadableASCII(CharSequence string){ + if (TextUtils.isEmpty(string)) return false; + try { + Pattern p = Pattern.compile("[\\x20-\\x7E]+"); + return p.matcher(string).matches(); + } catch (Throwable e){ + return true; + } + } + + public static String getDeviceId(Context context) { + return JPushInterface.getUdid(context); + } +} diff --git a/app/src/main/java/com/appstore/uiui/jpush/Invalid/ExampleApplication.java b/app/src/main/java/com/appstore/uiui/jpush/Invalid/ExampleApplication.java new file mode 100644 index 0000000..cd004f2 --- /dev/null +++ b/app/src/main/java/com/appstore/uiui/jpush/Invalid/ExampleApplication.java @@ -0,0 +1,25 @@ +package com.appstore.uiui.jpush.Invalid; + +import android.app.Application; + +import com.appstore.uiui.jpush.Logger; + +import cn.jpush.android.api.JPushInterface; + +/** + * For developer startup JPush SDK + * + * 一般建议在自定义 Application 类里初始化。也可以在主 Activity 里。 + */ +public class ExampleApplication extends Application { + private static final String TAG = "JIGUANG-Example"; + + @Override + public void onCreate() { + Logger.d(TAG, "[ExampleApplication] onCreate"); + super.onCreate(); + + JPushInterface.setDebugMode(true); // 设置开启日志,发布时请关闭日志 + JPushInterface.init(this); // 初始化 JPush + } +} diff --git a/app/src/main/java/com/appstore/uiui/jpush/Invalid/MainActivity.java b/app/src/main/java/com/appstore/uiui/jpush/Invalid/MainActivity.java new file mode 100644 index 0000000..fec9c74 --- /dev/null +++ b/app/src/main/java/com/appstore/uiui/jpush/Invalid/MainActivity.java @@ -0,0 +1,181 @@ +package com.appstore.uiui.jpush.Invalid; + + +import android.content.BroadcastReceiver; +import android.content.Context; +import android.content.Intent; +import android.content.IntentFilter; +import android.os.Bundle; +import android.view.View; +import android.view.View.OnClickListener; +import android.widget.Button; +import android.widget.EditText; +import android.widget.TextView; +import android.widget.Toast; + +import cn.jpush.android.api.InstrumentedActivity; +import cn.jpush.android.api.JPushInterface; + import com.appstore.uiui.R; + + + +//public class MainActivity extends InstrumentedActivity implements OnClickListener{ +// +// private Button mInit; +// private Button mSetting; +// private Button mStopPush; +// private Button mResumePush; +// private Button mGetRid; +// private TextView mRegId; +// private EditText msgText; +// +// public static boolean isForeground = false; +// @Override +// public void onCreate(Bundle savedInstanceState) { +// super.onCreate(savedInstanceState); +// setContentView(R.layout.main); +// initView(); +// registerMessageReceiver(); // used for receive msg +// } +// +// private void initView(){ +// TextView mImei = (TextView) findViewById(R.id.tv_imei); +// String udid = ExampleUtil.getImei(getApplicationContext(), ""); +// if (null != udid) mImei.setText("IMEI: " + udid); +// +// TextView mAppKey = (TextView) findViewById(R.id.tv_appkey); +// String appKey = ExampleUtil.getAppKey(getApplicationContext()); +// if (null == appKey) appKey = "AppKey异常"; +// mAppKey.setText("AppKey: " + appKey); +// +// mRegId = (TextView) findViewById(R.id.tv_regId); +// mRegId.setText("RegId:"); +// +// String packageName = getPackageName(); +// TextView mPackage = (TextView) findViewById(R.id.tv_package); +// mPackage.setText("PackageName: " + packageName); +// +// String deviceId = ExampleUtil.getDeviceId(getApplicationContext()); +// TextView mDeviceId = (TextView) findViewById(R.id.tv_device_id); +// mDeviceId.setText("deviceId:" + deviceId); +// +// String versionName = ExampleUtil.GetVersion(getApplicationContext()); +// TextView mVersion = (TextView) findViewById(R.id.tv_version); +// mVersion.setText("Version: " + versionName); +// +// mInit = (Button)findViewById(R.id.init); +// mInit.setOnClickListener(this); +// +// mStopPush = (Button)findViewById(R.id.stopPush); +// mStopPush.setOnClickListener(this); +// +// mResumePush = (Button)findViewById(R.id.resumePush); +// mResumePush.setOnClickListener(this); +// +// mGetRid = (Button) findViewById(R.id.getRegistrationId); +// mGetRid.setOnClickListener(this); +// +// mSetting = (Button)findViewById(R.id.setting); +// mSetting.setOnClickListener(this); +// +// msgText = (EditText)findViewById(R.id.msg_rec); +// } +// +// +// @Override +// public void onClick(View v) { +// switch (v.getId()) { +// case R.id.init: +// init(); +// break; +// case R.id.setting: +// Intent intent = new Intent(MainActivity.this, PushSetActivity.class); +// startActivity(intent); +// break; +// case R.id.stopPush: +// JPushInterface.stopPush(getApplicationContext()); +// break; +// case R.id.resumePush: +// JPushInterface.resumePush(getApplicationContext()); +// break; +// case R.id.getRegistrationId: +// String rid = JPushInterface.getRegistrationID(getApplicationContext()); +// if (!rid.isEmpty()) { +// mRegId.setText("RegId:" + rid); +// } else { +// Toast.makeText(this, "Get registration fail, JPush init failed!", Toast.LENGTH_SHORT).show(); +// } +// break; +// } +// } +// +// // 初始化 JPush。如果已经初始化,但没有登录成功,则执行重新登录。 +// private void init(){ +// JPushInterface.init(getApplicationContext()); +// } +// +// +// @Override +// protected void onResume() { +// isForeground = true; +// super.onResume(); +// } +// +// +// @Override +// protected void onPause() { +// isForeground = false; +// super.onPause(); +// } +// +// +// @Override +// protected void onDestroy() { +// LocalBroadcastManager.getInstance(this).unregisterReceiver(mMessageReceiver); +// super.onDestroy(); +// } +// +// +// //for receive customer msg from jpush server +// private MessageReceiver mMessageReceiver; +// public static final String MESSAGE_RECEIVED_ACTION = "com.example.jpushdemo.MESSAGE_RECEIVED_ACTION"; +// public static final String KEY_TITLE = "title"; +// public static final String KEY_MESSAGE = "message"; +// public static final String KEY_EXTRAS = "extras"; +// +// public void registerMessageReceiver() { +// mMessageReceiver = new MessageReceiver(); +// IntentFilter filter = new IntentFilter(); +// filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY); +// filter.addAction(MESSAGE_RECEIVED_ACTION); +// LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver, filter); +// } +// +// public class MessageReceiver extends BroadcastReceiver { +// +// @Override +// public void onReceive(Context context, Intent intent) { +// try { +// if (MESSAGE_RECEIVED_ACTION.equals(intent.getAction())) { +// String messge = intent.getStringExtra(KEY_MESSAGE); +// String extras = intent.getStringExtra(KEY_EXTRAS); +// StringBuilder showMsg = new StringBuilder(); +// showMsg.append(KEY_MESSAGE + " : " + messge + "\n"); +// if (!ExampleUtil.isEmpty(extras)) { +// showMsg.append(KEY_EXTRAS + " : " + extras + "\n"); +// } +// setCostomMsg(showMsg.toString()); +// } +// } catch (Exception e){ +// } +// } +// } +// +// private void setCostomMsg(String msg){ +// if (null != msgText) { +// msgText.setText(msg); +// msgText.setVisibility(View.VISIBLE); +// } +// } + +//} \ No newline at end of file diff --git a/app/src/main/java/com/appstore/uiui/jpush/Invalid/PushSetActivity.java b/app/src/main/java/com/appstore/uiui/jpush/Invalid/PushSetActivity.java new file mode 100644 index 0000000..c5709b8 --- /dev/null +++ b/app/src/main/java/com/appstore/uiui/jpush/Invalid/PushSetActivity.java @@ -0,0 +1,265 @@ +package com.appstore.uiui.jpush.Invalid; + +//public class PushSetActivity extends InstrumentedActivity implements OnClickListener { +// private static final String TAG = "JIGUANG-Example"; +// +// @Override +// public void onCreate(Bundle icicle) { +// super.onCreate(icicle); +// setContentView(R.layout.push_set_dialog); +// initListener(); +// } +// +// private void initListener() { +// //增加tag +// findViewById(R.id.bt_addtag).setOnClickListener(this); +// //设置tag +// findViewById(R.id.bt_settag).setOnClickListener(this); +// //删除tag +// findViewById(R.id.bt_deletetag).setOnClickListener(this); +// //获取所有tag +// findViewById(R.id.bt_getalltag).setOnClickListener(this); +// //清除所有tag +// findViewById(R.id.bt_cleantag).setOnClickListener(this); +// //查询tag绑定状态 +// findViewById(R.id.bt_checktag).setOnClickListener(this); +// +// //设置alias +// findViewById(R.id.bt_setalias).setOnClickListener(this); +// //获取alias +// findViewById(R.id.bt_getalias).setOnClickListener(this); +// //删除alias +// findViewById(R.id.bt_deletealias).setOnClickListener(this); +// //设置手机号码 +// findViewById(R.id.bt_setmobileNumber).setOnClickListener(this); +// //StyleAddActions +// findViewById(R.id.setStyle0).setOnClickListener(this); +// //StyleBasic +// findViewById(R.id.setStyle1).setOnClickListener(this); +// //StyleCustom +// findViewById(R.id.setStyle2).setOnClickListener(this); +// //SetPushTime +// findViewById(R.id.bu_setTime).setOnClickListener(this); +// } +// +// @Override +// public void onClick(View view) { +// switch (view.getId()) { +// case R.id.setStyle0: +// setAddActionsStyle(); +// break; +// case R.id.setStyle1: +// setStyleBasic(); +// break; +// case R.id.setStyle2: +// setStyleCustom(); +// break; +// case R.id.bu_setTime: +// Intent intent = new Intent(PushSetActivity.this, SettingActivity.class); +// startActivity(intent); +// break; +// default: +// onTagAliasAction(view); +// break; +// } +// } +// +// TagAliasCallback tagAlias = new TagAliasCallback() { +// @Override +// public void gotResult(int responseCode, String alias, Set tags) { +// Log.e(TAG,"responseCode:"+responseCode+",alias:"+alias+",tags:"+tags); +// } +// }; +// +// +// /** +// * 设置通知提示方式 - 基础属性 +// */ +// private void setStyleBasic() { +// BasicPushNotificationBuilder builder = new BasicPushNotificationBuilder(PushSetActivity.this); +// builder.statusBarDrawable = R.drawable.ic_launcher; +// builder.notificationFlags = Notification.FLAG_AUTO_CANCEL; //设置为点击后自动消失 +// builder.notificationDefaults = Notification.DEFAULT_SOUND; //设置为铃声( Notification.DEFAULT_SOUND)或者震动( Notification.DEFAULT_VIBRATE) +// JPushInterface.setPushNotificationBuilder(1, builder); +// Toast.makeText(PushSetActivity.this, "Basic Builder - 1", Toast.LENGTH_SHORT).show(); +// } +// +// +// /** +// * 设置通知栏样式 - 定义通知栏Layout +// */ +// private void setStyleCustom() { +// CustomPushNotificationBuilder builder = new CustomPushNotificationBuilder(PushSetActivity.this, R.layout.customer_notitfication_layout, R.id.icon, R.id.title, R.id.text); +// builder.layoutIconDrawable = R.drawable.ic_launcher; +// builder.developerArg0 = "developerArg2"; +// JPushInterface.setPushNotificationBuilder(2, builder); +// Toast.makeText(PushSetActivity.this, "Custom Builder - 2", Toast.LENGTH_SHORT).show(); +// } +// +// @Override +// public boolean onKeyDown(int keyCode, KeyEvent event) { +// if (keyCode == KeyEvent.KEYCODE_BACK) { +// finish(); +// } +// return super.onKeyDown(keyCode, event); +// } +// +// private void setAddActionsStyle() { +// MultiActionsNotificationBuilder builder = new MultiActionsNotificationBuilder(PushSetActivity.this); +// builder.addJPushAction(R.drawable.jpush_ic_richpush_actionbar_back, "first", "my_extra1"); +// builder.addJPushAction(R.drawable.jpush_ic_richpush_actionbar_back, "second", "my_extra2"); +// builder.addJPushAction(R.drawable.jpush_ic_richpush_actionbar_back, "third", "my_extra3"); +// JPushInterface.setPushNotificationBuilder(10, builder); +// +// Toast.makeText(PushSetActivity.this, "AddActions Builder - 10", Toast.LENGTH_SHORT).show(); +// } +// +// +// /**===========================================================================**/ +// /**=========================TAG/ALIAS 相关=====================================**/ +// /**===========================================================================**/ +// +// /** +// * 处理tag/alias相关操作的点击 +// * */ +// public void onTagAliasAction(View view) { +// Set tags = null; +// String alias = null; +// int action = -1; +// boolean isAliasAction = false; +// switch (view.getId()){ +// //设置手机号码: +// case R.id.bt_setmobileNumber: +// handleSetMobileNumber(); +// return; +// //增加tag +// case R.id.bt_addtag: +// tags = getInPutTags(); +// if(tags == null){ +// return; +// } +// action = ACTION_ADD; +// break; +// //设置tag +// case R.id.bt_settag: +// tags = getInPutTags(); +// if(tags == null){ +// return; +// } +// action = ACTION_SET; +// break; +// //删除tag +// case R.id.bt_deletetag: +// tags = getInPutTags(); +// if(tags == null){ +// return; +// } +// action = ACTION_DELETE; +// break; +// //获取所有tag +// case R.id.bt_getalltag: +// action = ACTION_GET; +// break; +// //清除所有tag +// case R.id.bt_cleantag: +// action = ACTION_CLEAN; +// break; +// case R.id.bt_checktag: +// tags = getInPutTags(); +// if(tags == null){ +// return; +// } +// action = ACTION_CHECK; +// break; +// //设置alias +// case R.id.bt_setalias: +// alias = getInPutAlias(); +// if(TextUtils.isEmpty(alias)){ +// return; +// } +// isAliasAction = true; +// action = ACTION_SET; +// break; +// //获取alias +// case R.id.bt_getalias: +// isAliasAction = true; +// action = ACTION_GET; +// break; +// //删除alias +// case R.id.bt_deletealias: +// isAliasAction = true; +// action = ACTION_DELETE; +// break; +// default: +// return; +// } +// TagAliasBean tagAliasBean = new TagAliasBean(); +// tagAliasBean.action = action; +// sequence++; +// if(isAliasAction){ +// tagAliasBean.alias = alias; +// }else{ +// tagAliasBean.tags = tags; +// } +// tagAliasBean.isAliasAction = isAliasAction; +// TagAliasOperatorHelper.getInstance().handleAction(getApplicationContext(),sequence,tagAliasBean); +// } +// +// private void handleSetMobileNumber(){ +// EditText mobileEdit = (EditText) findViewById(R.id.et_mobilenumber); +// String mobileNumber = mobileEdit.getText().toString().trim(); +// if (TextUtils.isEmpty(mobileNumber)) { +// Toast.makeText(getApplicationContext(), R.string.mobilenumber_empty_guide, Toast.LENGTH_SHORT).show(); +// } +// if (!ExampleUtil.isValidMobileNumber(mobileNumber)) { +// Toast.makeText(getApplicationContext(), R.string.error_tag_gs_empty, Toast.LENGTH_SHORT).show(); +// return; +// } +// sequence++; +// TagAliasOperatorHelper.getInstance().handleAction(getApplicationContext(),sequence,mobileNumber); +// } +// /** +// * 获取输入的alias +// * */ +// private String getInPutAlias(){ +// EditText aliasEdit = (EditText) findViewById(R.id.et_alias); +// String alias = aliasEdit.getText().toString().trim(); +// if (TextUtils.isEmpty(alias)) { +// Toast.makeText(getApplicationContext(), R.string.error_alias_empty, Toast.LENGTH_SHORT).show(); +// return null; +// } +// if (!ExampleUtil.isValidTagAndAlias(alias)) { +// Toast.makeText(getApplicationContext(), R.string.error_tag_gs_empty, Toast.LENGTH_SHORT).show(); +// return null; +// } +// return alias; +// } +// /** +// * 获取输入的tags +// * */ +// private Set getInPutTags(){ +// EditText tagEdit = (EditText) findViewById(R.id.et_tag); +// String tag = tagEdit.getText().toString().trim(); +// // 检查 tag 的有效性 +// if (TextUtils.isEmpty(tag)) { +// Toast.makeText(getApplicationContext(), R.string.error_tag_empty, Toast.LENGTH_SHORT).show(); +// return null; +// } +// +// // ","隔开的多个 转换成 Set +// String[] sArray = tag.split(","); +// Set tagSet = new LinkedHashSet(); +// for (String sTagItme : sArray) { +// if (!ExampleUtil.isValidTagAndAlias(sTagItme)) { +// Toast.makeText(getApplicationContext(), R.string.error_tag_gs_empty, Toast.LENGTH_SHORT).show(); +// return null; +// } +// tagSet.add(sTagItme); +// } +// if(tagSet.isEmpty()){ +// Toast.makeText(getApplicationContext(), R.string.error_tag_empty, Toast.LENGTH_SHORT).show(); +// return null; +// } +// return tagSet; +// } +//} \ No newline at end of file diff --git a/app/src/main/java/com/appstore/uiui/jpush/Invalid/SettingActivity.java b/app/src/main/java/com/appstore/uiui/jpush/Invalid/SettingActivity.java new file mode 100644 index 0000000..1348751 --- /dev/null +++ b/app/src/main/java/com/appstore/uiui/jpush/Invalid/SettingActivity.java @@ -0,0 +1,197 @@ +package com.appstore.uiui.jpush.Invalid; + +import android.content.SharedPreferences; +import android.content.SharedPreferences.Editor; +import android.os.Bundle; +import android.text.TextUtils; +import android.text.format.DateFormat; +import android.view.KeyEvent; +import android.view.View; +import android.view.View.OnClickListener; +import android.widget.Button; +import android.widget.CheckBox; +import android.widget.TimePicker; +import android.widget.Toast; + +import java.util.HashSet; +import java.util.Set; + +import cn.jpush.android.api.InstrumentedActivity; +import cn.jpush.android.api.JPushInterface; + import com.appstore.uiui.R; + +//public class SettingActivity extends InstrumentedActivity implements OnClickListener { +// TimePicker startTime; +// TimePicker endTime; +// CheckBox mMonday ; +// CheckBox mTuesday ; +// CheckBox mWednesday; +// CheckBox mThursday; +// CheckBox mFriday ; +// CheckBox mSaturday; +// CheckBox mSunday ; +// Button mSetTime; +// SharedPreferences mSettings; +// Editor mEditor; +// +// @Override +// public void onCreate(Bundle icicle) { +// super.onCreate(icicle); +// setContentView(R.layout.set_push_time); +// init(); +// initListener(); +// } +// +// @Override +// public void onStart() { +// super.onStart(); +// initData(); +// } +// +// private void init(){ +// startTime = (TimePicker) findViewById(R.id.start_time); +// endTime = (TimePicker) findViewById(R.id.end_time); +// startTime.setIs24HourView(DateFormat.is24HourFormat(this)); +// endTime.setIs24HourView(DateFormat.is24HourFormat(this)); +// mSetTime = (Button)findViewById(R.id.bu_setTime); +// mMonday = (CheckBox)findViewById(R.id.cb_monday); +// mTuesday = (CheckBox)findViewById(R.id.cb_tuesday); +// mWednesday = (CheckBox)findViewById(R.id.cb_wednesday); +// mThursday = (CheckBox)findViewById(R.id.cb_thursday); +// mFriday = (CheckBox)findViewById(R.id.cb_friday); +// mSaturday = (CheckBox)findViewById(R.id.cb_saturday); +// mSunday = (CheckBox)findViewById(R.id.cb_sunday); +// } +// +// private void initListener(){ +// mSetTime.setOnClickListener(this); +// } +// +// private void initData(){ +// mSettings = getSharedPreferences(ExampleUtil.PREFS_NAME, MODE_PRIVATE); +// String days = mSettings.getString(ExampleUtil.PREFS_DAYS, ""); +// if (!TextUtils.isEmpty(days)) { +// initAllWeek(false); +// String[] sArray = days.split(","); +// for (String day : sArray) { +// setWeek(day); +// } +// } else { +// initAllWeek(true); +// } +// +// int startTimeStr = mSettings.getInt(ExampleUtil.PREFS_START_TIME, 0); +// startTime.setCurrentHour(startTimeStr); +// int endTimeStr = mSettings.getInt(ExampleUtil.PREFS_END_TIME, 23); +// endTime.setCurrentHour(endTimeStr); +// } +// +// @Override +// public void onClick(View v) { +// switch (v.getId()) { +// case R.id.bu_setTime: +// v.requestFocus(); +// v.requestFocusFromTouch(); +// setPushTime(); +// break; +// } +// } +// +// /** +// *设置允许接收通知时间 +// */ +// private void setPushTime(){ +// int startime = startTime.getCurrentHour(); +// int endtime = endTime.getCurrentHour(); +// if (startime > endtime) { +// Toast.makeText(SettingActivity.this, "开始时间不能大于结束时间", Toast.LENGTH_SHORT).show(); +// return; +// } +// StringBuffer daysSB = new StringBuffer(); +// Set days = new HashSet(); +// if (mSunday.isChecked()) { +// days.add(0); +// daysSB.append("0,"); +// } +// if (mMonday.isChecked()) { +// days.add(1); +// daysSB.append("1,"); +// } +// if (mTuesday.isChecked()) { +// days.add(2); +// daysSB.append("2,"); +// } +// if (mWednesday.isChecked()) { +// days.add(3); +// daysSB.append("3,"); +// } +// if (mThursday.isChecked()) { +// days.add(4); +// daysSB.append("4,"); +// } +// if (mFriday.isChecked()) { +// days.add(5); +// daysSB.append("5,"); +// } +// if (mSaturday.isChecked()) { +// days.add(6); +// daysSB.append("6,"); +// } +// +// +// //调用JPush api设置Push时间 +// JPushInterface.setPushTime(getApplicationContext(), days, startime, endtime); +// +// mEditor = mSettings.edit(); +// mEditor.putString(ExampleUtil.PREFS_DAYS, daysSB.toString()); +// mEditor.putInt(ExampleUtil.PREFS_START_TIME, startime); +// mEditor.putInt(ExampleUtil.PREFS_END_TIME, endtime); +// mEditor.commit(); +// Toast.makeText(SettingActivity.this, R.string.setting_su, Toast.LENGTH_SHORT).show(); +// } +// +// @Override +// public boolean onKeyDown(int keyCode, KeyEvent event) { +// if (keyCode == KeyEvent.KEYCODE_BACK){ +// finish(); +// } +// return super.onKeyDown(keyCode, event); +// } +// +// private void setWeek(String day){ +// int dayId = Integer.valueOf(day); +// switch (dayId) { +// case 0: +// mSunday.setChecked(true); +// break; +// case 1: +// mMonday.setChecked(true); +// break; +// case 2: +// mTuesday.setChecked(true); +// break; +// case 3: +// mWednesday.setChecked(true); +// break; +// case 4: +// mThursday.setChecked(true); +// break; +// case 5: +// mFriday.setChecked(true); +// break; +// case 6: +// mSaturday.setChecked(true); +// break; +// } +// } +// +// private void initAllWeek(boolean isChecked) { +// mSunday.setChecked(isChecked); +// mMonday.setChecked(isChecked); +// mTuesday.setChecked(isChecked); +// mWednesday.setChecked(isChecked); +// mThursday.setChecked(isChecked); +// mFriday.setChecked(isChecked); +// mSaturday.setChecked(isChecked); +// } +//} \ No newline at end of file diff --git a/app/src/main/java/com/appstore/uiui/jpush/Invalid/TestActivity.java b/app/src/main/java/com/appstore/uiui/jpush/Invalid/TestActivity.java new file mode 100644 index 0000000..1fed3ad --- /dev/null +++ b/app/src/main/java/com/appstore/uiui/jpush/Invalid/TestActivity.java @@ -0,0 +1,32 @@ +package com.appstore.uiui.jpush.Invalid; + +import android.app.Activity; +import android.content.Intent; +import android.os.Bundle; +import android.view.ViewGroup.LayoutParams; +import android.widget.TextView; + +import cn.jpush.android.api.JPushInterface; + +public class TestActivity extends Activity { + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + TextView tv = new TextView(this); + tv.setText("用户自定义打开的Activity"); + Intent intent = getIntent(); + if (null != intent) { + Bundle bundle = getIntent().getExtras(); + String title = null; + String content = null; + if(bundle!=null){ + title = bundle.getString(JPushInterface.EXTRA_NOTIFICATION_TITLE); + content = bundle.getString(JPushInterface.EXTRA_ALERT); + } + tv.setText("Title : " + title + " " + "Content : " + content); + } + addContentView(tv, new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT)); + } + +} diff --git a/app/src/main/java/com/appstore/uiui/jpush/LocalBroadcastManager.java b/app/src/main/java/com/appstore/uiui/jpush/LocalBroadcastManager.java new file mode 100644 index 0000000..a3bee04 --- /dev/null +++ b/app/src/main/java/com/appstore/uiui/jpush/LocalBroadcastManager.java @@ -0,0 +1,263 @@ +package com.appstore.uiui.jpush; + +import android.content.BroadcastReceiver; +import android.content.Context; +import android.content.Intent; +import android.content.IntentFilter; +import android.net.Uri; +import android.os.Handler; +import android.os.Message; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Set; + +/** + * Created by efan on 2017/4/14. + */ + +public final class LocalBroadcastManager { + private static final String TAG = "JIGUANG-Example"; + private static final boolean DEBUG = false; + private final Context mAppContext; + private final HashMap> mReceivers = new HashMap>(); + private final HashMap> mActions = new HashMap> (); + private final ArrayList mPendingBroadcasts = new ArrayList(); + static final int MSG_EXEC_PENDING_BROADCASTS = 1; + private final Handler mHandler; + private static final Object mLock = new Object(); + private static LocalBroadcastManager mInstance; + + public static LocalBroadcastManager getInstance(Context context) { + Object var1 = mLock; + synchronized (mLock) { + if (mInstance == null) { + mInstance = new LocalBroadcastManager(context.getApplicationContext()); + } + + return mInstance; + } + } + + private LocalBroadcastManager(Context context) { + this.mAppContext = context; + this.mHandler = new Handler(context.getMainLooper()) { + public void handleMessage(Message msg) { + switch (msg.what) { + case 1: + LocalBroadcastManager.this.executePendingBroadcasts(); + break; + default: + super.handleMessage(msg); + } + + } + }; + } + + public void registerReceiver(BroadcastReceiver receiver, IntentFilter filter) { + HashMap var3 = this.mReceivers; + synchronized (this.mReceivers) { + ReceiverRecord entry = new ReceiverRecord(filter, receiver); + ArrayList filters = (ArrayList) this.mReceivers.get(receiver); + if (filters == null) { + filters = new ArrayList(1); + this.mReceivers.put(receiver, filters); + } + + filters.add(filter); + + for (int i = 0; i < filter.countActions(); ++i) { + String action = filter.getAction(i); + ArrayList entries = (ArrayList) this.mActions.get(action); + if (entries == null) { + entries = new ArrayList(1); + this.mActions.put(action, entries); + } + + entries.add(entry); + } + + } + } + + public void unregisterReceiver(BroadcastReceiver receiver) { + HashMap var2 = this.mReceivers; + synchronized (this.mReceivers) { + ArrayList filters = (ArrayList) this.mReceivers.remove(receiver); + if (filters != null) { + for (int i = 0; i < filters.size(); ++i) { + IntentFilter filter = (IntentFilter) filters.get(i); + + for (int j = 0; j < filter.countActions(); ++j) { + String action = filter.getAction(j); + ArrayList receivers = (ArrayList) this.mActions.get(action); + if (receivers != null) { + for (int k = 0; k < receivers.size(); ++k) { + if (((ReceiverRecord) receivers.get(k)).receiver == receiver) { + receivers.remove(k); + --k; + } + } + + if (receivers.size() <= 0) { + this.mActions.remove(action); + } + } + } + } + + } + } + } + + public boolean sendBroadcast(Intent intent) { + HashMap var2 = this.mReceivers; + synchronized (this.mReceivers) { + String action = intent.getAction(); + String type = intent.resolveTypeIfNeeded(this.mAppContext.getContentResolver()); + Uri data = intent.getData(); + String scheme = intent.getScheme(); + Set categories = intent.getCategories(); + boolean debug = (intent.getFlags() & 8) != 0; + if (debug) { + Logger.v("LocalBroadcastManager", "Resolving type " + type + " scheme " + scheme + " of intent " + intent); + } + + ArrayList entries = (ArrayList) this.mActions.get(intent.getAction()); + if (entries != null) { + if (debug) { + Logger.v("LocalBroadcastManager", "Action list: " + entries); + } + + ArrayList receivers = null; + + int i; + for (i = 0; i < entries.size(); ++i) { + ReceiverRecord receiver = (ReceiverRecord) entries.get(i); + if (debug) { + Logger.v("LocalBroadcastManager", "Matching against filter " + receiver.filter); + } + + if (receiver.broadcasting) { + if (debug) { + Logger.v("LocalBroadcastManager", " Filter\'s target already added"); + } + } else { + int match = receiver.filter.match(action, type, scheme, data, categories, "LocalBroadcastManager"); + if (match >= 0) { + if (debug) { + Logger.v("LocalBroadcastManager", " Filter matched! match=0x" + Integer.toHexString(match)); + } + + if (receivers == null) { + receivers = new ArrayList(); + } + + receivers.add(receiver); + receiver.broadcasting = true; + } else if (debug) { + String reason; + switch (match) { + case -4: + reason = "category"; + break; + case -3: + reason = "action"; + break; + case -2: + reason = "data"; + break; + case -1: + reason = "type"; + break; + default: + reason = "unknown reason"; + } + + Logger.v("LocalBroadcastManager", " Filter did not match: " + reason); + } + } + } + + if (receivers != null) { + for (i = 0; i < receivers.size(); ++i) { + ((ReceiverRecord) receivers.get(i)).broadcasting = false; + } + + this.mPendingBroadcasts.add(new BroadcastRecord(intent, receivers)); + if (!this.mHandler.hasMessages(1)) { + this.mHandler.sendEmptyMessage(1); + } + + return true; + } + } + + return false; + } + } + + public void sendBroadcastSync(Intent intent) { + if (this.sendBroadcast(intent)) { + this.executePendingBroadcasts(); + } + + } + + private void executePendingBroadcasts() { + while (true) { + BroadcastRecord[] brs = null; + HashMap i = this.mReceivers; + synchronized (this.mReceivers) { + int br = this.mPendingBroadcasts.size(); + if (br <= 0) { + return; + } + + brs = new BroadcastRecord[br]; + this.mPendingBroadcasts.toArray(brs); + this.mPendingBroadcasts.clear(); + } + + for (int var6 = 0; var6 < brs.length; ++var6) { + BroadcastRecord var7 = brs[var6]; + + for (int j = 0; j < var7.receivers.size(); ++j) { + ((ReceiverRecord) var7.receivers.get(j)).receiver.onReceive(this.mAppContext, var7.intent); + } + } + } + } + + private static class BroadcastRecord { + final Intent intent; + final ArrayList receivers; + + BroadcastRecord(Intent _intent, ArrayList _receivers) { + this.intent = _intent; + this.receivers = _receivers; + } + } + + private static class ReceiverRecord { + final IntentFilter filter; + final BroadcastReceiver receiver; + boolean broadcasting; + + ReceiverRecord(IntentFilter _filter, BroadcastReceiver _receiver) { + this.filter = _filter; + this.receiver = _receiver; + } + + public String toString() { + StringBuilder builder = new StringBuilder(128); + builder.append("Receiver{"); + builder.append(this.receiver); + builder.append(" filter="); + builder.append(this.filter); + builder.append("}"); + return builder.toString(); + } + } +} \ No newline at end of file diff --git a/app/src/main/java/com/appstore/uiui/jpush/Logger.java b/app/src/main/java/com/appstore/uiui/jpush/Logger.java new file mode 100644 index 0000000..9c65cae --- /dev/null +++ b/app/src/main/java/com/appstore/uiui/jpush/Logger.java @@ -0,0 +1,40 @@ +package com.appstore.uiui.jpush; + +import android.util.Log; + +/** + * Created by efan on 2017/4/13. + */ + +public class Logger { + + //设为false关闭日志 + private static final boolean LOG_ENABLE = true; + + public static void i(String tag, String msg){ + if (LOG_ENABLE){ + Log.i(tag, msg); + } + } + public static void v(String tag, String msg){ + if (LOG_ENABLE){ + Log.v(tag, msg); + } + } + public static void d(String tag, String msg){ + if (LOG_ENABLE){ + Log.d(tag, msg); + } + } + public static void w(String tag, String msg){ + if (LOG_ENABLE){ + Log.w(tag, msg); + } + } + public static void e(String tag, String msg){ + if (LOG_ENABLE){ + Log.e(tag, msg); + } + } + +} diff --git a/app/src/main/java/com/appstore/uiui/jpush/MyJPushMessageReceiver.java b/app/src/main/java/com/appstore/uiui/jpush/MyJPushMessageReceiver.java new file mode 100644 index 0000000..dcc513d --- /dev/null +++ b/app/src/main/java/com/appstore/uiui/jpush/MyJPushMessageReceiver.java @@ -0,0 +1,44 @@ +package com.appstore.uiui.jpush; + +import android.content.Context; + +import com.appstore.uiui.MyApplication; + +import cn.jpush.android.api.CustomMessage; +import cn.jpush.android.api.JPushMessage; +import cn.jpush.android.service.JPushMessageReceiver; + +/** + * 自定义JPush message 接收器,包括操作tag/alias的结果返回(仅仅包含tag/alias新接口部分) + * */ +public class MyJPushMessageReceiver extends JPushMessageReceiver { + + @Override + public void onTagOperatorResult(Context context,JPushMessage jPushMessage) { + TagAliasOperatorHelper.getInstance().onTagOperatorResult(context,jPushMessage); + super.onTagOperatorResult(context, jPushMessage); + } + @Override + public void onCheckTagOperatorResult(Context context,JPushMessage jPushMessage){ + TagAliasOperatorHelper.getInstance().onCheckTagOperatorResult(context,jPushMessage); + super.onCheckTagOperatorResult(context, jPushMessage); + } + @Override + public void onAliasOperatorResult(Context context, JPushMessage jPushMessage) { + TagAliasOperatorHelper.getInstance().onAliasOperatorResult(context,jPushMessage); + super.onAliasOperatorResult(context, jPushMessage); + + } + + @Override + public void onMobileNumberOperatorResult(Context context, JPushMessage jPushMessage) { + TagAliasOperatorHelper.getInstance().onMobileNumberOperatorResult(context,jPushMessage); + super.onMobileNumberOperatorResult(context, jPushMessage); + } + + @Override + public void onMessage(Context context, CustomMessage customMessage) { + super.onMessage(context, customMessage); + MyApplication.getInstance().manageCustomMessage(customMessage); + } +} diff --git a/app/src/main/java/com/appstore/uiui/jpush/MyReceiver.java b/app/src/main/java/com/appstore/uiui/jpush/MyReceiver.java new file mode 100644 index 0000000..6290f7f --- /dev/null +++ b/app/src/main/java/com/appstore/uiui/jpush/MyReceiver.java @@ -0,0 +1,129 @@ +package com.appstore.uiui.jpush; + +import android.content.BroadcastReceiver; +import android.content.Context; +import android.content.Intent; +import android.os.Bundle; +import android.text.TextUtils; + +import com.appstore.uiui.activity.MainActivity; + +import org.json.JSONException; +import org.json.JSONObject; + +import java.util.Iterator; + +import cn.jpush.android.api.JPushInterface; + +/** + * 自定义接收器 + * + * 如果不定义这个 Receiver,则: + * 1) 默认用户会打开主界面 + * 2) 接收不到自定义消息 + */ +public class MyReceiver extends BroadcastReceiver { + private static final String TAG = "JIGUANG-Example"; + + @Override + public void onReceive(Context context, Intent intent) { + try { + Bundle bundle = intent.getExtras(); + Logger.d(TAG, "[MyReceiver] onReceive - " + intent.getAction() + ", extras: " + printBundle(bundle)); + + if (JPushInterface.ACTION_REGISTRATION_ID.equals(intent.getAction())) { + String regId = bundle.getString(JPushInterface.EXTRA_REGISTRATION_ID); + Logger.d(TAG, "[MyReceiver] 接收Registration Id : " + regId); + //send the Registration Id to your server... + + } else if (JPushInterface.ACTION_MESSAGE_RECEIVED.equals(intent.getAction())) { + Logger.d(TAG, "[MyReceiver] 接收到推送下来的自定义消息: " + bundle.getString(JPushInterface.EXTRA_MESSAGE)); + processCustomMessage(context, bundle); + + } else if (JPushInterface.ACTION_NOTIFICATION_RECEIVED.equals(intent.getAction())) { + Logger.d(TAG, "[MyReceiver] 接收到推送下来的通知"); + int notifactionId = bundle.getInt(JPushInterface.EXTRA_NOTIFICATION_ID); + Logger.d(TAG, "[MyReceiver] 接收到推送下来的通知的ID: " + notifactionId); + + } else if (JPushInterface.ACTION_NOTIFICATION_OPENED.equals(intent.getAction())) { + Logger.d(TAG, "[MyReceiver] 用户点击打开了通知"); + + //打开自定义的Activity +// Intent i = new Intent(context, TestActivity.class); +// i.putExtras(bundle); + //i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); +// i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP ); +// context.startActivity(i); + + } else if (JPushInterface.ACTION_RICHPUSH_CALLBACK.equals(intent.getAction())) { + Logger.d(TAG, "[MyReceiver] 用户收到到RICH PUSH CALLBACK: " + bundle.getString(JPushInterface.EXTRA_EXTRA)); + //在这里根据 JPushInterface.EXTRA_EXTRA 的内容处理代码,比如打开新的Activity, 打开一个网页等.. + + } else if(JPushInterface.ACTION_CONNECTION_CHANGE.equals(intent.getAction())) { + boolean connected = intent.getBooleanExtra(JPushInterface.EXTRA_CONNECTION_CHANGE, false); + Logger.w(TAG, "[MyReceiver]" + intent.getAction() +" connected state change to "+connected); + } else { + Logger.d(TAG, "[MyReceiver] Unhandled intent - " + intent.getAction()); + } + } catch (Exception e){ + + } + + } + + // 打印所有的 intent extra 数据 + private static String printBundle(Bundle bundle) { + StringBuilder sb = new StringBuilder(); + for (String key : bundle.keySet()) { + if (key.equals(JPushInterface.EXTRA_NOTIFICATION_ID)) { + sb.append("\nkey:" + key + ", value:" + bundle.getInt(key)); + }else if(key.equals(JPushInterface.EXTRA_CONNECTION_CHANGE)){ + sb.append("\nkey:" + key + ", value:" + bundle.getBoolean(key)); + } else if (key.equals(JPushInterface.EXTRA_EXTRA)) { + if (TextUtils.isEmpty(bundle.getString(JPushInterface.EXTRA_EXTRA))) { + Logger.i(TAG, "This message has no Extra data"); + continue; + } + + try { + JSONObject json = new JSONObject(bundle.getString(JPushInterface.EXTRA_EXTRA)); + Iterator it = json.keys(); + + while (it.hasNext()) { + String myKey = it.next(); + sb.append("\nkey:" + key + ", value: [" + + myKey + " - " +json.optString(myKey) + "]"); + } + } catch (JSONException e) { + Logger.e(TAG, "Get message extra JSON error!"); + } + + } else { + sb.append("\nkey:" + key + ", value:" + bundle.get(key)); + } + } + return sb.toString(); + } + + //send msg to MainActivity + private void processCustomMessage(Context context, Bundle bundle) { + if (MainActivity.isForeground) { + String message = bundle.getString(JPushInterface.EXTRA_MESSAGE); + String extras = bundle.getString(JPushInterface.EXTRA_EXTRA); + Intent msgIntent = new Intent(MainActivity.MESSAGE_RECEIVED_ACTION); + msgIntent.putExtra(MainActivity.KEY_MESSAGE, message); + if (!ExampleUtil.isEmpty(extras)) { + try { + JSONObject extraJson = new JSONObject(extras); + if (extraJson.length() > 0) { + msgIntent.putExtra(MainActivity.KEY_EXTRAS, extras); + } + } catch (JSONException e) { + + } + + } + LocalBroadcastManager.getInstance(context).sendBroadcast(msgIntent); + } + } +} diff --git a/app/src/main/java/com/appstore/uiui/jpush/PushService.java b/app/src/main/java/com/appstore/uiui/jpush/PushService.java new file mode 100644 index 0000000..b5d61fb --- /dev/null +++ b/app/src/main/java/com/appstore/uiui/jpush/PushService.java @@ -0,0 +1,7 @@ +package com.appstore.uiui.jpush; + +import cn.jpush.android.service.JCommonService; + +public class PushService extends JCommonService { + +} diff --git a/app/src/main/java/com/appstore/uiui/jpush/TagAliasOperatorHelper.java b/app/src/main/java/com/appstore/uiui/jpush/TagAliasOperatorHelper.java new file mode 100644 index 0000000..4feca3e --- /dev/null +++ b/app/src/main/java/com/appstore/uiui/jpush/TagAliasOperatorHelper.java @@ -0,0 +1,338 @@ +package com.appstore.uiui.jpush; + +import android.content.Context; +import android.os.Handler; +import android.os.Message; +import android.util.SparseArray; + +import java.util.Locale; +import java.util.Set; + +import cn.jpush.android.api.JPushInterface; +import cn.jpush.android.api.JPushMessage; + +/** + * 处理tagalias相关的逻辑 + * */ +public class TagAliasOperatorHelper { + private static final String TAG = "JIGUANG-TagAliasHelper"; + public static int sequence = 1; + /**增加*/ + public static final int ACTION_ADD = 1; + /**覆盖*/ + public static final int ACTION_SET = 2; + /**删除部分*/ + public static final int ACTION_DELETE = 3; + /**删除所有*/ + public static final int ACTION_CLEAN = 4; + /**查询*/ + public static final int ACTION_GET = 5; + + public static final int ACTION_CHECK = 6; + + public static final int DELAY_SEND_ACTION = 1; + + public static final int DELAY_SET_MOBILE_NUMBER_ACTION = 2; + + private Context context; + + private static TagAliasOperatorHelper mInstance; + private TagAliasOperatorHelper(){ + } + public static TagAliasOperatorHelper getInstance(){ + if(mInstance == null){ + synchronized (TagAliasOperatorHelper.class){ + if(mInstance == null){ + mInstance = new TagAliasOperatorHelper(); + } + } + } + return mInstance; + } + public void init(Context context){ + if(context != null) { + this.context = context.getApplicationContext(); + } + } + private SparseArray setActionCache = new SparseArray(); + + public Object get(int sequence){ + return setActionCache.get(sequence); + } + public Object remove(int sequence){ + return setActionCache.get(sequence); + } + public void put(int sequence,Object tagAliasBean){ + setActionCache.put(sequence,tagAliasBean); + } + private Handler delaySendHandler = new Handler(){ + @Override + public void handleMessage(Message msg) { + switch (msg.what){ + case DELAY_SEND_ACTION: + if(msg.obj !=null && msg.obj instanceof TagAliasBean){ + Logger.i(TAG,"on delay time"); + sequence++; + TagAliasBean tagAliasBean = (TagAliasBean) msg.obj; + setActionCache.put(sequence, tagAliasBean); + if(context!=null) { + handleAction(context, sequence, tagAliasBean); + }else{ + Logger.e(TAG,"#unexcepted - context was null"); + } + }else{ + Logger.w(TAG,"#unexcepted - msg obj was incorrect"); + } + break; + case DELAY_SET_MOBILE_NUMBER_ACTION: + if(msg.obj !=null && msg.obj instanceof String) { + Logger.i(TAG, "retry set mobile number"); + sequence++; + String mobileNumber = (String) msg.obj; + setActionCache.put(sequence, mobileNumber); + if(context !=null) { + handleAction(context, sequence, mobileNumber); + }else { + Logger.e(TAG, "#unexcepted - context was null"); + } + }else{ + Logger.w(TAG,"#unexcepted - msg obj was incorrect"); + } + break; + } + } + }; + public void handleAction(Context context,int sequence,String mobileNumber){ + put(sequence,mobileNumber); + Logger.d(TAG,"sequence:"+sequence+",mobileNumber:"+mobileNumber); + JPushInterface.setMobileNumber(context,sequence,mobileNumber); + } + /** + * 处理设置tag + * */ + public void handleAction(Context context,int sequence, TagAliasBean tagAliasBean){ + init(context); + if(tagAliasBean == null){ + Logger.w(TAG,"tagAliasBean was null"); + return; + } + put(sequence,tagAliasBean); + if(tagAliasBean.isAliasAction){ + switch (tagAliasBean.action){ + case ACTION_GET: + JPushInterface.getAlias(context,sequence); + break; + case ACTION_DELETE: + JPushInterface.deleteAlias(context,sequence); + break; + case ACTION_SET: + JPushInterface.setAlias(context,sequence,tagAliasBean.alias); + break; + default: + Logger.w(TAG,"unsupport alias action type"); + return; + } + }else { + switch (tagAliasBean.action) { + case ACTION_ADD: + JPushInterface.addTags(context, sequence, tagAliasBean.tags); + break; + case ACTION_SET: + JPushInterface.setTags(context, sequence, tagAliasBean.tags); + break; + case ACTION_DELETE: + JPushInterface.deleteTags(context, sequence, tagAliasBean.tags); + break; + case ACTION_CHECK: + //一次只能check一个tag + String tag = (String)tagAliasBean.tags.toArray()[0]; + JPushInterface.checkTagBindState(context,sequence,tag); + break; + case ACTION_GET: + JPushInterface.getAllTags(context, sequence); + break; + case ACTION_CLEAN: + JPushInterface.cleanTags(context, sequence); + break; + default: + Logger.w(TAG,"unsupport tag action type"); + return; + } + } + } + private boolean RetryActionIfNeeded(int errorCode,TagAliasBean tagAliasBean){ + if(!ExampleUtil.isConnected(context)){ + Logger.w(TAG,"no network"); + return false; + } + //返回的错误码为6002 超时,6014 服务器繁忙,都建议延迟重试 + if(errorCode == 6002 || errorCode == 6014){ + Logger.d(TAG,"need retry"); + if(tagAliasBean!=null){ + Message message = new Message(); + message.what = DELAY_SEND_ACTION; + message.obj = tagAliasBean; + delaySendHandler.sendMessageDelayed(message,1000*60); + String logs =getRetryStr(tagAliasBean.isAliasAction, tagAliasBean.action,errorCode); + ExampleUtil.showToast(logs, context); + return true; + } + } + return false; + } + private boolean RetrySetMObileNumberActionIfNeeded(int errorCode,String mobileNumber){ + if(!ExampleUtil.isConnected(context)){ + Logger.w(TAG,"no network"); + return false; + } + //返回的错误码为6002 超时,6024 服务器内部错误,建议稍后重试 + if(errorCode == 6002 || errorCode == 6024){ + Logger.d(TAG,"need retry"); + Message message = new Message(); + message.what = DELAY_SET_MOBILE_NUMBER_ACTION; + message.obj = mobileNumber; + delaySendHandler.sendMessageDelayed(message,1000*60); + String str = "Failed to set mobile number due to %s. Try again after 60s."; + str = String.format(Locale.ENGLISH,str,(errorCode == 6002 ? "timeout" : "server internal error”")); + ExampleUtil.showToast(str, context); + return true; + } + return false; + + } + private String getRetryStr(boolean isAliasAction,int actionType,int errorCode){ + String str = "Failed to %s %s due to %s. Try again after 60s."; + str = String.format(Locale.ENGLISH,str,getActionStr(actionType),(isAliasAction? "alias" : " tags") ,(errorCode == 6002 ? "timeout" : "server too busy")); + return str; + } + + private String getActionStr(int actionType){ + switch (actionType){ + case ACTION_ADD: + return "add"; + case ACTION_SET: + return "set"; + case ACTION_DELETE: + return "delete"; + case ACTION_GET: + return "get"; + case ACTION_CLEAN: + return "clean"; + case ACTION_CHECK: + return "check"; + } + return "unkonw operation"; + } + public void onTagOperatorResult(Context context, JPushMessage jPushMessage) { + int sequence = jPushMessage.getSequence(); + Logger.i(TAG,"action - onTagOperatorResult, sequence:"+sequence+",tags:"+jPushMessage.getTags()); + Logger.i(TAG,"tags size:"+jPushMessage.getTags().size()); + init(context); + //根据sequence从之前操作缓存中获取缓存记录 + TagAliasBean tagAliasBean = (TagAliasBean)setActionCache.get(sequence); + if(tagAliasBean == null){ + ExampleUtil.showToast("获取缓存记录失败", context); + return; + } + if(jPushMessage.getErrorCode() == 0){ + Logger.i(TAG,"action - modify tag Success,sequence:"+sequence); + setActionCache.remove(sequence); + String logs = getActionStr(tagAliasBean.action)+" tags success"; + Logger.i(TAG,logs); + ExampleUtil.showToast(logs, context); + }else{ + String logs = "Failed to " + getActionStr(tagAliasBean.action)+" tags"; + if(jPushMessage.getErrorCode() == 6018){ + //tag数量超过限制,需要先清除一部分再add + logs += ", tags is exceed limit need to clean"; + } + logs += ", errorCode:" + jPushMessage.getErrorCode(); + Logger.e(TAG, logs); + if(!RetryActionIfNeeded(jPushMessage.getErrorCode(),tagAliasBean)) { + ExampleUtil.showToast(logs, context); + } + } + } + public void onCheckTagOperatorResult(Context context, JPushMessage jPushMessage){ + int sequence = jPushMessage.getSequence(); + Logger.i(TAG,"action - onCheckTagOperatorResult, sequence:"+sequence+",checktag:"+jPushMessage.getCheckTag()); + init(context); + //根据sequence从之前操作缓存中获取缓存记录 + TagAliasBean tagAliasBean = (TagAliasBean)setActionCache.get(sequence); + if(tagAliasBean == null){ + ExampleUtil.showToast("获取缓存记录失败", context); + return; + } + if(jPushMessage.getErrorCode() == 0){ + Logger.i(TAG,"tagBean:"+tagAliasBean); + setActionCache.remove(sequence); + String logs = getActionStr(tagAliasBean.action)+" tag "+jPushMessage.getCheckTag() + " bind state success,state:"+jPushMessage.getTagCheckStateResult(); + Logger.i(TAG,logs); + ExampleUtil.showToast(logs, context); + }else{ + String logs = "Failed to " + getActionStr(tagAliasBean.action)+" tags, errorCode:" + jPushMessage.getErrorCode(); + Logger.e(TAG, logs); + if(!RetryActionIfNeeded(jPushMessage.getErrorCode(),tagAliasBean)) { + ExampleUtil.showToast(logs, context); + } + } + } + public void onAliasOperatorResult(Context context, JPushMessage jPushMessage) { + int sequence = jPushMessage.getSequence(); + Logger.i(TAG,"action - onAliasOperatorResult, sequence:"+sequence+",alias:"+jPushMessage.getAlias()); + init(context); + //根据sequence从之前操作缓存中获取缓存记录 + TagAliasBean tagAliasBean = (TagAliasBean)setActionCache.get(sequence); + if(tagAliasBean == null){ + ExampleUtil.showToast("获取缓存记录失败", context); + return; + } + if(jPushMessage.getErrorCode() == 0){ + Logger.i(TAG,"action - modify alias Success,sequence:"+sequence); + setActionCache.remove(sequence); + String logs = getActionStr(tagAliasBean.action)+" alias success"; + Logger.i(TAG,logs); + ExampleUtil.showToast(logs, context); + }else{ + String logs = "Failed to " + getActionStr(tagAliasBean.action)+" alias, errorCode:" + jPushMessage.getErrorCode(); + Logger.e(TAG, logs); + if(!RetryActionIfNeeded(jPushMessage.getErrorCode(),tagAliasBean)) { + ExampleUtil.showToast(logs, context); + } + } + } + //设置手机号码回调 + public void onMobileNumberOperatorResult(Context context, JPushMessage jPushMessage) { + int sequence = jPushMessage.getSequence(); + Logger.i(TAG,"action - onMobileNumberOperatorResult, sequence:"+sequence+",mobileNumber:"+jPushMessage.getMobileNumber()); + init(context); + if(jPushMessage.getErrorCode() == 0){ + Logger.i(TAG,"action - set mobile number Success,sequence:"+sequence); + setActionCache.remove(sequence); + }else{ + String logs = "Failed to set mobile number, errorCode:" + jPushMessage.getErrorCode(); + Logger.e(TAG, logs); + if(!RetrySetMObileNumberActionIfNeeded(jPushMessage.getErrorCode(),jPushMessage.getMobileNumber())){ + ExampleUtil.showToast(logs, context); + } + } + } + public static class TagAliasBean{ + public int action; + public Set tags; + public String alias; + public boolean isAliasAction; + + @Override + public String toString() { + return "TagAliasBean{" + + "action=" + action + + ", tags=" + tags + + ", alias='" + alias + '\'' + + ", isAliasAction=" + isAliasAction + + '}'; + } + } + + +} diff --git a/app/src/main/java/com/appstore/uiui/listener/LogDownloadListener.java b/app/src/main/java/com/appstore/uiui/listener/LogDownloadListener.java new file mode 100644 index 0000000..b43a9c0 --- /dev/null +++ b/app/src/main/java/com/appstore/uiui/listener/LogDownloadListener.java @@ -0,0 +1,63 @@ +/* + * Copyright 2016 jeasonlzy(廖子尧) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.appstore.uiui.listener; + +import com.lzy.okgo.model.Progress; +import com.lzy.okserver.download.DownloadListener; + +import java.io.File; + +/** + * ================================================ + * 作 者:jeasonlzy(廖子尧)Github地址:https://github.com/jeasonlzy + * 版 本:1.0 + * 创建日期:2017/6/7 + * 描 述: + * 修订历史: + * ================================================ + */ +public class LogDownloadListener extends DownloadListener { + + public LogDownloadListener() { + super("LogDownloadListener"); + } + + @Override + public void onStart(Progress progress) { + System.out.println("onStart: " + progress); + } + + @Override + public void onProgress(Progress progress) { + System.out.println("onProgress: " + progress); + } + + @Override + public void onError(Progress progress) { + System.out.println("onError: " + progress); + progress.exception.printStackTrace(); + } + + @Override + public void onFinish(File file, Progress progress) { + System.out.println("onFinish: " + progress); + } + + @Override + public void onRemove(Progress progress) { + System.out.println("onRemove: " + progress); + } +} diff --git a/app/src/main/java/com/appstore/uiui/network/OKGOPost.java b/app/src/main/java/com/appstore/uiui/network/OKGOPost.java index 39fe6fb..b299002 100644 --- a/app/src/main/java/com/appstore/uiui/network/OKGOPost.java +++ b/app/src/main/java/com/appstore/uiui/network/OKGOPost.java @@ -1,59 +1,248 @@ package com.appstore.uiui.network; +import android.content.Context; import android.os.Handler; import android.os.Message; import android.util.Log; +import androidx.annotation.NonNull; + import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; +import com.appstore.uiui.TextCode.MessageWhat; +import com.appstore.uiui.base.UserInfo; import com.appstore.uiui.bean.AppInfo; import com.appstore.uiui.network.URLs.Url; import com.appstore.uiui.utils.LogUtils; +import com.appstore.uiui.utils.SPUtils; import com.appstore.uiui.utils.ToastUtil; +import com.appstore.uiui.utils.Utils; import com.lzy.okgo.OkGo; import com.lzy.okgo.callback.StringCallback; import com.lzy.okgo.model.Response; - import java.util.List; -import okhttp3.Call; - public class OKGOPost { + private static final int GET_ALL_APPINFO = 0; + private static final int GET_USERINFO = 1; + private static final int GET_SORTAPP = 2; + + private Handler mhandler = new Handler() { + @Override + public void handleMessage(@NonNull Message msg) { + super.handleMessage(msg); + switch (msg.what) { + case GET_ALL_APPINFO: + break; + case GET_USERINFO: + + break; + case GET_SORTAPP: + + break; + } + } + }; + + //msg.what=0 synchronized public static void getAllAppInfo(final Handler handler) { - OkGo.post(Url.GET_ALL_APPINFO).execute(new StringCallback() { + OkGo.post(Url.GET_ALL_APPINFO).execute(new StringCallback() { @Override - public void onSuccess(String s, Call call, okhttp3.Response response) { + public void onSuccess(Response response) { try { - JSONObject body = JSON.parseObject(s); -// Log.e("onSuccess", body.toString()); + JSONObject body = JSON.parseObject(response.body()); +// LogUtils.e("onSuccess", body.toString()); + LogUtils.e("fht", "getAllAppInfo onSuccess"); int code = body.getInteger("code"); String msg = body.getString("msg"); String data = body.getString("data"); List applist = JSON.parseArray(data, AppInfo.class); - if (code == 200) { + if (code == MessageWhat.CODE_SUCCESSFUL) { Message message = new Message(); - message.what = 0; + message.what = 1; message.obj = applist; handler.sendMessage(message); } else { ToastUtil.show(msg); + handler.sendEmptyMessage(0); } } catch (Exception e) { - Log.e("Exception", e.getMessage()); + LogUtils.e("Exception", e.getMessage()); ToastUtil.show("服务器错误,请稍后重试"); - + handler.sendEmptyMessage(0); } } + @Override - public void onError(Call call, okhttp3.Response response, Exception e) { - super.onError(call, response, e); - LogUtils.e("Exception", e.getMessage()); + public void onError(Response response) { + super.onError(response); + LogUtils.e("onError", response.getException().toString()); ToastUtil.show("网络连接失败,检查网络连接"); + handler.sendEmptyMessage(0); + } }); + } + + //msg.what=1 + synchronized public static void getUserInfo(final Handler handler) { + String sn = Utils.getSerial(); + OkGo.post(Url.GET_INFO_FROMESN) + .params("sn", sn) + .execute(new StringCallback() { + @Override + public void onSuccess(Response response) { + LogUtils.e("fht", "getUserInfo onSuccess"); + JSONObject jsonObject = JSON.parseObject(response.body()); + int code = jsonObject.getInteger("code"); + String msg = jsonObject.getString("msg"); + if (code == MessageWhat.CODE_SUCCESSFUL) { + String data = jsonObject.getString("data"); + UserInfo userInfo = JSON.parseObject(data, UserInfo.class); + Message message = new Message(); + message.what = 1; + message.obj = userInfo; + handler.sendMessage(message); + } else { + ToastUtil.show(msg); + } + } + + @Override + public void onError(Response response) { + super.onError(response); + LogUtils.e("onError", response.getException().toString()); + ToastUtil.show("网络连接失败,检查网络连接"); + } + }); + } + + //msg.what=2 + synchronized public static void getUserInfo(final Context context) { + OkGo.post(Url.GET_INFO_FROMESN) + .params("sn", Utils.getSerial()) + .execute(new StringCallback() { + @Override + public void onSuccess(Response response) { + LogUtils.e("fht", "getUserInfo onSuccess"); + JSONObject jsonObject = JSON.parseObject(response.body()); + int code = jsonObject.getInteger("code"); + String msg = jsonObject.getString("msg"); + if (code == MessageWhat.CODE_SUCCESSFUL) { + String data = jsonObject.getString("data"); + UserInfo userInfo = JSON.parseObject(data, UserInfo.class); + SPUtils.put(context, "member_id", userInfo.getMember_id()); + SPUtils.put(context, "sn_id", userInfo.getId()); + } else { + ToastUtil.show(msg); + } + } + + @Override + public void onError(Response response) { + super.onError(response); + LogUtils.e("onError", response.getException().toString()); + ToastUtil.show("网络连接失败,检查网络连接"); + } + }); + } + + //msg.what=3 + synchronized public static void getSortApp(final Handler handler, int type, int grade, int subject) { + OkGo.post(Url.GET_SORT_APP) + .params("app_type", type)//应用分类 0学习 1娱乐 + .params("grade", grade)//年级 以数字代表 + .params("subject", subject) //科目 以数字代表 + .execute(new StringCallback() { + @Override + public void onSuccess(Response response) { + LogUtils.e("fht", "getSortApp onSuccess"); + JSONObject jsonObject = JSON.parseObject(response.body()); + int code = jsonObject.getInteger("code"); + String msg = jsonObject.getString("msg"); + if (code == MessageWhat.CODE_SUCCESSFUL) { + String data = jsonObject.getString("data"); + List list = JSON.parseArray(data, AppInfo.class); + Message message = new Message(); + message.what = 1; + message.obj = list; + handler.sendMessage(message); + } else { + ToastUtil.show(msg); + } + } + + @Override + public void onError(Response response) { + super.onError(response); + LogUtils.e("onError", response.getException().toString()); + ToastUtil.show("网络连接失败,检查网络连接"); + } + }); + } + + //msg.what=4 + synchronized public static void setAppinstallInfo(int member_id, String sn_id, String app_name, String packageName) { + OkGo.post(Url.SET_APP_INSTALL_INFO) + .params("member_id", member_id) + .params("sn_id", sn_id) + .params("app_name", app_name) + .params("package", packageName) + .execute(new StringCallback() { + @Override + public void onSuccess(Response response) { + JSONObject object = JSON.parseObject(response.body()); + int code = object.getInteger("code"); + String msg = object.getString("msg"); + if (code == MessageWhat.CODE_SUCCESSFUL) { + LogUtils.e("setAppinstallInfo", msg); + } else { + ToastUtil.show(msg); + } + } + + @Override + public void onError(Response response) { + super.onError(response); + LogUtils.e("setAppinstallInfo", "onError:" + response.getException()); + + } + }); + + } + + //msg.what=5 + synchronized public static void setAppuninstallInfo(String sn_id, String packageName) { + OkGo.post(Url.SET_APP_UNINSTALL_INFO) + .params("sn_id", sn_id) + .params("package", packageName) + .execute(new StringCallback() { + @Override + public void onSuccess(Response response) { + JSONObject object = JSON.parseObject(response.body()); + int code = object.getInteger("code"); + String msg = object.getString("msg"); + if (code == MessageWhat.CODE_SUCCESSFUL) { + LogUtils.e("setAppinstallInfo", msg); + } else { + ToastUtil.show(msg); + } + } + + @Override + public void onError(Response response) { + super.onError(response); + LogUtils.e("setAppinstallInfo", "onError:" + response.getException()); + + } + }); + + } + } + diff --git a/app/src/main/java/com/appstore/uiui/network/URLs/Url.java b/app/src/main/java/com/appstore/uiui/network/URLs/Url.java index 7bb12fa..b82b0ee 100644 --- a/app/src/main/java/com/appstore/uiui/network/URLs/Url.java +++ b/app/src/main/java/com/appstore/uiui/network/URLs/Url.java @@ -5,5 +5,13 @@ public class Url { public final static String GET_ALL_APPINFO = NETWORK_HOME_ADDRESS + "/App/allInfo"; //获取所有应用 + public final static String GET_INFO_FROMESN = NETWORK_HOME_ADDRESS + "/Member/snInfo"; + //通过SN获取绑定信息 + public final static String GET_SORT_APP = NETWORK_HOME_ADDRESS + "/App/sortApp"; + //app分类查询 + public final static String SET_APP_INSTALL_INFO = NETWORK_HOME_ADDRESS + "/App/appInstall"; + //发送app安装信息 + public final static String SET_APP_UNINSTALL_INFO = NETWORK_HOME_ADDRESS + "/App/appUnload"; + //发送app卸载信息 } diff --git a/app/src/main/java/com/appstore/uiui/receiver/AppManagerReceiver.java b/app/src/main/java/com/appstore/uiui/receiver/AppManagerReceiver.java new file mode 100644 index 0000000..433be7b --- /dev/null +++ b/app/src/main/java/com/appstore/uiui/receiver/AppManagerReceiver.java @@ -0,0 +1,53 @@ +package com.appstore.uiui.receiver; + +import android.content.BroadcastReceiver; +import android.content.Context; +import android.content.Intent; +import android.content.pm.PackageInfo; +import android.util.Log; + +import com.appstore.uiui.network.OKGOPost; +import com.appstore.uiui.utils.ApkUtils; +import com.appstore.uiui.utils.LogUtils; +import com.appstore.uiui.utils.SPUtils; +import com.appstore.uiui.utils.ToastUtil; + +public class AppManagerReceiver extends BroadcastReceiver { + + private static final String TAG = "--AppManagerReceiver--"; + private String action = null; + + @Override + public void onReceive(Context context, Intent intent) { + int member_id = (int) SPUtils.get(context, "member_id", -1); + String sn_id = (String) SPUtils.get(context, "sn_id", "-1"); + + action = intent.getAction(); + //接收安装广播 + if (action.equals(Intent.ACTION_PACKAGE_ADDED) || action.equals(Intent.ACTION_PACKAGE_REPLACED)) { + String packageName = intent.getDataString().replace("package:", ""); + String name = ApkUtils.getApplicationName(context, packageName); + ToastUtil.show(name + ":安装成功"); + LogUtils.e(TAG, "安装了:" + packageName + "包名的程序"); +// ToastTool.show("安装成功"); + if (member_id == -1 || sn_id.equals("-1")) { + OKGOPost.getUserInfo(context); + } else { + OKGOPost.setAppinstallInfo(member_id, sn_id, name, packageName); + } + } + + //接收卸载广播 + if (action.equals(Intent.ACTION_PACKAGE_REMOVED)) { + String packageName = intent.getDataString().replace("package:", ""); + LogUtils.e(TAG, "卸载了:" + packageName + "包名的程序"); + if (member_id == -1 || sn_id.equals("-1")) { + OKGOPost.getUserInfo(context); + } else { + OKGOPost.setAppuninstallInfo(sn_id, packageName); + } + } + } + + +} diff --git a/app/src/main/java/com/appstore/uiui/receiver/BootReceiver.java b/app/src/main/java/com/appstore/uiui/receiver/BootReceiver.java new file mode 100644 index 0000000..595bab3 --- /dev/null +++ b/app/src/main/java/com/appstore/uiui/receiver/BootReceiver.java @@ -0,0 +1,27 @@ +package com.appstore.uiui.receiver; + +import android.content.BroadcastReceiver; +import android.content.Context; +import android.content.Intent; +import android.util.Log; + +import com.appstore.uiui.network.OKGOPost; +import com.appstore.uiui.service.GuardService; +import com.appstore.uiui.service.InitJpushServer; +import com.appstore.uiui.service.StepService; +import com.appstore.uiui.utils.LogUtils; + +public class BootReceiver extends BroadcastReceiver { + @Override + public void onReceive(Context context, Intent intent) { + if (intent.getAction().equals("android.intent.action.BOOT_COMPLETED")) { + + Intent i = new Intent(context, InitJpushServer.class); + context.startService(i); + context.startService(new Intent(context, StepService.class)); + context.startService(new Intent(context, GuardService.class)); + OKGOPost.getUserInfo(context); + LogUtils.e("fht", "booting BootReceiver"); + } + } +} diff --git a/app/src/main/java/com/appstore/uiui/service/GuardService.java b/app/src/main/java/com/appstore/uiui/service/GuardService.java index 05ffffb..5bbb621 100644 --- a/app/src/main/java/com/appstore/uiui/service/GuardService.java +++ b/app/src/main/java/com/appstore/uiui/service/GuardService.java @@ -17,12 +17,13 @@ import android.util.Log; import androidx.annotation.Nullable; +import com.appstore.uiui.KeepAliveConnection; import com.appstore.uiui.utils.ApkUtils; +import com.appstore.uiui.utils.LogUtils; import com.appstore.uiui.utils.ServiceAliveUtils; import com.arialyy.annotations.Download; import com.arialyy.aria.core.Aria; import com.arialyy.aria.core.task.DownloadTask; -import com.blankj.utilcode.util.LogUtils; import com.blankj.utilcode.util.ToastUtils; @@ -57,9 +58,8 @@ public class GuardService extends Service { @Nullable @Override public IBinder onBind(Intent intent) { -// return new KeepAliveConnection.Stub() {}; - return null; - + return new KeepAliveConnection.Stub() { + }; } @Override @@ -68,31 +68,27 @@ public class GuardService extends Service { Aria.init(this); Aria.get(this).getDownloadConfig().setMaxTaskNum(1); - - Aria.download(this).register(); - // startForeground(1, new Notification()); // 绑定建立链接 bindService(new Intent(this, StepService.class), mServiceConnection, Context.BIND_IMPORTANT); return START_STICKY; } - //在这里处理任务执行中的状态,如进度进度条的刷新 @Download.onTaskRunning - protected void running(DownloadTask task) { - Log.e("mjsheng", "我在下载=--------------::" + task.getState() + "-------" + task.getPercent() + "-------" + task.getExtendField()); + protected void running( DownloadTask task) { + LogUtils.e("mjsheng", "我在下载=--------------::" + task.getState() + "-------" + task.getPercent()+ "-------" + task.getExtendField()); ToastUtils.showShort("我在下载=--------------::" + task.getExtendField() + "-------" + task.getPercent()); } @Download.onTaskComplete - void taskComplete(DownloadTask task) { + void taskComplete( DownloadTask task) { //在这里处理任务完成的状态 String downloadPath = task.getFilePath(); String packageName = task.getExtendField(); - Log.e("mjsheng", "downloadPath::" + downloadPath); - Log.e("mjsheng", "extendField::" + packageName); + LogUtils.e("mjsheng", "downloadPath::" + downloadPath); + LogUtils.e("mjsheng", "extendField::" + packageName); ApkUtils.installApkInSilence(downloadPath, packageName); } } diff --git a/app/src/main/java/com/appstore/uiui/service/InitJpushServer.java b/app/src/main/java/com/appstore/uiui/service/InitJpushServer.java new file mode 100644 index 0000000..0e9a5e3 --- /dev/null +++ b/app/src/main/java/com/appstore/uiui/service/InitJpushServer.java @@ -0,0 +1,16 @@ +package com.appstore.uiui.service; + +import android.app.Service; +import android.content.Intent; +import android.os.IBinder; + +public class InitJpushServer extends Service { + public InitJpushServer() { + } + + @Override + public IBinder onBind(Intent intent) { + // TODO: Return the communication channel to the service. + throw new UnsupportedOperationException("Not yet implemented"); + } +} diff --git a/app/src/main/java/com/appstore/uiui/service/MyDownloadService.java b/app/src/main/java/com/appstore/uiui/service/MyDownloadService.java index abb5f73..44f6387 100644 --- a/app/src/main/java/com/appstore/uiui/service/MyDownloadService.java +++ b/app/src/main/java/com/appstore/uiui/service/MyDownloadService.java @@ -1,48 +1,14 @@ - package com.appstore.uiui.service; import android.app.Service; -import android.content.BroadcastReceiver; -import android.content.Context; import android.content.Intent; -import android.content.IntentFilter; -import android.content.pm.PackageInfo; -import android.content.pm.PackageManager; import android.os.IBinder; -import android.provider.Settings; -import android.util.Log; import androidx.annotation.Nullable; -import com.appstore.uiui.MyApplication; -import com.appstore.uiui.bean.AppDateInfo; -import com.appstore.uiui.bean.AppDownloadInfo; -import com.appstore.uiui.utils.ApkUtils; -import com.appstore.uiui.utils.SaveListUtils; -import com.appstore.uiui.utils.StorageUtils; -import com.appstore.uiui.utils.Utils; -import com.lzy.okgo.OkGo; -import com.lzy.okgo.request.GetRequest; -import com.lzy.okserver.download.DownloadInfo; -import com.lzy.okserver.download.DownloadManager; -import com.lzy.okserver.download.DownloadService; -import com.lzy.okserver.listener.DownloadListener; - - -import java.io.Serializable; -import java.util.ArrayList; -import java.util.List; - // 下载管理服务 public class MyDownloadService extends Service { - private DownloadReceiver downloadReceiver; - private DownloadManager downloadManager; - public List allTask; - private List downloadURL; // 当前下载的任务 - private static final String ACTION_START = "START"; - private static final String ACTION_STOP = "STOP"; - @Override public int onStartCommand(Intent intent, int flags, int startId) { @@ -52,32 +18,7 @@ public class MyDownloadService extends Service { @Override public void onCreate() { - super.onCreate(); - downloadManager = DownloadService.getDownloadManager(); - downloadManager.getThreadPool().setCorePoolSize(1); - allTask = downloadManager.getAllTask(); - for (DownloadInfo downloadInfo : allTask) { - DownloadListener downloadListener = new MyDownloadListener(); - downloadListener.setUserTag(downloadInfo.getUrl()); - downloadInfo.setListener(downloadListener); - } - downloadReceiver = new DownloadReceiver(); - downloadURL = new ArrayList<>(); - /* 注册广播 */ - IntentFilter mScreenOnFilter = new IntentFilter(); - mScreenOnFilter.addAction(Utils.DOWNLOAD_STARTALL_ACTION); - mScreenOnFilter.addAction(Utils.DOWNLOAD_DELETE_UPDATE_ACTION); - mScreenOnFilter.addAction(Utils.DOWNLOAD_START_ACTION); - mScreenOnFilter.addAction(Utils.DOWNLOAD_STOP_ACTION); - mScreenOnFilter.addAction(Utils.DOWNLOAD_INITIALIZE_ACTION); - mScreenOnFilter.addAction(Utils.DOWNLOAD_DELETE_URL_ACTION); - mScreenOnFilter.addAction(Utils.DOWNLOAD_DELETE_PACKAGENAME_ACTION); - mScreenOnFilter.addAction(Utils.DOWNLOAD_DELETEALL_ACTION); - mScreenOnFilter.addAction(Utils.DOWNLOAD_ALLTASK_ACTION); - mScreenOnFilter.addAction(Utils.DOWNLOAD_PACKAGENAME_ACTION); - MyDownloadService.this.registerReceiver(downloadReceiver, mScreenOnFilter); - startService(new Intent(this, StepService.class)); startService(new Intent(this, GuardService.class)); } @@ -90,17 +31,6 @@ public class MyDownloadService extends Service { @Override public void onDestroy() { super.onDestroy(); - if (downloadManager != null) { - downloadManager.stopAllTask(); - } - if (allTask != null) { - allTask.clear(); - allTask = null; - } - downloadURL.clear(); - MyDownloadService.this.unregisterReceiver(downloadReceiver); - Intent sevice = new Intent(this, DownloadService.class); - this.startService(sevice); } @Nullable @@ -109,239 +39,5 @@ public class MyDownloadService extends Service { return null; } - private class MyDownloadListener extends DownloadListener { - - @Override - public void onProgress(DownloadInfo downloadInfo) { - Log.e("mjsheng", "onProgress::::::::" + downloadInfo.getProgress()); - sendDownloadState(downloadInfo); - } - - @Override - public void onFinish(DownloadInfo downloadInfo) { - sendDownloadState(downloadInfo); - AppDateInfo info = (AppDateInfo) downloadInfo.getData(); - if (info.getApp_baoming().equals(Utils.YOUNGSYSTEM_APP_TONGBU) || info.getApp_baoming().equals(MyApplication.getAppContext().getPackageName())) { -// ApkUtils.install(MyApplication.getAppContext(), new File(downloadInfo.getTargetPath())); - ApkUtils.installApkInSilence(downloadInfo.getTargetPath(), info.getApp_baoming()); - } - if (downloadURL.contains(downloadInfo.getUrl())) { -// ApkUtils.install(MyApplication.getAppContext(), new File(downloadInfo.getTargetPath())); - ApkUtils.installApkInSilence(downloadInfo.getTargetPath(), info.getApp_baoming()); - downloadURL.remove(downloadInfo.getUrl()); - } - } - - @Override - public void onError(DownloadInfo downloadInfo, String errorMsg, Exception e) { - sendDownloadState(downloadInfo); - } - } - - private void sendDownloadState(DownloadInfo downloadInfo) { - if (downloadInfo == null) return; - AppDownloadInfo info = new AppDownloadInfo(); - info.setFileName(downloadInfo.getFileName()); - info.setProgress(downloadInfo.getProgress()); - info.setTargetPath(downloadInfo.getTargetPath()); - info.setUrl(downloadInfo.getUrl()); - info.setState(downloadInfo.getState()); - info.setDownloadLength(downloadInfo.getDownloadLength()); - info.setTotalLength(downloadInfo.getTotalLength()); - AppDateInfo dateInfo = (AppDateInfo) downloadInfo.getData(); - info.setPackageName(dateInfo.getApp_baoming()); - info.setVersion(dateInfo.getApp_banben()); - info.setData(dateInfo); - Intent intent = new Intent(); - intent.setAction(Utils.DOWNLOAD_SERVICE_ACTION); - intent.putExtra("DownloadInfo", info); - sendBroadcast(intent); - } - - /** - * 是否存在该包名的下载任务 - */ - public DownloadInfo getPackageName(String packagename) { - if (packagename != null) { - for (DownloadInfo downloadInfo : allTask) { - AppDateInfo info = (AppDateInfo) downloadInfo.getData(); - if (info.getApp_baoming() != null) { - if (info.getApp_baoming().equals(packagename)) { - return downloadInfo; - } - } - } - } - return null; - } - - - public class DownloadReceiver extends BroadcastReceiver { - - @Override - public void onReceive(Context context, Intent intent) { - if (Utils.DOWNLOAD_STARTALL_ACTION.equals(intent.getAction())) { - downloadManager.startAllTask(); - } else if (Utils.DOWNLOAD_DELETE_URL_ACTION.equals(intent.getAction())) { - // 删除标识 下载地址 - String URL = intent.getStringExtra("URL"); - DownloadInfo downloadInfo = downloadManager.getDownloadInfo(URL); - if (downloadInfo != null && StorageUtils.isFileIsExists(downloadInfo.getTargetPath())) { - downloadInfo.setState(10); - sendDownloadState(downloadInfo); - downloadManager.removeTask(downloadInfo.getUrl(), true); - } - } else if (Utils.DOWNLOAD_START_ACTION.equals(intent.getAction())) { - // 下载 - String URL = intent.getStringExtra("URL"); - AppDateInfo appDateInfo = (AppDateInfo) intent.getSerializableExtra("AppDateInfo"); - if (appDateInfo != null) { - GetRequest request = OkGo.get(URL); - MyDownloadListener listener = new MyDownloadListener(); - listener.setUserTag(URL); - if (URL != null) { - if (downloadManager.getDownloadInfo(URL) == null) { - if (!StorageUtils.isFileIsExists("/Android/data/" + context.getPackageName() + "/files/Download")) { - StorageUtils.getFileRoot(context); - } - downloadManager.addTask(URL, appDateInfo, request, listener); - SaveListUtils.addDownLoadList(appDateInfo.getApp_baoming()); - DownloadInfo downloadInfo = downloadManager.getDownloadInfo(URL); - AppDownloadInfo info = new AppDownloadInfo(); - info.setFileName(downloadInfo.getFileName()); - info.setProgress(downloadInfo.getProgress()); - info.setTargetPath(downloadInfo.getTargetPath()); - info.setUrl(downloadInfo.getUrl()); - info.setState(downloadInfo.getState()); - info.setDownloadLength(downloadInfo.getDownloadLength()); - info.setTotalLength(downloadInfo.getTotalLength()); - AppDateInfo dateInfo = (AppDateInfo) downloadInfo.getData(); - info.setPackageName(dateInfo.getApp_baoming()); - String s = Settings.System.getString(getContentResolver(), "qch_app_forbid"); - Settings.System.putString(getContentResolver(), "qch_app_forbid", s + "," + dateInfo.getApp_baoming()); - Log.e("SystemSetting", "qch_app_forbid__________" + Settings.System.getString(getContentResolver(), "qch_app_forbid")); - - //2019.9.26 - info.setVersion(dateInfo.getApp_banben()); - info.setData(dateInfo); - Intent allIntent = new Intent(); - allIntent.setAction(Utils.DOWNLOAD_NEWSERVICE_ACTION); - allIntent.putExtra("addTask", info); - sendBroadcast(allIntent); - - } else { - if (!StorageUtils.isFileIsExists(downloadManager.getDownloadInfo(URL).getTargetPath())) { - downloadManager.removeTask(URL, true); - StorageUtils.getFileRoot(context); - } - downloadManager.addTask(URL, appDateInfo, request, listener); - } - if (!downloadURL.contains(URL)) { - downloadURL.add(URL); - } - } - } else { - if (downloadManager.getDownloadInfo(URL) != null) { - downloadManager.restartTask(URL); - } - } - } else if (Utils.DOWNLOAD_INITIALIZE_ACTION.equals(intent.getAction())) { - // 初始化item状态 - String URL = intent.getStringExtra("URL"); - DownloadInfo downloadInfo = downloadManager.getDownloadInfo(URL); - if (downloadInfo != null && StorageUtils.isFileIsExists(downloadInfo.getTargetPath())) { - sendDownloadState(downloadInfo); - } - } else if (Utils.DOWNLOAD_PACKAGENAME_ACTION.equals(intent.getAction())) { - // 初始化item状态 - String packageName = intent.getStringExtra("packageName"); - DownloadInfo downloadInfo = getPackageName(packageName); - if (downloadInfo != null && StorageUtils.isFileIsExists(downloadInfo.getTargetPath())) { - sendDownloadState(downloadInfo); - } - } else if (Utils.DOWNLOAD_STOP_ACTION.equals(intent.getAction())) { - // 暂停标识 - String URL = intent.getStringExtra("URL"); - downloadManager.pauseTask(URL); - DownloadInfo downloadInfo = downloadManager.getDownloadInfo(URL); - if (downloadInfo != null && StorageUtils.isFileIsExists(downloadInfo.getTargetPath())) { - sendDownloadState(downloadInfo); - } - } else if (Utils.DOWNLOAD_DELETE_PACKAGENAME_ACTION.equals(intent.getAction())) { - // 删除标识 包名 - String packageName = intent.getStringExtra("packageName"); - DownloadInfo downloadInfo = getPackageName(packageName); - if (downloadInfo != null && StorageUtils.isFileIsExists(downloadInfo.getTargetPath())) { - downloadInfo.setState(10); - sendDownloadState(downloadInfo); - downloadManager.removeTask(downloadInfo.getUrl(), true); - } - } else if (Utils.DOWNLOAD_DELETE_URL_ACTION.equals(intent.getAction())) { - // 删除标识 下载地址 - String URL = intent.getStringExtra("URL"); - DownloadInfo downloadInfo = downloadManager.getDownloadInfo(URL); - if (downloadInfo != null) { - downloadInfo.setState(10); - sendDownloadState(downloadInfo); - downloadManager.removeTask(downloadInfo.getUrl(), true); - } - } else if (Utils.DOWNLOAD_DELETE_UPDATE_ACTION.equals(intent.getAction())) { - // 删除 应用更新包 - String packageName = intent.getStringExtra("packageName"); - DownloadInfo downloadInfo = getPackageName(packageName); - if (downloadInfo != null && downloadInfo.getData() != null) { - AppDateInfo dateInfo = (AppDateInfo) downloadInfo.getData(); - PackageManager packageManager = context.getPackageManager(); - try { - PackageInfo packInfo = packageManager.getPackageInfo(context.getPackageName(), - 0); - String version = packInfo.versionName; - String oldVersion = dateInfo.getApp_banben(); - if (oldVersion == null || oldVersion.equals("")) { - downloadManager.removeTask(downloadInfo.getUrl(), true); - } else if (Utils.isUpdate(oldVersion, version) == true || oldVersion.equals(version)) { - downloadManager.removeTask(downloadInfo.getUrl(), true); - } - } catch (PackageManager.NameNotFoundException e) { - e.printStackTrace(); - } - if (StorageUtils.isFileIsExists(downloadInfo.getTargetPath())) { - downloadInfo.setState(10); - sendDownloadState(downloadInfo); - downloadManager.removeTask(downloadInfo.getUrl(), true); - } - } - } else if (Utils.DOWNLOAD_ALLTASK_ACTION.equals(intent.getAction())) { - downloadManager = DownloadService.getDownloadManager(); - allTask = downloadManager.getAllTask(); - List list = new ArrayList<>(); - for (int i = 0; i < allTask.size(); i++) { - DownloadInfo downloadInfo = allTask.get(i); - if (downloadInfo != null && StorageUtils.isFileIsExists(downloadInfo.getTargetPath())) { - AppDateInfo dateInfo = (AppDateInfo) downloadInfo.getData(); - if (!dateInfo.getApp_baoming().equals(Utils.YOUNGSYSTEM_APP_TONGBU) && !dateInfo.getApp_baoming().equals(context.getPackageName())) { - AppDownloadInfo info = new AppDownloadInfo(); - info.setFileName(downloadInfo.getFileName()); - info.setProgress(downloadInfo.getProgress()); - info.setTargetPath(downloadInfo.getTargetPath()); - info.setUrl(downloadInfo.getUrl()); - info.setState(downloadInfo.getState()); - info.setDownloadLength(downloadInfo.getDownloadLength()); - info.setTotalLength(downloadInfo.getTotalLength()); - info.setPackageName(dateInfo.getApp_baoming()); - info.setVersion(dateInfo.getApp_banben()); - info.setData(dateInfo); - list.add(info); - } - } - } - Intent allIntent = new Intent(); - allIntent.setAction(Utils.DOWNLOAD_ALLSERVICE_ACTION); - allIntent.putExtra("allTask", (Serializable) list); - sendBroadcast(allIntent); - } - } - - } } diff --git a/app/src/main/java/com/appstore/uiui/service/StepService.java b/app/src/main/java/com/appstore/uiui/service/StepService.java index f3cc57a..06c2ec5 100644 --- a/app/src/main/java/com/appstore/uiui/service/StepService.java +++ b/app/src/main/java/com/appstore/uiui/service/StepService.java @@ -16,8 +16,9 @@ import android.os.IBinder; import androidx.annotation.Nullable; +import com.appstore.uiui.KeepAliveConnection; +import com.appstore.uiui.utils.LogUtils; import com.appstore.uiui.utils.ServiceAliveUtils; -import com.blankj.utilcode.util.LogUtils; /** * 主进程 双进程通讯 @@ -51,8 +52,8 @@ public class StepService extends Service { @Nullable @Override public IBinder onBind(Intent intent) { -// return new KeepAliveConnection.Stub() { }; - return null; + return new KeepAliveConnection.Stub() { + }; } @Override diff --git a/app/src/main/java/com/appstore/uiui/utils/ApkUtils.java b/app/src/main/java/com/appstore/uiui/utils/ApkUtils.java index 18b3639..fc4af0f 100644 --- a/app/src/main/java/com/appstore/uiui/utils/ApkUtils.java +++ b/app/src/main/java/com/appstore/uiui/utils/ApkUtils.java @@ -78,6 +78,15 @@ public class ApkUtils { return; } + public static void openApp(Context context, String packageName) { + Intent intent = context.getPackageManager().getLaunchIntentForPackage(packageName); + if (intent != null) { + intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + context.startActivity(intent); + } + } + + /** * 安装一个apk文件 */ @@ -89,7 +98,7 @@ public class ApkUtils { if (Build.VERSION.SDK_INT >= 24) { //判读版本是否在7.0以上 //参数1 上下文, 参数2 Provider主机地址 和配置文件中保持一致 参数3 共享的文件 Uri apkUri = - FileProvider.getUriForFile(context, "com.mjsheng.myappstore.fileprovider", uriFile); + FileProvider.getUriForFile(context, "com.appstore.uiui.fileprovider", uriFile); //添加这一句表示对目标应用临时授权该Uri所代表的文件 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); intent.setDataAndType(apkUri, "application/vnd.android.package-archive"); @@ -298,6 +307,8 @@ public class ApkUtils { // Log.e("fanhuitong", "安装失败"); // } // } + + //使用系统签名 public static void installApkInSilence(String installPath, String packageName) { ToastUtil.show("正在安装应用..."); Class pmService; @@ -366,4 +377,47 @@ public class ApkUtils { return uid / PER_USER_RANGE; } + public static boolean checkIsUpdate(Context context, String packageName, int versionCode) { + PackageManager packageManager = context.getPackageManager(); + boolean update = false; + PackageInfo packageInfo = null; + try { + packageInfo = packageManager.getPackageInfo(packageName, PackageManager.GET_ACTIVITIES); + int code = packageInfo.versionCode; + update = versionCode > code; + } catch (PackageManager.NameNotFoundException e) { + e.printStackTrace(); +// LogUtils.e("NameNotFoundException", e.getMessage()); + update = false; + } + return update; + } + + synchronized public static PackageInfo getPackageInfo(Context context, String packageName) { + PackageManager pm = context.getPackageManager(); + PackageInfo packageInfo = null; + try { + packageInfo = pm.getPackageInfo(packageName, 0); + } catch (PackageManager.NameNotFoundException e) { + e.printStackTrace(); + Log.e("getPackageInfo", packageName + ":" + e.getMessage()); + } + return packageInfo; + } + + synchronized public static String getApplicationName(Context context, String packageName) { + PackageManager pm = context.getPackageManager(); + PackageInfo packageInfo = null; + String name = ""; + try { + packageInfo = pm.getPackageInfo(packageName, 0); + name = pm.getApplicationLabel(packageInfo.applicationInfo).toString(); + } catch (PackageManager.NameNotFoundException e) { + e.printStackTrace(); + Log.e("getPackageInfo", packageName + ":" + e.getMessage()); + } + return name; + } + + } diff --git a/app/src/main/java/com/appstore/uiui/utils/SPUtils.java b/app/src/main/java/com/appstore/uiui/utils/SPUtils.java new file mode 100644 index 0000000..015d23f --- /dev/null +++ b/app/src/main/java/com/appstore/uiui/utils/SPUtils.java @@ -0,0 +1,202 @@ +package com.appstore.uiui.utils; + +import android.content.Context; +import android.content.SharedPreferences; +import android.graphics.Bitmap; +import android.graphics.BitmapFactory; +import android.graphics.drawable.BitmapDrawable; +import android.util.Base64; +import android.widget.ImageView; + + +import com.appstore.uiui.common.CommonDatas; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.Map; + +/** + * 作者 mjsheng + * 日期 2018/10/9 18:41 + * 邮箱 501802639@qq.com + * 来自: + */ + +public class SPUtils { + /** + * 保存在手机里面的文件名 + */ + public static final String FILE_NAME = "share_data"; + + /** + * 保存数据的方法,我们需要拿到保存数据的具体类型,然后根据类型调用不同的保存方法 + */ + public static void put(Context context, String key, Object object) { + + SharedPreferences sp = context.getSharedPreferences(FILE_NAME, + Context.MODE_PRIVATE); + SharedPreferences.Editor editor = sp.edit(); + + if (object instanceof String) { + editor.putString(key, (String) object); + } else if (object instanceof Integer) { + editor.putInt(key, (Integer) object); + } else if (object instanceof Boolean) { + editor.putBoolean(key, (Boolean) object); + } else if (object instanceof Float) { + editor.putFloat(key, (Float) object); + } else if (object instanceof Long) { + editor.putLong(key, (Long) object); + } else { + editor.putString(key, object.toString()); + } + + SharedPreferencesCompat.apply(editor); + } + + /** + * 得到保存数据的方法,我们根据默认值得到保存的数据的具体类型,然后调用相对于的方法获取值 + */ + public static Object get(Context context, String key, Object defaultObject) { + SharedPreferences sp = context.getSharedPreferences(FILE_NAME, + Context.MODE_PRIVATE); + + if (defaultObject instanceof String) { + return sp.getString(key, (String) defaultObject); + } else if (defaultObject instanceof Integer) { + return sp.getInt(key, (Integer) defaultObject); + } else if (defaultObject instanceof Boolean) { + return sp.getBoolean(key, (Boolean) defaultObject); + } else if (defaultObject instanceof Float) { + return sp.getFloat(key, (Float) defaultObject); + } else if (defaultObject instanceof Long) { + return sp.getLong(key, (Long) defaultObject); + } + + return null; + } + + /** + * 移除某个key值已经对应的值 + */ + public static void remove(Context context, String key) { + SharedPreferences sp = context.getSharedPreferences(FILE_NAME, + Context.MODE_PRIVATE); + SharedPreferences.Editor editor = sp.edit(); + editor.remove(key); + SharedPreferencesCompat.apply(editor); + } + + /** + * 清除所有数据 + */ + public static void clear(Context context) { + SharedPreferences sp = context.getSharedPreferences(FILE_NAME, + Context.MODE_PRIVATE); + SharedPreferences.Editor editor = sp.edit(); + editor.clear(); + SharedPreferencesCompat.apply(editor); + reductFirstEnter(context); + } + + //还原状态firstEnter信息 + private static void reductFirstEnter(Context context){ + put(context, CommonDatas.FLAG_FIRST_ENTER,CommonDatas.FLAG_FIRST_ENTER); + } + + + /** + * 查询某个key是否已经存在 + */ + public static boolean contains(Context context, String key) { + SharedPreferences sp = context.getSharedPreferences(FILE_NAME, + Context.MODE_PRIVATE); + return sp.contains(key); + } + + /** + * 返回所有的键值对 + */ + public static Map getAll(Context context) { + SharedPreferences sp = context.getSharedPreferences(FILE_NAME, + Context.MODE_PRIVATE); + return sp.getAll(); + } + + + /** + * 保存图片到SharedPreferences + * + * @param mContext + * @param imageView + */ + public static void putImage(Context mContext, String key, ImageView imageView) { + BitmapDrawable drawable = (BitmapDrawable) imageView.getDrawable(); + Bitmap bitmap = drawable.getBitmap(); + // 将Bitmap压缩成字节数组输出流 + ByteArrayOutputStream byStream = new ByteArrayOutputStream(); + bitmap.compress(Bitmap.CompressFormat.PNG, 80, byStream); + // 利用Base64将我们的字节数组输出流转换成String + byte[] byteArray = byStream.toByteArray(); + String imgString = new String(Base64.encodeToString(byteArray, Base64.DEFAULT)); + // 将String保存shareUtils + SPUtils.put(mContext, key, imgString); + } + + /** + * 从SharedPreferences读取图片 + * + * @param mContext + * @param imageView + */ + public static Bitmap getImage(Context mContext, String key, ImageView imageView) { + String imgString = (String) SPUtils.get(mContext, key, ""); + if (!imgString.equals("")) { + // 利用Base64将我们string转换 + byte[] byteArray = Base64.decode(imgString, Base64.DEFAULT); + ByteArrayInputStream byStream = new ByteArrayInputStream(byteArray); + // 生成bitmap + return BitmapFactory.decodeStream(byStream); + } + return null; + } + + /** + * 创建一个解决SharedPreferencesCompat.apply方法的一个兼容类 + */ + private static class SharedPreferencesCompat { + private static final Method sApplyMethod = findApplyMethod(); + + /** + * 反射查找apply的方法 + */ + @SuppressWarnings({"unchecked", "rawtypes"}) + private static Method findApplyMethod() { + try { + Class clz = SharedPreferences.Editor.class; + return clz.getMethod("apply"); + } catch (NoSuchMethodException e) { + } + + return null; + } + + /** + * 如果找到则使用apply执行,否则使用commit + */ + public static void apply(SharedPreferences.Editor editor) { + try { + if (sApplyMethod != null) { + sApplyMethod.invoke(editor); + return; + } + } catch (IllegalArgumentException e) { + } catch (IllegalAccessException e) { + } catch (InvocationTargetException e) { + } + editor.commit(); + } + } +} diff --git a/app/src/main/java/com/appstore/uiui/utils/ServiceAliveUtils.java b/app/src/main/java/com/appstore/uiui/utils/ServiceAliveUtils.java index 2fff427..729b39a 100644 --- a/app/src/main/java/com/appstore/uiui/utils/ServiceAliveUtils.java +++ b/app/src/main/java/com/appstore/uiui/utils/ServiceAliveUtils.java @@ -10,7 +10,7 @@ public class ServiceAliveUtils { public static boolean isServiceAlice() { boolean isServiceRunning = false; ActivityManager manager = - (ActivityManager) MyApplication.getAppContext().getSystemService(Context.ACTIVITY_SERVICE); + (ActivityManager) MyApplication.getInstance().getAppContext().getSystemService(Context.ACTIVITY_SERVICE); if (manager == null) { return true; } diff --git a/app/src/main/java/com/appstore/uiui/utils/ToastUtil.java b/app/src/main/java/com/appstore/uiui/utils/ToastUtil.java index c40105c..3b4a475 100644 --- a/app/src/main/java/com/appstore/uiui/utils/ToastUtil.java +++ b/app/src/main/java/com/appstore/uiui/utils/ToastUtil.java @@ -6,6 +6,8 @@ import android.os.Handler; import android.os.Looper; import android.widget.Toast; +import com.appstore.uiui.BuildConfig; + /** * Created by haoge on 2017/3/2. */ @@ -17,6 +19,8 @@ public class ToastUtil { @SuppressLint("ShowToast") public static void init(Context context) { toast = Toast.makeText(context, "", Toast.LENGTH_SHORT); + debugToast = Toast.makeText(context, "", Toast.LENGTH_SHORT); + } public static void show(final String msg) { @@ -31,7 +35,7 @@ public class ToastUtil { }); } -// public static void showInCenter(String msg) { + // public static void showInCenter(String msg) { // mainHandler.post(() -> { // if (toast != null) { // toast.setGravity(Gravity.CENTER, 0, 0); @@ -40,5 +44,21 @@ public class ToastUtil { // } // }); // } + static Handler debugHandler = new Handler(Looper.getMainLooper()); + static Toast debugToast; + + public static void debugShow(final String msg) { + mainHandler.post(new Runnable() { + @Override + public void run() { + if (BuildConfig.LOG_DEBUG) { + if (toast != null) { + toast.setText(msg); + toast.show(); + } + } + } + }); + } } diff --git a/app/src/main/java/com/appstore/uiui/view/NumberProgressBar.java b/app/src/main/java/com/appstore/uiui/view/NumberProgressBar.java new file mode 100644 index 0000000..9db734e --- /dev/null +++ b/app/src/main/java/com/appstore/uiui/view/NumberProgressBar.java @@ -0,0 +1,524 @@ +/* + * Copyright 2016 jeasonlzy(廖子尧) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.appstore.uiui.view; + +import android.content.Context; +import android.content.res.TypedArray; +import android.graphics.Canvas; +import android.graphics.Color; +import android.graphics.Paint; +import android.graphics.RectF; +import android.os.Bundle; +import android.os.Parcelable; +import android.util.AttributeSet; +import android.view.View; + +import com.appstore.uiui.R; + +/** + * ================================================ + * 作 者:jeasonlzy(廖子尧)Github地址:https://github.com/jeasonlzy + * 版 本:1.0 + * 创建日期:16/9/11 + * 描 述: + * 修订历史: + * ================================================ + */ +public class NumberProgressBar extends View { + + public interface OnProgressBarListener { + + void onProgressChange(int current, int max); + } + + private int mMaxProgress = 100; + + /** + * Current progress, can not exceed the max progress. + */ + private int mCurrentProgress = 0; + + /** + * The progress area bar color. + */ + private int mReachedBarColor; + + /** + * The bar unreached area color. + */ + private int mUnreachedBarColor; + + /** + * The progress text color. + */ + private int mTextColor; + + /** + * The progress text size. + */ + private float mTextSize; + + /** + * The height of the reached area. + */ + private float mReachedBarHeight; + + /** + * The height of the unreached area. + */ + private float mUnreachedBarHeight; + + /** + * The suffix of the number. + */ + private String mSuffix = "%"; + + /** + * The prefix. + */ + private String mPrefix = ""; + + private final int default_text_color = Color.rgb(66, 145, 241); + private final int default_reached_color = Color.rgb(66, 145, 241); + private final int default_unreached_color = Color.rgb(204, 204, 204); + private final float default_progress_text_offset; + private final float default_text_size; + private final float default_reached_bar_height; + private final float default_unreached_bar_height; + + /** + * For save and restore instance of progressbar. + */ + private static final String INSTANCE_STATE = "saved_instance"; + private static final String INSTANCE_TEXT_COLOR = "text_color"; + private static final String INSTANCE_TEXT_SIZE = "text_size"; + private static final String INSTANCE_REACHED_BAR_HEIGHT = "reached_bar_height"; + private static final String INSTANCE_REACHED_BAR_COLOR = "reached_bar_color"; + private static final String INSTANCE_UNREACHED_BAR_HEIGHT = "unreached_bar_height"; + private static final String INSTANCE_UNREACHED_BAR_COLOR = "unreached_bar_color"; + private static final String INSTANCE_MAX = "max"; + private static final String INSTANCE_PROGRESS = "progress"; + private static final String INSTANCE_SUFFIX = "suffix"; + private static final String INSTANCE_PREFIX = "prefix"; + private static final String INSTANCE_TEXT_VISIBILITY = "text_visibility"; + + private static final int PROGRESS_TEXT_VISIBLE = 0; + + /** + * The width of the text that to be drawn. + */ + private float mDrawTextWidth; + + /** + * The drawn text start. + */ + private float mDrawTextStart; + + /** + * The drawn text end. + */ + private float mDrawTextEnd; + + /** + * The text that to be drawn in onDraw(). + */ + private String mCurrentDrawText; + + /** + * The Paint of the reached area. + */ + private Paint mReachedBarPaint; + /** + * The Paint of the unreached area. + */ + private Paint mUnreachedBarPaint; + /** + * The Paint of the progress text. + */ + private Paint mTextPaint; + + /** + * Unreached bar area to draw rect. + */ + private RectF mUnreachedRectF = new RectF(0, 0, 0, 0); + /** + * Reached bar area rect. + */ + private RectF mReachedRectF = new RectF(0, 0, 0, 0); + + /** + * The progress text offset. + */ + private float mOffset; + + /** + * Determine if need to draw unreached area. + */ + private boolean mDrawUnreachedBar = true; + + private boolean mDrawReachedBar = true; + + private boolean mIfDrawText = true; + + /** + * Listener + */ + private OnProgressBarListener mListener; + + public enum ProgressTextVisibility { + Visible, Invisible + } + + public NumberProgressBar(Context context) { + this(context, null); + } + + public NumberProgressBar(Context context, AttributeSet attrs) { + this(context, attrs, 0); + } + + public NumberProgressBar(Context context, AttributeSet attrs, int defStyleAttr) { + super(context, attrs, defStyleAttr); + + default_reached_bar_height = dp2px(1.5f); + default_unreached_bar_height = dp2px(1.0f); + default_text_size = sp2px(10); + default_progress_text_offset = dp2px(3.0f); + + //load styled attributes. + final TypedArray attributes = context.getTheme().obtainStyledAttributes(attrs, R.styleable.NumberProgressBar, defStyleAttr, 0); + + mReachedBarColor = attributes.getColor(R.styleable.NumberProgressBar_progress_reached_color, default_reached_color); + mUnreachedBarColor = attributes.getColor(R.styleable.NumberProgressBar_progress_unreached_color, default_unreached_color); + mTextColor = attributes.getColor(R.styleable.NumberProgressBar_progress_text_color, default_text_color); + mTextSize = attributes.getDimension(R.styleable.NumberProgressBar_progress_text_size, default_text_size); + + mReachedBarHeight = attributes.getDimension(R.styleable.NumberProgressBar_progress_reached_bar_height, default_reached_bar_height); + mUnreachedBarHeight = attributes.getDimension(R.styleable.NumberProgressBar_progress_unreached_bar_height, default_unreached_bar_height); + mOffset = attributes.getDimension(R.styleable.NumberProgressBar_progress_text_offset, default_progress_text_offset); + + int textVisible = attributes.getInt(R.styleable.NumberProgressBar_progress_text_visibility, PROGRESS_TEXT_VISIBLE); + if (textVisible != PROGRESS_TEXT_VISIBLE) { + mIfDrawText = false; + } + + setProgress(attributes.getInt(R.styleable.NumberProgressBar_progress_current, 0)); + setMax(attributes.getInt(R.styleable.NumberProgressBar_progress_max, 100)); + + attributes.recycle(); + initializePainters(); + } + + @Override + protected int getSuggestedMinimumWidth() { + return (int) mTextSize; + } + + @Override + protected int getSuggestedMinimumHeight() { + return Math.max((int) mTextSize, Math.max((int) mReachedBarHeight, (int) mUnreachedBarHeight)); + } + + @Override + protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { + setMeasuredDimension(measure(widthMeasureSpec, true), measure(heightMeasureSpec, false)); + } + + private int measure(int measureSpec, boolean isWidth) { + int result; + int mode = MeasureSpec.getMode(measureSpec); + int size = MeasureSpec.getSize(measureSpec); + int padding = isWidth ? getPaddingLeft() + getPaddingRight() : getPaddingTop() + getPaddingBottom(); + if (mode == MeasureSpec.EXACTLY) { + result = size; + } else { + result = isWidth ? getSuggestedMinimumWidth() : getSuggestedMinimumHeight(); + result += padding; + if (mode == MeasureSpec.AT_MOST) { + if (isWidth) { + result = Math.max(result, size); + } else { + result = Math.min(result, size); + } + } + } + return result; + } + + @Override + protected void onDraw(Canvas canvas) { + if (mIfDrawText) { + calculateDrawRectF(); + } else { + calculateDrawRectFWithoutProgressText(); + } + + if (mDrawReachedBar) { + canvas.drawRect(mReachedRectF, mReachedBarPaint); + } + + if (mDrawUnreachedBar) { + canvas.drawRect(mUnreachedRectF, mUnreachedBarPaint); + } + + if (mIfDrawText) canvas.drawText(mCurrentDrawText, mDrawTextStart, mDrawTextEnd, mTextPaint); + } + + private void initializePainters() { + mReachedBarPaint = new Paint(Paint.ANTI_ALIAS_FLAG); + mReachedBarPaint.setColor(mReachedBarColor); + + mUnreachedBarPaint = new Paint(Paint.ANTI_ALIAS_FLAG); + mUnreachedBarPaint.setColor(mUnreachedBarColor); + + mTextPaint = new Paint(Paint.ANTI_ALIAS_FLAG); + mTextPaint.setColor(mTextColor); + mTextPaint.setTextSize(mTextSize); + } + + private void calculateDrawRectFWithoutProgressText() { + mReachedRectF.left = getPaddingLeft(); + mReachedRectF.top = getHeight() / 2.0f - mReachedBarHeight / 2.0f; + mReachedRectF.right = (getWidth() - getPaddingLeft() - getPaddingRight()) / (getMax() * 1.0f) * getProgress() + getPaddingLeft(); + mReachedRectF.bottom = getHeight() / 2.0f + mReachedBarHeight / 2.0f; + + mUnreachedRectF.left = mReachedRectF.right; + mUnreachedRectF.right = getWidth() - getPaddingRight(); + mUnreachedRectF.top = getHeight() / 2.0f + -mUnreachedBarHeight / 2.0f; + mUnreachedRectF.bottom = getHeight() / 2.0f + mUnreachedBarHeight / 2.0f; + } + + private void calculateDrawRectF() { + + mCurrentDrawText = String.format("%d", getProgress() * 100 / getMax()); + mCurrentDrawText = mPrefix + mCurrentDrawText + mSuffix; + mDrawTextWidth = mTextPaint.measureText(mCurrentDrawText); + + if (getProgress() == 0) { + mDrawReachedBar = false; + mDrawTextStart = getPaddingLeft(); + } else { + mDrawReachedBar = true; + mReachedRectF.left = getPaddingLeft(); + mReachedRectF.top = getHeight() / 2.0f - mReachedBarHeight / 2.0f; + mReachedRectF.right = (getWidth() - getPaddingLeft() - getPaddingRight()) / (getMax() * 1.0f) * getProgress() - mOffset + getPaddingLeft(); + mReachedRectF.bottom = getHeight() / 2.0f + mReachedBarHeight / 2.0f; + mDrawTextStart = (mReachedRectF.right + mOffset); + } + + mDrawTextEnd = (int) ((getHeight() / 2.0f) - ((mTextPaint.descent() + mTextPaint.ascent()) / 2.0f)); + + if ((mDrawTextStart + mDrawTextWidth) >= getWidth() - getPaddingRight()) { + mDrawTextStart = getWidth() - getPaddingRight() - mDrawTextWidth; + mReachedRectF.right = mDrawTextStart - mOffset; + } + + float unreachedBarStart = mDrawTextStart + mDrawTextWidth + mOffset; + if (unreachedBarStart >= getWidth() - getPaddingRight()) { + mDrawUnreachedBar = false; + } else { + mDrawUnreachedBar = true; + mUnreachedRectF.left = unreachedBarStart; + mUnreachedRectF.right = getWidth() - getPaddingRight(); + mUnreachedRectF.top = getHeight() / 2.0f + -mUnreachedBarHeight / 2.0f; + mUnreachedRectF.bottom = getHeight() / 2.0f + mUnreachedBarHeight / 2.0f; + } + } + + /** + * Get progress text color. + * + * @return progress text color. + */ + public int getTextColor() { + return mTextColor; + } + + /** + * Get progress text size. + * + * @return progress text size. + */ + public float getProgressTextSize() { + return mTextSize; + } + + public int getUnreachedBarColor() { + return mUnreachedBarColor; + } + + public int getReachedBarColor() { + return mReachedBarColor; + } + + public int getProgress() { + return mCurrentProgress; + } + + public int getMax() { + return mMaxProgress; + } + + public float getReachedBarHeight() { + return mReachedBarHeight; + } + + public float getUnreachedBarHeight() { + return mUnreachedBarHeight; + } + + public void setProgressTextSize(float textSize) { + this.mTextSize = textSize; + mTextPaint.setTextSize(mTextSize); + invalidate(); + } + + public void setProgressTextColor(int textColor) { + this.mTextColor = textColor; + mTextPaint.setColor(mTextColor); + invalidate(); + } + + public void setUnreachedBarColor(int barColor) { + this.mUnreachedBarColor = barColor; + mUnreachedBarPaint.setColor(mUnreachedBarColor); + invalidate(); + } + + public void setReachedBarColor(int progressColor) { + this.mReachedBarColor = progressColor; + mReachedBarPaint.setColor(mReachedBarColor); + invalidate(); + } + + public void setReachedBarHeight(float height) { + mReachedBarHeight = height; + } + + public void setUnreachedBarHeight(float height) { + mUnreachedBarHeight = height; + } + + public void setMax(int maxProgress) { + if (maxProgress > 0) { + this.mMaxProgress = maxProgress; + invalidate(); + } + } + + public void setSuffix(String suffix) { + if (suffix == null) { + mSuffix = ""; + } else { + mSuffix = suffix; + } + } + + public String getSuffix() { + return mSuffix; + } + + public void setPrefix(String prefix) { + if (prefix == null) mPrefix = ""; + else { + mPrefix = prefix; + } + } + + public String getPrefix() { + return mPrefix; + } + + public void incrementProgressBy(int by) { + if (by > 0) { + setProgress(getProgress() + by); + } + + if (mListener != null) { + mListener.onProgressChange(getProgress(), getMax()); + } + } + + public void setProgress(int progress) { + if (progress <= getMax() && progress >= 0) { + this.mCurrentProgress = progress; + invalidate(); + } + } + + @Override + protected Parcelable onSaveInstanceState() { + final Bundle bundle = new Bundle(); + bundle.putParcelable(INSTANCE_STATE, super.onSaveInstanceState()); + bundle.putInt(INSTANCE_TEXT_COLOR, getTextColor()); + bundle.putFloat(INSTANCE_TEXT_SIZE, getProgressTextSize()); + bundle.putFloat(INSTANCE_REACHED_BAR_HEIGHT, getReachedBarHeight()); + bundle.putFloat(INSTANCE_UNREACHED_BAR_HEIGHT, getUnreachedBarHeight()); + bundle.putInt(INSTANCE_REACHED_BAR_COLOR, getReachedBarColor()); + bundle.putInt(INSTANCE_UNREACHED_BAR_COLOR, getUnreachedBarColor()); + bundle.putInt(INSTANCE_MAX, getMax()); + bundle.putInt(INSTANCE_PROGRESS, getProgress()); + bundle.putString(INSTANCE_SUFFIX, getSuffix()); + bundle.putString(INSTANCE_PREFIX, getPrefix()); + bundle.putBoolean(INSTANCE_TEXT_VISIBILITY, getProgressTextVisibility()); + return bundle; + } + + @Override + protected void onRestoreInstanceState(Parcelable state) { + if (state instanceof Bundle) { + final Bundle bundle = (Bundle) state; + mTextColor = bundle.getInt(INSTANCE_TEXT_COLOR); + mTextSize = bundle.getFloat(INSTANCE_TEXT_SIZE); + mReachedBarHeight = bundle.getFloat(INSTANCE_REACHED_BAR_HEIGHT); + mUnreachedBarHeight = bundle.getFloat(INSTANCE_UNREACHED_BAR_HEIGHT); + mReachedBarColor = bundle.getInt(INSTANCE_REACHED_BAR_COLOR); + mUnreachedBarColor = bundle.getInt(INSTANCE_UNREACHED_BAR_COLOR); + initializePainters(); + setMax(bundle.getInt(INSTANCE_MAX)); + setProgress(bundle.getInt(INSTANCE_PROGRESS)); + setPrefix(bundle.getString(INSTANCE_PREFIX)); + setSuffix(bundle.getString(INSTANCE_SUFFIX)); + setProgressTextVisibility(bundle.getBoolean(INSTANCE_TEXT_VISIBILITY) ? ProgressTextVisibility.Visible : ProgressTextVisibility.Invisible); + super.onRestoreInstanceState(bundle.getParcelable(INSTANCE_STATE)); + return; + } + super.onRestoreInstanceState(state); + } + + public float dp2px(float dp) { + final float scale = getResources().getDisplayMetrics().density; + return dp * scale + 0.5f; + } + + public float sp2px(float sp) { + final float scale = getResources().getDisplayMetrics().scaledDensity; + return sp * scale; + } + + public void setProgressTextVisibility(ProgressTextVisibility visibility) { + mIfDrawText = visibility == ProgressTextVisibility.Visible; + invalidate(); + } + + public boolean getProgressTextVisibility() { + return mIfDrawText; + } + + public void setOnProgressBarListener(OnProgressBarListener listener) { + mListener = listener; + } +} diff --git a/app/src/main/res/drawable/bt_delete.png b/app/src/main/res/drawable/bt_delete.png new file mode 100644 index 0000000..c1d3740 Binary files /dev/null and b/app/src/main/res/drawable/bt_delete.png differ diff --git a/app/src/main/res/drawable/icon_biology.png b/app/src/main/res/drawable/icon_biology.png new file mode 100644 index 0000000..3391e3a Binary files /dev/null and b/app/src/main/res/drawable/icon_biology.png differ diff --git a/app/src/main/res/drawable/icon_chemistry.png b/app/src/main/res/drawable/icon_chemistry.png new file mode 100644 index 0000000..1b67635 Binary files /dev/null and b/app/src/main/res/drawable/icon_chemistry.png differ diff --git a/app/src/main/res/drawable/icon_english.png b/app/src/main/res/drawable/icon_english.png new file mode 100644 index 0000000..6f5ddc1 Binary files /dev/null and b/app/src/main/res/drawable/icon_english.png differ diff --git a/app/src/main/res/drawable/icon_game.png b/app/src/main/res/drawable/icon_game.png new file mode 100644 index 0000000..72394c9 Binary files /dev/null and b/app/src/main/res/drawable/icon_game.png differ diff --git a/app/src/main/res/drawable/icon_geography.png b/app/src/main/res/drawable/icon_geography.png new file mode 100644 index 0000000..b50d18c Binary files /dev/null and b/app/src/main/res/drawable/icon_geography.png differ diff --git a/app/src/main/res/drawable/icon_history.png b/app/src/main/res/drawable/icon_history.png new file mode 100644 index 0000000..99c7b5a Binary files /dev/null and b/app/src/main/res/drawable/icon_history.png differ diff --git a/app/src/main/res/drawable/icon_language.png b/app/src/main/res/drawable/icon_language.png new file mode 100644 index 0000000..b48fa58 Binary files /dev/null and b/app/src/main/res/drawable/icon_language.png differ diff --git a/app/src/main/res/drawable/icon_math.png b/app/src/main/res/drawable/icon_math.png new file mode 100644 index 0000000..61ec0f8 Binary files /dev/null and b/app/src/main/res/drawable/icon_math.png differ diff --git a/app/src/main/res/drawable/icon_physics.png b/app/src/main/res/drawable/icon_physics.png new file mode 100644 index 0000000..fc622ae Binary files /dev/null and b/app/src/main/res/drawable/icon_physics.png differ diff --git a/app/src/main/res/drawable/icon_politics.png b/app/src/main/res/drawable/icon_politics.png new file mode 100644 index 0000000..3bff914 Binary files /dev/null and b/app/src/main/res/drawable/icon_politics.png differ diff --git a/app/src/main/res/layout/activity_details.xml b/app/src/main/res/layout/activity_details.xml new file mode 100644 index 0000000..5ffe751 --- /dev/null +++ b/app/src/main/res/layout/activity_details.xml @@ -0,0 +1,179 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/app/src/main/res/layout/activity_download_manager.xml b/app/src/main/res/layout/activity_download_manager.xml new file mode 100644 index 0000000..26bedbb --- /dev/null +++ b/app/src/main/res/layout/activity_download_manager.xml @@ -0,0 +1,49 @@ + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/app/src/main/res/layout/activity_kind_detail.xml b/app/src/main/res/layout/activity_kind_detail.xml new file mode 100644 index 0000000..5b2b678 --- /dev/null +++ b/app/src/main/res/layout/activity_kind_detail.xml @@ -0,0 +1,53 @@ + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/app/src/main/res/layout/activity_local_manager.xml b/app/src/main/res/layout/activity_local_manager.xml new file mode 100644 index 0000000..7c6be19 --- /dev/null +++ b/app/src/main/res/layout/activity_local_manager.xml @@ -0,0 +1,57 @@ + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/app/src/main/res/layout/fragment_manage.xml b/app/src/main/res/layout/fragment_manage.xml index 6c58107..f522508 100644 --- a/app/src/main/res/layout/fragment_manage.xml +++ b/app/src/main/res/layout/fragment_manage.xml @@ -42,16 +42,10 @@ android:layout_height="match_parent" android:layout_weight="1" android:gravity="center_vertical" - android:text="53个应用可以升级" + android:text="0个应用可以升级" android:textColor="@color/black" android:textSize="16sp" /> -