> items, OnItemInteractionListener listener) {
20 | mValues = items;
21 | mListener = listener;
22 | }
23 |
24 | @Override
25 | public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
26 | View view = LayoutInflater.from(parent.getContext())
27 | .inflate(android.R.layout.simple_list_item_1, parent, false);
28 | return new ViewHolder(view, mListener);
29 | }
30 |
31 | @Override
32 | public final void onBindViewHolder(final ViewHolder holder, int position) {
33 | if (null != sectionFirstItemPosition && position >= sectionFirstItemPosition[0]) {//有多个分组
34 | int groupFirst;
35 | for (int i = sectionFirstItemPosition.length - 1; i > -1; --i) {//倒序循环
36 | groupFirst = sectionFirstItemPosition[i];//从最大的值开始
37 | if (position >= groupFirst) {
38 | onBindViewHolder(holder, i+1, position - groupFirst);
39 | return;
40 | }
41 | }
42 | } else {//第一组
43 | onBindViewHolder(holder, 0, position);
44 | }
45 | }
46 |
47 | public void onBindViewHolder(final ViewHolder holder, int section, int row) {
48 | String mItem = mValues.get(section).get(row);
49 | holder.section = section;
50 | holder.row = row;
51 | }
52 |
53 | @Override
54 | public int getItemCount() {
55 | return count > 0? count : 0;
56 | }
57 |
58 | public static class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener, View.OnLongClickListener {
59 | public TextView tvTitle;
60 | public int section;
61 | public int row;
62 | public Object data;
63 | private OnItemInteractionListener mListener;
64 |
65 | public ViewHolder(View view, OnItemInteractionListener listener) {
66 | super(view);
67 | // tvTitle = view.findViewById(R.id.)
68 | mListener = listener;
69 | view.setOnClickListener(this);
70 | view.setOnLongClickListener(this);
71 | }
72 |
73 | @Override
74 | public void onClick(View v) {
75 | // getAdapterPosition()
76 | if (null != mListener) {
77 | mListener.OnItemClick(section, row, data);
78 | }
79 | }
80 |
81 | @Override
82 | public boolean onLongClick(View v) {
83 | if (null != mListener) {
84 | mListener.OnItemLongClick(section, row, data);
85 | }
86 | return true;
87 | }
88 |
89 | @Override
90 | public String toString() {
91 | return super.toString() + " '" + tvTitle.getText() + "'";
92 | }
93 | }
94 |
95 | public interface OnItemInteractionListener {
96 | void OnItemClick(int section, int row, Object data);
97 | void OnItemLongClick(int section, int row, Object data);
98 | }
99 | }
100 |
--------------------------------------------------------------------------------
/厂商推送服务端关键字段.txt:
--------------------------------------------------------------------------------
1 | 厂商推送与页面跳转、推送测试、无限制推送相关的重要字段
2 | 1、字段详细说明请查官方文档,消息结构差异很大,一定要看官方文档
3 | 2、Android intent 转成 uri 后的固定格式: intent:#Intent;action="action 路径";component="包名"/"Activity 组件路径";S.key1=value1;i.key2=2;end
4 | intent uri 必须以 "intent:#Intent;" 开头,以 ";end" 结尾。
5 | 不允许存在多个 "action=" 字符或 "component=" 字符。
6 | "S.":代表参数值是 String 格式。
7 | "i.":代表参数值是 int 格式。
8 | 3、厂商推送对消息有数量限制,默认只有1~2条,想无限制推送,需要去厂商申请消息分类
9 | 4、有些厂商提供了测试模式,测试模式可以推送多条
10 | 5、tag 和 notify id 一般用于通知栏的覆盖或者撤回,用不到可以不填
11 | 6、被跳转的 Activity 必须设置 android:exported="true" 和 ,某些厂商得这么设置,否则无法打开Activity
12 | 7、一定要防止 Activity 类名打包时被混淆,否则intent里的Activity就对不上了
13 |
14 | 小米
15 | 无测试字段:
16 | restricted_package_name: App的包名,根据需要填。小米的一个AppID可以设置多个包名,此字段在这种情况下就有用了
17 | extra.notify_effect: "2" // 通知栏点击后打开app的任一Activity
18 | extra.intent_uri : "intent:#Intent;action=min.test.myaction;component=min.test/min.test.TestActivity;S.key1=value;i.key2=2;S.key3={\"messageNo\":null,\"title\":\"您的订单已取消\"};end"
19 | extra.channel_id : // 与无限制推送有关
20 | tag: // 目前无此参数
21 | notify_id: // 标识符
22 | 无限制推送: 申请消息分类,得到的 channel_id 填到 extra.channel_id 字段
23 | 推送角标由系统控制
24 |
25 | OPPO
26 | 无测试字段:貌似可以先在推送运营后台(配置管理中)添加测试设备,然后被添加的设备貌似就可以无限制推送了(未验证)
27 | click_action_type: 4 // 跳转指定应用内页(全路径类名); 5:跳转Intent scheme URL,要加字段 click_action_url: "intent:#Intent;action=min.test.myaction;component=min.test/min.test.TestActivity;S.key1=value;i.key2=2;S.key3={\"messageNo\":null,\"title\":\"您的订单已取消\"};end"
28 | click_action_activity: "min.test.TestActivity"
29 | action_parameters: "{\"messageNo\":null,\"title\":\"您的订单已取消\"}"
30 | channel_id :// 与无限制推送有关,旧的
31 | category: // 消息分类,与无限制推送有关,新的
32 | notify_level: // 通知弹窗方式/提醒方式,新的
33 | tag: // 目前无此参数
34 | notify_id: // 标识符
35 | 无限制推送: 申请私信通道权限,要发邮件,通过后要在平台上登记
36 | 推送无角标设置
37 |
38 | vivo
39 | pushMode: 1 // 先在推送运营后台添加测试设备,否则无效;推送模式 0:正式推送;1:测试推送,不填默认0;
40 | category: // 消息分类,与无限制推送有关
41 | skipType: 4 // 打开app内指定页面
42 | skipContent: "intent:#Intent;action=min.test.myaction;component=min.test/min.test.TestActivity;S.key1=value;i.key2=2;S.key3={\"messageNo\":null,\"title\":\"您的订单已取消\"};end"
43 | addBadge: true // 角标,大部分类型的App还未开放,具体看文档或找客服问
44 | clientCustomMap: // 看文档,也许有用
45 | channel_id: // 目前无此参数
46 | tag: // 目前无此参数
47 | notifyId: // 标识符
48 | 无限制推送: 提工单开通
49 |
50 | 华为
51 | target_user_type: 1 // 1:测试消息;0:普通消息;不填默认0;每个应用每日可发送该测试消息500条且不受每日单设备推送数量上限要求
52 | category: // 消息分类,与无限制推送有关,自分类权益 开通哪个填哪个
53 | click_action: {
54 | type: 3, // 打开应用自定义页面
55 | intent: "intent:#Intent;action=min.test.myaction;component=min.test/min.test.TestActivity;S.key1=value;i.key2=2;S.key3={\"messageNo\":null,\"title\":\"您的订单已取消\"};end"
56 | }
57 | badge: {
58 | class: "min.test.TestActivity", // 入口Activity
59 | add_num: 1 // 不填置默认+1
60 | }
61 | channel_id:
62 | tag: // 标识符
63 | notify_id: // 标识符
64 | 无限制推送: 在 推送服务->配置 里开通 自分类权益
65 |
66 | 荣耀
67 | targetUserType: 1 // 1:测试消息;0:普通消息;不填默认0;每个应用每日可发送该测试消息500条且不受每日单设备推送数量上限要求
68 | importance: "NORMAL" // 消息分类,目前与无限制推送有关,以后可能会变动;LOW:资讯营销类消息,NORMAL:服务与通讯类消息;NORMAL无限制推送
69 | clickAction: {
70 | type: 1, // 打开应用自定义页面
71 | intent: "intent:#Intent;action=min.test.myaction;component=min.test/min.test.TestActivity;S.key1=value;i.key2=2;S.key3={\"messageNo\":null,\"title\":\"您的订单已取消\"};end"
72 | }
73 | badge: {
74 | badgeClass: "min.test.TestActivity", // 入口Activity
75 | addNum: 1 // 不填置默认+1
76 | }
77 | channel_id: // 目前无此参数
78 | tag: // 标识符
79 | notifyId: // 标识符
80 | 无限制推送: 目前参考 importance
81 |
82 | FCM
83 | restricted_package_name: App的包名。根据需要填。注册令牌必须匹配的应用程序的包名称才能接收消息。
84 | data: json object // 传参
85 | click_action: "min.test.TestActivity" // 可以是 Activity 全名(貌似这种方式无效),也可以是 action name
86 | color: "#FF0000" // 通知的图标颜色,以#rrggbb 格式表示。如果app内部没有默认值,最好填一个
87 | notification_count: 1 // 角标,不填置默认+1
88 | channel_id:
89 | tag: // 标识符
90 | notify_id: // 目前无此参数
91 |
--------------------------------------------------------------------------------
/app/src/main/java/template/CircleProgressView.java:
--------------------------------------------------------------------------------
1 | package template;
2 |
3 | import android.animation.ValueAnimator;
4 | import android.content.Context;
5 | import android.graphics.Canvas;
6 | import android.graphics.Color;
7 | import android.graphics.Paint;
8 | import android.graphics.RectF;
9 | import android.util.AttributeSet;
10 | import android.util.TypedValue;
11 | import android.view.View;
12 | import android.view.animation.LinearInterpolator;
13 |
14 | import androidx.annotation.NonNull;
15 | import androidx.annotation.Nullable;
16 |
17 | import java.util.Optional;
18 |
19 | public class CircleProgressView extends View {
20 |
21 | private Paint circlePaint;
22 | private Paint circleBgPaint;
23 | private float strokeWidth;
24 | private float radius;
25 | private float centerX;
26 | private float centerY;
27 | private RectF rectF;
28 | private float sweepAngle;
29 | private ValueAnimator animator;
30 |
31 | public CircleProgressView(Context context, @Nullable AttributeSet attrs) {
32 | super(context, attrs);
33 | init();
34 | }
35 |
36 | public CircleProgressView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
37 | super(context, attrs, defStyleAttr);
38 | init();
39 | }
40 |
41 | public CircleProgressView(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
42 | super(context, attrs, defStyleAttr, defStyleRes);
43 | init();
44 | }
45 |
46 | public CircleProgressView(Context context) {
47 | super(context);
48 | init();
49 | }
50 |
51 | private void init() {
52 | sweepAngle = 0;
53 | strokeWidth = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 10,
54 | getResources().getDisplayMetrics());
55 | // 动画环画笔
56 | circlePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
57 | circlePaint.setColor(Color.BLUE);
58 | circlePaint.setStyle(Paint.Style.STROKE);
59 | circlePaint.setStrokeCap(Paint.Cap.ROUND);
60 | circlePaint.setStrokeWidth(strokeWidth);
61 |
62 | // 背景环画笔
63 | circleBgPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
64 | circleBgPaint.setColor(Color.GRAY);
65 | circleBgPaint.setStyle(Paint.Style.STROKE);
66 | circleBgPaint.setStrokeCap(Paint.Cap.ROUND);
67 | circleBgPaint.setStrokeWidth(strokeWidth);
68 | }
69 |
70 | @Override
71 | protected void onSizeChanged(int w, int h, int oldw, int oldh) {
72 | super.onSizeChanged(w, h, oldw, oldh);
73 | float minSize = Math.min(getHeight(), getWidth());
74 | radius = (minSize - strokeWidth) / 2;
75 | centerX = getWidth() / 2.0f;
76 | centerY = getHeight() / 2.0f;
77 | rectF = new RectF();
78 | rectF.left = 0 + strokeWidth/2;
79 | rectF.top = 0 + strokeWidth/2;
80 | rectF.right = minSize - strokeWidth/2;
81 | rectF.bottom = minSize - strokeWidth/2;
82 | }
83 |
84 | @Override
85 | protected void onDraw(@NonNull Canvas canvas) {
86 | super.onDraw(canvas);
87 |
88 | // 绘制圆环
89 | canvas.drawCircle(centerX, centerY, radius, circleBgPaint);
90 | // canvas.drawArc(rectF, 0, 360, false, circleBgPaint);
91 | canvas.drawArc(rectF, -90, sweepAngle, false, circlePaint);
92 | }
93 |
94 | /**
95 | * 开始动画
96 | * @param totalTime 总时间
97 | * @param remainingTime 剩余时间
98 | */
99 | public void startAnim(long totalTime, long remainingTime) {
100 | Optional.ofNullable(animator).ifPresent(ValueAnimator::cancel);
101 |
102 | animator = ValueAnimator.ofFloat(-360.0f * remainingTime / totalTime, 0);
103 | animator.setDuration(remainingTime);
104 | animator.setInterpolator(new LinearInterpolator());
105 | animator.addUpdateListener(animation -> {
106 | sweepAngle = (Float) animation.getAnimatedValue();
107 | invalidate();
108 | });
109 | animator.start();
110 | }
111 |
112 | public void stopAnim() {
113 | if (null != animator) {
114 | animator.cancel();
115 | animator = null;
116 | }
117 | sweepAngle = 0;
118 | invalidate();
119 | }
120 | }
121 |
--------------------------------------------------------------------------------
/app/src/main/java/template/BottomNavigationFragment.java:
--------------------------------------------------------------------------------
1 | package template;
2 |
3 | import android.annotation.SuppressLint;
4 | import android.os.Bundle;
5 | import android.view.LayoutInflater;
6 | import android.view.MenuItem;
7 | import android.view.View;
8 | import android.view.ViewGroup;
9 |
10 | import androidx.annotation.NonNull;
11 | import androidx.annotation.Nullable;
12 | import androidx.fragment.app.Fragment;
13 |
14 | import com.google.android.material.bottomnavigation.BottomNavigationItemView;
15 | import com.google.android.material.bottomnavigation.BottomNavigationMenuView;
16 | import com.google.android.material.bottomnavigation.BottomNavigationView;
17 | import com.google.android.material.bottomnavigation.LabelVisibilityMode;
18 |
19 | //https://www.jianshu.com/p/24278f3259b3
20 | //https://stackoverflow.com/questions/40176244/how-to-disable-bottomnavigationview-shift-mode
21 | public class BottomNavigationFragment extends Fragment {
22 |
23 | private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
24 | = new BottomNavigationView.OnNavigationItemSelectedListener() {
25 |
26 | @Override
27 | public boolean onNavigationItemSelected(@NonNull MenuItem item) {
28 | switch (item.getItemId()) {
29 | }
30 | return false;
31 | }
32 | };
33 |
34 | /*
35 | 布局文件
36 |
48 | */
49 |
50 | @Nullable
51 | @Override
52 | public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
53 |
54 | /*
55 | BottomNavigationView的item移动的原因有两个:
56 | 1、选中的item显示title,而未选中的不显示;
57 | 解决方案:1.设置所有item不显示title
58 | 2.设置所有item显示title,这也是产生移动的第二个原因
59 | 2、item有2个TextView,分别显示选中和未选中的title,但他们的textSize不一样
60 | 解决方案:1.覆盖这两个textSize,设置成一样
61 | */
62 | BottomNavigationView navigation = new BottomNavigationView(container.getContext());
63 | navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
64 | //解决移动的第1个原因,此属性貌似在安卓8.0以后才有,
65 | //也可在布局文件中设置app:labelVisibilityMode="labeled"
66 | // navigation.setLabelVisibilityMode(LabelVisibilityMode.LABEL_VISIBILITY_LABELED);
67 | /*
68 | 解决移动的第2个原因
69 | 然后把下面两个拷贝到dimens.xml文件中,注意:这两行的值要完全相等,以保证选中和未选中状态的字体大小一样
70 | 12sp
71 | 12sp
72 |
73 | //禁止item平移,但textSize不一样时,会有上下移动
74 | app:itemHorizontalTranslationEnabled="false"
75 |
76 | 如果要设置icon距离上边距的距离,也可以通过重新定义R.dimen.design_bottom_navigation_margin来实现,
77 | 也就是
78 | 12dp
79 | */
80 |
81 | //使用了上面两种方法,这个就不用了
82 | // removeShiftMode(navigation);
83 | return null;
84 | }
85 |
86 | @SuppressLint("RestrictedApi")
87 | static void removeShiftMode(BottomNavigationView view) {
88 | BottomNavigationMenuView menuView = (BottomNavigationMenuView) view.getChildAt(0);
89 | for (int i = 0; i < menuView.getChildCount(); i++) {
90 | BottomNavigationItemView item = (BottomNavigationItemView) menuView.getChildAt(i);
91 | //noinspection RestrictedApi
92 | item.setShifting(false);//Android8.0以前不是这个方法,而且要用反射
93 | item.setLabelVisibilityMode(LabelVisibilityMode.LABEL_VISIBILITY_LABELED);
94 |
95 | // set once again checked value, so view will be updated
96 | //noinspection RestrictedApi
97 | item.setChecked(item.getItemData().isChecked());
98 | }
99 | }
100 | }
101 |
--------------------------------------------------------------------------------
/app/src/main/java/utils/get_context_no_dependence_anything/Applications.java:
--------------------------------------------------------------------------------
1 | package utils.get_context_no_dependence_anything;
2 |
3 | import android.annotation.SuppressLint;
4 | import android.app.Application;
5 | import android.util.Log;
6 |
7 | import androidx.annotation.NonNull;
8 |
9 | import java.lang.reflect.Field;
10 | import java.lang.reflect.Method;
11 |
12 | /**
13 | * 借用的源码:
14 | * https://github.com/kaedea/Feya/blob/master/feya/applications/droid.feya/src/main/java/me/kaede/feya/context/Applications.java
15 | */
16 | @SuppressWarnings({"WeakerAccess", "unused"})
17 | public class Applications {
18 | private static final String TAG = "Applications";
19 |
20 | /**
21 | * Access a global {@link Application} context from anywhere, such as getting a context in a Library
22 | * module without attaching it from App module.
23 | *
24 | * Note that this method may return null in some cases, such as working with a hotfix framework
25 | * or access when the App is terminated.
26 | *
27 | * 此context只用来获取资源,不要用来启动Activity和Service
28 | */
29 | @NonNull
30 | public static Application context() {
31 | if (CURRENT != null) {
32 | return CURRENT;
33 | }
34 | if (sAttached != null) {
35 | Log.w(TAG, "Seems CURRENT is null here, you may call Applications#context() before or " +
36 | "inside Application#attachBaseContext(Context), which is not recommended.");
37 | return sAttached;
38 | }
39 | throw new IllegalStateException("Please make sure you do not call Applications#context() " +
40 | "before or inside Application#attachBaseContext(Context). " +
41 | "If you have to, please call Applications#attach(Application) first.");
42 | }
43 |
44 | @SuppressLint("StaticFieldLeak")
45 | private static final Application CURRENT;
46 | @SuppressLint("StaticFieldLeak")
47 | private static Application sAttached;
48 |
49 | static {
50 | /*
51 | * The following 'Magic Code' is going to access the Application context from ActivityThread.
52 | * For now, it works only after Applications#attach(Application).
53 | *
54 | * Note that if you call this method before or inside Applications#attach(Application),
55 | * {@link Applications#CURRENT} will always be null.
56 | */
57 | try {
58 | Object app = autoAttach();
59 | if (app == null) {
60 | throw new IllegalStateException("Can not get Application context, " +
61 | "pls make sure that you didn't call this method before or inner " +
62 | "Application#attachBaseContext(Context)");
63 | }
64 | CURRENT = (Application) app;
65 |
66 | //noinspection ConstantConditions
67 | if (CURRENT == null) {
68 | throw new IllegalStateException("Can not access Application context from ActivityThread, " +
69 | "please make sure that you did not call this method before or inside Application#attachBaseContext(Context).");
70 | }
71 | } catch (Throwable e) {
72 | throw new IllegalStateException("Can not access Application context by magic code, boom!", e);
73 | }
74 | }
75 |
76 | private static Object autoAttach() throws ReflectiveOperationException {
77 | Object activityThread = AndroidHacks.getActivityThread();
78 | Class> activityThreadClass = Class.forName("android.app.ActivityThread");
79 | Method method = activityThreadClass.getMethod("getApplication");
80 | method.setAccessible(true);
81 | Object app = method.invoke(activityThread);
82 | method.setAccessible(false);
83 |
84 | if (app == null) {
85 | Field field = activityThreadClass.getField("mInitialApplication");
86 | field.setAccessible(true);
87 | app = field.get(activityThread);
88 | field.setAccessible(false);
89 | }
90 | return app;
91 | }
92 |
93 | /**
94 | * Manually attach an Application context for {@link Applications#sAttached}. If the above
95 | * Magic Code works, this method is not necessary.
96 | *
97 | * @see #autoAttach()
98 | */
99 | public static void attach(@NonNull Application app) {
100 | if (sAttached == null) {
101 | sAttached = app;
102 | }
103 | }
104 | }
105 |
--------------------------------------------------------------------------------
/app/build.gradle.kts:
--------------------------------------------------------------------------------
1 | // https://developer.android.google.cn/studio/projects/android-library
2 | import java.util.Properties
3 |
4 | plugins {
5 | alias(libs.plugins.android.application)
6 | alias(libs.plugins.kotlin.android)
7 | }
8 |
9 | // 上面要 import
10 | val keystoreProperties = Properties()
11 | // 自定义keystore本地配置。放在项目根目录下
12 | val file = rootProject.file("keystore.properties");
13 | if (file.exists()) {
14 | file.inputStream().use { keystoreProperties.load(it) }
15 | }
16 |
17 | android {
18 | namespace = "min.test.android_app_template"
19 | compileSdk = 35
20 |
21 | defaultConfig {
22 | applicationId = "min.test.android_app_template"
23 | minSdk = 26
24 | targetSdk = 35
25 | versionCode = 1
26 | versionName = "1.0"
27 | // 自定义打包名称,不完全自定义,后面自动会加上${buildType.name}
28 | base.archivesName = "Template-v$versionName-$versionCode-" + (Math.floor(Math.random() * 1000000) + 1).toInt()
29 | // 替换值
30 | manifestPlaceholders += mapOf(
31 | "AAA" to "1111",
32 | )
33 | ndk.abiFilters += mutableSetOf("arm64-v8a", "armeabi-v7a", "x86_64")
34 | /*splits {
35 | // 根据像素密度生成多个单一apk
36 | density {
37 | isEnable = true
38 | reset()
39 | include("hdpi", "xhdpi", "xxhdpi", "xxxhdpi")
40 | }
41 | // 根据ABI生成多个单一apk
42 | abi {
43 | // Enables building multiple APKs per ABI.
44 | isEnable = true
45 |
46 | // By default all ABIs are included, so use reset() and include to specify that we only
47 | // want APKs for x86 and x86_64.
48 |
49 | // Resets the list of ABIs that Gradle should create APKs for to none.
50 | reset()
51 |
52 | // 不能与 ndk.abiFilters 同时配置,否则报错
53 | // Specifies a list of ABIs that Gradle should create APKs for.
54 | include("arm64-v8a", "armeabi-v7a")//"x86", "x86_64"
55 |
56 | // Specifies that we do not want to also generate a universal APK that includes all ABIs.
57 | isUniversalApk = false
58 | }
59 | }*/
60 |
61 | testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
62 | }
63 | // 必须放在 buildTypes 上面
64 | signingConfigs {
65 | // release 不存在要自己创建
66 | create("release") {
67 | // keyAlias = keystoreProperties["keyAlias"] as String
68 | // keyPassword = keystoreProperties["keyPassword"] as String
69 | // storeFile = keystoreProperties["storeFile"]?.let { file(it) }
70 | // storePassword = keystoreProperties["storePassword"] as String
71 | }
72 | // debug 本身就有
73 | getByName("debug") {
74 | // keyAlias = keystoreProperties["keyAlias"] as String
75 | // keyPassword = keystoreProperties["keyPassword"] as String
76 | // storeFile = keystoreProperties["storeFile"]?.let { file(it) }
77 | // storePassword = keystoreProperties["storePassword"] as String
78 | }
79 | }
80 |
81 | buildTypes {
82 | release {
83 | isMinifyEnabled = false
84 | proguardFiles(
85 | getDefaultProguardFile("proguard-android-optimize.txt"),
86 | "proguard-rules.pro"
87 | )
88 | signingConfig = signingConfigs.getByName("release")
89 | }
90 | }
91 | compileOptions {
92 | sourceCompatibility = JavaVersion.VERSION_11
93 | targetCompatibility = JavaVersion.VERSION_11
94 | }
95 | kotlinOptions {
96 | jvmTarget = "11"
97 | }
98 | buildFeatures {
99 | // compose = true
100 | // 支持视图绑定
101 | viewBinding = true
102 | }
103 | }
104 |
105 | dependencies {
106 |
107 | implementation(libs.androidx.core.ktx)
108 | implementation(libs.androidx.appcompat)
109 | // implementation(libs.androidx.activity)
110 | implementation(libs.material)
111 | implementation(libs.androidx.constraintlayout)
112 | implementation(libs.androidx.recyclerview)
113 | implementation(libs.okhttp)
114 | // 跟踪和报告应用的各种运行时指标
115 | implementation(libs.androidx.metrics.performance)
116 | // 读取和写入图片文件 EXIF 标记
117 | implementation(libs.androidx.exifinterface)
118 | implementation(libs.rxjava)
119 | implementation(libs.rxandroid)
120 | // fileTree 写法
121 | implementation(fileTree("libs") {
122 | include("*.aar", "*.jar")
123 | })
124 |
125 | // 在 Android Studio 中准确衡量代码性能, 性能测试框架
126 | androidTestImplementation(libs.androidx.benchmark.macro.junit4)
127 | // 远程测试框架
128 | androidTestImplementation(libs.androidx.uiautomator)
129 |
130 | testImplementation(libs.junit)
131 | androidTestImplementation(libs.androidx.junit)
132 | androidTestImplementation(libs.androidx.espresso.core)
133 | }
--------------------------------------------------------------------------------
/app/src/main/java/template/recyclerview_group/SectionRVTestFragment.java:
--------------------------------------------------------------------------------
1 | package template.recyclerview_group;
2 |
3 | import android.content.Context;
4 | import android.os.Bundle;
5 | import android.util.Log;
6 | import android.view.LayoutInflater;
7 | import android.view.View;
8 | import android.view.ViewGroup;
9 |
10 | import androidx.fragment.app.Fragment;
11 | import androidx.recyclerview.widget.LinearLayoutManager;
12 | import androidx.recyclerview.widget.RecyclerView;
13 |
14 | import java.util.ArrayList;
15 | import java.util.LinkedList;
16 |
17 | public class SectionRVTestFragment extends Fragment implements SectionRVAdapter.OnItemInteractionListener {
18 |
19 | private Context context;
20 | private String titles[];
21 | private ArrayList> tasks;
22 | private ArrayList loadingTasks;
23 | private ArrayList doneTasks;
24 | private ArrayList errorTasks;
25 |
26 | private SectionItemDecoration titleDecoration;
27 | private SectionRVAdapter adapter;
28 |
29 | @Override
30 | public void onCreate(Bundle savedInstanceState) {
31 | super.onCreate(savedInstanceState);
32 |
33 | tasks = new ArrayList<>(3);
34 | loadingTasks = new ArrayList<>(3);
35 | doneTasks = new ArrayList<>(3);
36 | errorTasks = new ArrayList<>(3);
37 | // titles = context.getResources().getStringArray(R.array.permission);
38 | titles = new String[]{"正在下载", "下载完成", "下载失败"};
39 |
40 | loadingTasks.add("task0-1");
41 | loadingTasks.add("task0-2");
42 | loadingTasks.add("task0-3");
43 | loadingTasks.add("task0-4");
44 | loadingTasks.add("task0-5");
45 | loadingTasks.add("task0-6");
46 | loadingTasks.add("task0-7");
47 | loadingTasks.add("task0-8");
48 | loadingTasks.add("task0-9");
49 | loadingTasks.add("task0-10");
50 | loadingTasks.add("task0-11");
51 | loadingTasks.add("task0-12");
52 |
53 | doneTasks.add("task1-1");
54 | doneTasks.add("task1-2");
55 | doneTasks.add("task1-3");
56 | doneTasks.add("task1-4");
57 | doneTasks.add("task1-5");
58 | doneTasks.add("task1-6");
59 | doneTasks.add("task1-7");
60 | doneTasks.add("task1-8");
61 | doneTasks.add("task1-9");
62 | doneTasks.add("task1-10");
63 | doneTasks.add("task1-11");
64 | doneTasks.add("task1-12");
65 |
66 | errorTasks.add("task2-1");
67 | errorTasks.add("task2-2");
68 | errorTasks.add("task2-3");
69 | errorTasks.add("task2-4");
70 | errorTasks.add("task2-5");
71 | errorTasks.add("task2-6");
72 | errorTasks.add("task2-7");
73 | errorTasks.add("task2-8");
74 | errorTasks.add("task2-9");
75 | errorTasks.add("task2-10");
76 | errorTasks.add("task2-11");
77 | errorTasks.add("task2-12");
78 | }
79 |
80 | @Override
81 | public View onCreateView(LayoutInflater inflater, ViewGroup container,
82 | Bundle savedInstanceState) {
83 | // View view = inflater.inflate(android.R.layout.list_content, container, false);
84 | View view = new RecyclerView(container.getContext());//这里换成自己的视图
85 | if (view instanceof RecyclerView) {
86 | Context context = view.getContext();
87 | RecyclerView recyclerView = (RecyclerView) view;
88 | recyclerView.setLayoutManager(new LinearLayoutManager(context));
89 |
90 | adapter = new SectionRVAdapter(tasks, this);
91 | recyclerView.setAdapter(adapter);
92 |
93 | titleDecoration = new SectionItemDecoration(context);
94 | titleDecoration.titleDocksAtTheTop = true;
95 | recyclerView.addItemDecoration(titleDecoration);
96 | sortGroup();
97 | }
98 | return view;
99 | }
100 |
101 |
102 | @Override
103 | public void onAttach(Context context) {
104 | super.onAttach(context);
105 | this.context = context;
106 | }
107 |
108 | @Override
109 | public void onStart() {
110 | super.onStart();
111 | }
112 |
113 | @Override
114 | public void onDetach() {
115 | super.onDetach();
116 | context = null;
117 | }
118 |
119 | private void sortGroup() {
120 | tasks.clear();
121 | //重新排列数据和标题
122 | LinkedList list = new LinkedList<>();
123 | if (loadingTasks.size() > 0) {
124 | tasks.add(loadingTasks);
125 | list.add(titles[0]);
126 | }
127 | if (doneTasks.size() > 0) {
128 | tasks.add(doneTasks);
129 | list.add(titles[1]);
130 | }
131 | if (errorTasks.size() > 0) {
132 | tasks.add(errorTasks);
133 | list.add(titles[2]);
134 | }
135 |
136 | SectionItemDecoration.setGroup(titleDecoration, adapter, list, tasks);
137 | adapter.notifyDataSetChanged();
138 | }
139 |
140 | @Override
141 | public void OnItemClick(int section, int row, Object data) {
142 | Log.e("OnItemClick", section + "," + row);
143 | }
144 | @Override
145 | public void OnItemLongClick(int section, int row, Object data) {
146 | Log.e("OnItemLongClick", section + "," + row);
147 | }
148 | }
149 |
--------------------------------------------------------------------------------
/app/src/main/java/template/UDP.java:
--------------------------------------------------------------------------------
1 | package template;
2 |
3 | import android.content.Context;
4 |
5 | import java.io.IOException;
6 | import java.net.DatagramPacket;
7 | import java.net.DatagramSocket;
8 | import java.net.InetAddress;
9 | import java.net.InetSocketAddress;
10 | import java.net.SocketException;
11 | import java.net.SocketTimeoutException;
12 |
13 | //发送者
14 | class UDPSender {
15 | private String IPv4;
16 | private DatagramSocket socket;
17 |
18 | /**
19 | * //获取WiFi的ip
20 | WifiInfo wifiInfo = ((WifiManager)context.getSystemService(Context.WIFI_SERVICE)).getConnectionInfo();
21 | int ipAddress = wifiInfo.getIpAddress();
22 | String IPv4 = ((ipAddress & 0xff) + "." + (ipAddress>>8 & 0xff) + "." +
23 | (ipAddress>>16 & 0xff) + "." + (ipAddress>>24 & 0xff));
24 | */
25 |
26 | public static UDPSender getInstance(Context context) throws SocketException {
27 | // DatagramSocket socket = new DatagramSocket(port);//这么写会导致端口一直占用
28 | DatagramSocket socket = new DatagramSocket(null);//这里设置为null,setReuseAddress才会有效
29 | socket.setReuseAddress(true);//可复用,地址或者端口号
30 | socket.setBroadcast(true);//允许发送广播
31 | //socket不用绑定任何IP或端口号也能发送UDP广播,因为系统会自动分配端口
32 |
33 | return new UDPSender(socket, "IPv4");
34 | }
35 |
36 | private UDPSender(DatagramSocket socket, String IPv4) {
37 | this.IPv4 = IPv4;
38 | this.socket = socket;
39 | }
40 |
41 | private int port = 1234;//对方接收的端口
42 | public void send() {
43 | try {
44 | //要发送的数据
45 | byte[] bytes = "hello".getBytes();
46 | //广播地址255.255.255.255
47 | byte[] broadcast = new byte[]{(byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff};
48 | // InetAddress.getByName(IPv4);//或者对方地址
49 | //组装数据包
50 | DatagramPacket dataPacket = new DatagramPacket(bytes, bytes.length, InetAddress.getByAddress(broadcast), port);
51 | socket.send(dataPacket);//发送数据包
52 |
53 | } catch (IOException e) {
54 | // Log.e(TAG, "run: ", e);
55 | } finally {
56 | cancel();
57 | }
58 | }
59 |
60 | //发送完数据要释放资源
61 | public void cancel() {
62 | if (null != socket) {
63 | socket.close();
64 | }
65 | socket = null;
66 | }
67 | }
68 |
69 | class UDPReceiver extends Thread {
70 |
71 | private boolean cancelled = false;
72 | private DatagramSocket socket;
73 | private ReceiveListener listener;
74 |
75 | /**
76 | *
77 | * @param port 要监听的本地端口
78 | * @param listener 把收到的数据通过此接口传递出去
79 | * @return
80 | * @throws SocketException
81 | */
82 | public static UDPReceiver getInstance(int port, ReceiveListener listener) throws SocketException {
83 | // DatagramSocket socket = new DatagramSocket(port);//这么写会导致端口一直占用
84 | DatagramSocket socket = new DatagramSocket(null);
85 | socket.setReuseAddress(true);
86 | socket.bind(new InetSocketAddress(port));//监听指定的端口,若是不指定端口,系统会自动分配端口
87 | socket.setBroadcast(true);
88 | socket.setSoTimeout(15);//设置超时时间
89 | //若是不指定端口,此方法可获取系统自动分配的端口,然后通过某种方式告诉对方(如:广播包中携带此端口号)
90 | // socket.getLocalPort();
91 | return new UDPReceiver(socket, listener);
92 | }
93 |
94 | private UDPReceiver(DatagramSocket socket, ReceiveListener listener) {
95 | this.socket = socket;
96 | this.listener = listener;
97 | }
98 |
99 | //取消,释放资源
100 | public void cancel() {
101 | if (cancelled) return;
102 | if (null != socket) socket.close();
103 |
104 | socket = null;
105 | listener = null;
106 | cancelled = true;
107 | }
108 |
109 | @Override
110 | public void run() {
111 | try {
112 | byte[] bytes;
113 | DatagramPacket dataPacket;
114 | while (!cancelled) {
115 | bytes = new byte[1024];
116 | dataPacket = new DatagramPacket(bytes, bytes.length);//存放数据的盒子
117 | socket.receive(dataPacket);//接收数据包
118 | new ParseThread(dataPacket, listener).start();//开线程去解析收到的数据,我这里简单粗暴了点
119 | }
120 | } catch (SocketTimeoutException e) {
121 | //超时不用管
122 | } catch (IOException e) {
123 | // Log.e(TAG, "run: ", e);
124 | } finally {
125 | cancel();
126 | }
127 | }
128 |
129 | //用线程去解析数据
130 | static class ParseThread extends Thread {
131 | private DatagramPacket dataPacket;
132 | private ReceiveListener listener;
133 |
134 | public ParseThread(DatagramPacket dataPacket, ReceiveListener listener) {
135 | this.dataPacket = dataPacket;
136 | this.listener = listener;
137 | }
138 |
139 | @Override
140 | public void run() {
141 | //把收到的数据转成字符串
142 | String message = new String(dataPacket.getData(), dataPacket.getOffset(), dataPacket.getLength());
143 | //解析message成你要的数据
144 | //把数据传递出去
145 | listener.receive(message);
146 |
147 | dataPacket = null;
148 | listener = null;
149 | }
150 | }
151 |
152 | public interface ReceiveListener {
153 | void receive(String message);
154 | }
155 | }
156 |
157 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # Non-project-specific build files:
2 | build.xml
3 | /app/gradlew
4 | /app/gradlew.bat
5 | /app/gradle
6 | map.txt
7 | release-signing.properties
8 | debug-signing.properties
9 | # Ant builds
10 | ant-build
11 | ant-gen
12 | # Eclipse builds
13 | gen
14 | out
15 | # Gradle build artifacts
16 | .gradletasknamecache
17 | gradle-app.setting
18 |
19 | #================== Android.gitignore ==================
20 | # Gradle files
21 | .gradle/
22 | build/
23 | release/
24 |
25 | # Local configuration file (sdk path, etc)
26 | local.properties
27 |
28 | # Log/OS Files
29 | *.log
30 |
31 | # Android Studio generated files and folders
32 | captures/
33 | .externalNativeBuild/
34 | .cxx/
35 | *.aab
36 | *.apk
37 | output.json
38 | output-metadata.json
39 |
40 | # IntelliJ
41 | *.iml
42 | .idea/
43 | misc.xml
44 | deploymentTargetDropDown.xml
45 | render.experimental.xml
46 |
47 | # Keystore files
48 | *.jks
49 | *.keystore
50 |
51 | # Google Services (e.g. APIs or Firebase)
52 | google-services.json
53 | agconnect-services.json
54 |
55 | # Android Profiling
56 | *.hprof
57 |
58 | #================== JetBrains.gitignore ==================
59 | # Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio, WebStorm and Rider
60 | # Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839
61 |
62 | # User-specific stuff
63 | .idea/**/workspace.xml
64 | .idea/**/tasks.xml
65 | .idea/**/usage.statistics.xml
66 | .idea/**/dictionaries
67 | .idea/**/shelf
68 |
69 | # AWS User-specific
70 | .idea/**/aws.xml
71 |
72 | # Generated files
73 | .idea/**/contentModel.xml
74 |
75 | # Sensitive or high-churn files
76 | .idea/**/dataSources/
77 | .idea/**/dataSources.ids
78 | .idea/**/dataSources.local.xml
79 | .idea/**/sqlDataSources.xml
80 | .idea/**/dynamic.xml
81 | .idea/**/uiDesigner.xml
82 | .idea/**/dbnavigator.xml
83 |
84 | # Gradle
85 | .idea/**/gradle.xml
86 | .idea/**/libraries
87 |
88 | # Gradle and Maven with auto-import
89 | # When using Gradle or Maven with auto-import, you should exclude module files,
90 | # since they will be recreated, and may cause churn. Uncomment if using
91 | # auto-import.
92 | # .idea/artifacts
93 | # .idea/compiler.xml
94 | # .idea/jarRepositories.xml
95 | # .idea/modules.xml
96 | # .idea/*.iml
97 | # .idea/modules
98 | # *.iml
99 | # *.ipr
100 |
101 | # CMake
102 | cmake-build-*/
103 |
104 | # Mongo Explorer plugin
105 | .idea/**/mongoSettings.xml
106 |
107 | # File-based project format
108 | *.iws
109 |
110 | # IntelliJ
111 | out/
112 |
113 | # mpeltonen/sbt-idea plugin
114 | .idea_modules/
115 |
116 | # JIRA plugin
117 | atlassian-ide-plugin.xml
118 |
119 | # Cursive Clojure plugin
120 | .idea/replstate.xml
121 |
122 | # SonarLint plugin
123 | .idea/sonarlint/
124 |
125 | # Crashlytics plugin (for Android Studio and IntelliJ)
126 | com_crashlytics_export_strings.xml
127 | crashlytics.properties
128 | crashlytics-build.properties
129 | fabric.properties
130 |
131 | # Editor-based Rest Client
132 | .idea/httpRequests
133 |
134 | # Android studio 3.1+ serialized cache file
135 | .idea/caches/build_file_checksums.ser
136 |
137 | #================== macOS.gitignore ==================
138 | # General
139 | .DS_Store
140 | .AppleDouble
141 | .LSOverride
142 |
143 | # Icon must end with two \r
144 | Icon
145 |
146 | # Thumbnails
147 | ._*
148 |
149 | # Files that might appear in the root of a volume
150 | .DocumentRevisions-V100
151 | .fseventsd
152 | .Spotlight-V100
153 | .TemporaryItems
154 | .Trashes
155 | .VolumeIcon.icns
156 | .com.apple.timemachine.donotpresent
157 |
158 | # Directories potentially created on remote AFP share
159 | .AppleDB
160 | .AppleDesktop
161 | Network Trash Folder
162 | Temporary Items
163 | .apdisk
164 |
165 | #================== Linux.gitignore ==================
166 | *~
167 |
168 | # temporary files which can be created if a process still has a handle open of a deleted file
169 | .fuse_hidden*
170 |
171 | # KDE directory preferences
172 | .directory
173 |
174 | # Linux trash folder which might appear on any partition or disk
175 | .Trash-*
176 |
177 | # .nfs files are created when an open file is removed but is still being accessed
178 | .nfs*
179 |
180 | #================== Windows.gitignore ==================
181 | # Windows thumbnail cache files
182 | Thumbs.db
183 | Thumbs.db:encryptable
184 | ehthumbs.db
185 | ehthumbs_vista.db
186 |
187 | # Dump file
188 | *.stackdump
189 |
190 | # Folder config file
191 | [Dd]esktop.ini
192 |
193 | # Recycle Bin used on file shares
194 | $RECYCLE.BIN/
195 |
196 | # Windows Installer files
197 | *.cab
198 | *.msi
199 | *.msix
200 | *.msm
201 | *.msp
202 |
203 | # Windows shortcuts
204 | *.lnk
205 |
206 | #================== Vim.gitignore ==================
207 | # Swap
208 | [._]*.s[a-v][a-z]
209 | !*.svg # comment out if you don't need vector files
210 | [._]*.sw[a-p]
211 | [._]s[a-rt-v][a-z]
212 | [._]ss[a-gi-z]
213 | [._]sw[a-p]
214 |
215 | # Session
216 | Session.vim
217 | Sessionx.vim
218 |
219 | # Temporary
220 | .netrwhist
221 | *~
222 | # Auto-generated tag files
223 | tags
224 | # Persistent undo
225 | [._]*.un~
226 |
227 | #================== Vim.gitignore ==================
228 | .vscode/*
229 | !.vscode/settings.json
230 | !.vscode/tasks.json
231 | !.vscode/launch.json
232 | !.vscode/extensions.json
233 | !.vscode/*.code-snippets
234 |
235 | # Local History for Visual Studio Code
236 | .history/
237 |
238 | # Built Visual Studio Code Extensions
239 | *.vsix
--------------------------------------------------------------------------------
/app/src/main/java/template/ThumbnailImage.java:
--------------------------------------------------------------------------------
1 | package template;
2 |
3 | import android.content.ContentResolver;
4 | import android.content.Context;
5 | import android.database.Cursor;
6 | import android.graphics.Bitmap;
7 | import android.graphics.BitmapFactory;
8 | import android.net.Uri;
9 | import android.os.AsyncTask;
10 | import android.provider.MediaStore;
11 | import android.util.Base64;
12 | import android.widget.ImageView;
13 |
14 | import androidx.fragment.app.Fragment;
15 |
16 | import java.io.ByteArrayOutputStream;
17 | import java.io.File;
18 |
19 | public class ThumbnailImage extends Fragment {
20 |
21 | private Context mContext;
22 | ContentResolver cr;
23 | private ImageView imageView;
24 |
25 | @Override
26 | public void onAttach(Context context) {
27 | super.onAttach(context);
28 | this.mContext = context;
29 | cr = mContext.getContentResolver();
30 | imageView = null;
31 | }
32 |
33 | //测试获取缩略图
34 | public void test() {
35 | File file = new File("");
36 | String path = file.getAbsolutePath();
37 | //1、根据文件路径获取缩略图的id
38 | if (isPhoto(path)) {
39 | long id = getMediaId(cr, MediaStore.Images.Media.EXTERNAL_CONTENT_URI, path);
40 |
41 | LoadThumbnailsAsyncTask ltat = new LoadThumbnailsAsyncTask(cr);
42 | ltat.execute(imageView, id, 1);
43 | } else if (isVideo(path)) {
44 | long id = getMediaId(cr, MediaStore.Video.Media.EXTERNAL_CONTENT_URI, path);
45 |
46 | LoadThumbnailsAsyncTask ltat = new LoadThumbnailsAsyncTask(cr);
47 | ltat.execute(imageView, id, 2);
48 | }
49 | }
50 |
51 | private static final String WHERE = MediaStore.MediaColumns.DATA + "=?";//文件的绝对路径
52 | private static final String[] COLUMNS = new String[]{MediaStore.MediaColumns._ID};//图片id
53 |
54 | private static long getMediaId(ContentResolver cr, Uri content_uri, String path) {
55 | Cursor cursor = cr.query(content_uri, COLUMNS, WHERE, new String[]{path}, null);
56 | if (cursor.moveToFirst()) {
57 | long id = cursor.getLong(0);
58 | cursor.close();
59 | return id;
60 | }
61 |
62 | return -1;
63 | }
64 |
65 | public boolean isPhoto(String path) {
66 | return path.endsWith(".png");
67 | }
68 |
69 | public boolean isVideo(String path) {
70 | return path.endsWith(".mp4");
71 | }
72 |
73 | //异步获取缩略图
74 | static class LoadThumbnailsAsyncTask extends AsyncTask {
75 | private ImageView imageView;
76 | ContentResolver cr;
77 |
78 | public LoadThumbnailsAsyncTask(ContentResolver cr) {
79 | this.cr = cr;
80 | }
81 |
82 | @Override
83 | protected Bitmap doInBackground(Object... params) {
84 | //这是在后台子线程中执行的
85 | imageView = (ImageView) params[0];
86 | int id = (int) params[1];
87 | int type = (int) params[2];
88 | Bitmap bitmap = null;
89 | //2、根据缩略图id获取缩略图
90 | if (1 == type) {
91 | bitmap = MediaStore.Images.Thumbnails.getThumbnail(cr, id, MediaStore.Images.Thumbnails.MINI_KIND, null);
92 | } else if (2 == type) {
93 | bitmap = MediaStore.Video.Thumbnails.getThumbnail(cr, id, MediaStore.Video.Thumbnails.MINI_KIND, null);
94 | }
95 | return bitmap;
96 | }
97 |
98 | @Override
99 | protected void onPostExecute(Bitmap bitmap) {
100 | super.onPostExecute(bitmap);
101 | //当任务执行完成是调用,在UI线程
102 | //取消后这里不会执行
103 | imageView.setImageBitmap(bitmap);
104 | imageView.setTag(null);
105 | imageView = null;
106 | }
107 |
108 | @Override
109 | protected void onCancelled() {
110 | super.onCancelled();
111 | imageView = null;
112 | }
113 |
114 | @Override
115 | protected void onCancelled(Bitmap bitmap) {
116 | super.onCancelled(bitmap);
117 | imageView = null;
118 | }
119 | }
120 |
121 | //根据base64图片创建缩略图
122 | public static void createThumbImage(Context context, String base64) {
123 | byte[] decode = Base64.decode(base64.getBytes(), Base64.DEFAULT);
124 | //缩略图
125 | if (decode.length > 32 * 1024) {
126 | Bitmap bmp = BitmapFactory.decodeByteArray(decode, 0, decode.length);
127 | int width = bmp.getWidth();
128 | int height = bmp.getHeight();
129 | Bitmap thumbBmp = null;
130 | int baseLength = 150;
131 | if (width > height) {
132 | thumbBmp = Bitmap.createScaledBitmap(bmp, baseLength, bmp.getHeight() / (bmp.getWidth() / baseLength), true);
133 | } else {
134 | thumbBmp = Bitmap.createScaledBitmap(bmp, bmp.getWidth() / (bmp.getHeight() / baseLength), baseLength, true);
135 | }
136 | bmp.recycle();
137 |
138 | //缩略图转成字节数组
139 | ByteArrayOutputStream output = new ByteArrayOutputStream();
140 | thumbBmp.compress(Bitmap.CompressFormat.PNG, 100, output);
141 | thumbBmp.recycle();
142 | byte[] result = output.toByteArray();
143 | try {
144 | output.close();
145 | } catch (Exception e) {
146 | e.printStackTrace();
147 | }
148 | }
149 | }
150 | }
151 |
--------------------------------------------------------------------------------
/app/src/main/java/template/FloatDragBtnActivity.java:
--------------------------------------------------------------------------------
1 | package template;
2 |
3 | import android.annotation.SuppressLint;
4 | import android.content.res.Resources;
5 | import android.graphics.Color;
6 | import android.os.Bundle;
7 | import android.util.Log;
8 | import android.view.MotionEvent;
9 | import android.view.View;
10 | import android.view.ViewGroup;
11 | import android.widget.TextView;
12 |
13 | import androidx.appcompat.app.AppCompatActivity;
14 |
15 | import min.test.android_app_template.R;
16 |
17 | public class FloatDragBtnActivity extends AppCompatActivity {
18 |
19 | public static final String TAG = "FloatDragBtnActivity";
20 | private static final int STILLNESS = 24;
21 |
22 | @SuppressLint("ClickableViewAccessibility, InflateParams")
23 | @Override
24 | protected void onCreate(Bundle savedInstanceState) {
25 | super.onCreate(savedInstanceState);
26 |
27 | //以下为全部悬浮拖动按钮内容,使用的是setOnTouchListener,而非继承类
28 | View textView = getLayoutInflater().inflate(R.layout.float_drag_btn, null);
29 | textView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
30 | textView.setOnClickListener(v -> {
31 | Log.e(TAG, "onCreate: ");
32 | ((TextView)v).setTextColor(Color.GREEN);
33 | });
34 | textView.setY(900);
35 | textView.setX(Resources.getSystem().getDisplayMetrics().widthPixels - 200);
36 | textView.setOnTouchListener(new View.OnTouchListener() {
37 | private int touchX = 0;
38 | private int touchY = 0;
39 | private int beginX = 0;
40 | private int beginY = 0;
41 | private int w = 0;
42 | private int h = 0;
43 | private int dx = 0;
44 | private int dy = 0;
45 | private int parentW = 0;
46 | private int parentH = 0;
47 | private int navigationBarH = 0;
48 | private int statusBarH = 0;
49 |
50 | @SuppressLint("InternalInsetResource")
51 | @Override
52 | public boolean onTouch(View v, MotionEvent event) {
53 | switch (event.getAction()) {
54 | case MotionEvent.ACTION_DOWN:
55 | Resources resources = v.getContext().getResources();
56 | int resourceId = resources.getIdentifier("navigation_bar_height", "dimen", "android");
57 | navigationBarH = getResources().getDimensionPixelSize(resourceId);
58 | Log.e(TAG, "onTouch: navigation_bar_height " + navigationBarH);
59 | resourceId = resources.getIdentifier("status_bar_height", "dimen", "android");
60 | statusBarH = getResources().getDimensionPixelSize(resourceId);
61 | Log.e(TAG, "onTouch: status_bar_height " + statusBarH);
62 | w = v.getWidth();
63 | h = v.getHeight();
64 | View view = (View) v.getParent();
65 | parentW = view.getWidth();
66 | parentH = view.getHeight();
67 | v.setPressed(true);
68 | touchX = (int) v.getX();
69 | touchY = (int) v.getY();
70 | beginX = touchX;
71 | beginY = touchY;
72 | // 点击事件起始位置到原点的距离
73 | dx = (int) (event.getRawX() - beginX);
74 | dy = (int) (event.getRawY() - beginY);
75 | break;
76 | case MotionEvent.ACTION_MOVE:
77 | touchX = (int)event.getRawX();// x轴拖动的绝对距离
78 | touchY = (int)event.getRawY();// y轴拖动的绝对距离
79 | touchX -= dx;
80 | touchY -= dy;
81 | if (Math.abs(touchX - beginX) < STILLNESS && Math.abs(touchY - beginY) < STILLNESS) {
82 | break;
83 | }
84 | if (touchX < 0) {
85 | touchX = 0;
86 | }
87 | if (touchY < statusBarH) {
88 | touchY = statusBarH;
89 | }
90 | if (touchX + w > parentW) {
91 | touchX = parentW - w;
92 | }
93 | if (touchY + h > parentH - navigationBarH) {
94 | touchY = parentH - h - navigationBarH;
95 | }
96 | v.setX(touchX);
97 | v.setY(touchY);
98 | break;
99 | case MotionEvent.ACTION_UP:
100 | Log.e(TAG, "onTouch: ACTION_UP " + Math.abs(touchX - beginX) + ", " + Math.abs(touchY - beginY));
101 | // 以下5行代码必须这个么写,先后顺序不能颠倒,否则无法触发 Click 事件
102 | if (Math.abs(touchX - beginX) < STILLNESS && Math.abs(touchY - beginY) < STILLNESS) {
103 | v.onTouchEvent(event);
104 | }
105 | v.setPressed(false);
106 | return true;
107 | default: break;
108 | }
109 | return false;
110 | }
111 | });
112 |
113 | ((ViewGroup)(getWindow().getDecorView())).addView(textView);
114 | }
115 | }
--------------------------------------------------------------------------------
/app/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
14 |
15 |
16 |
32 |
33 |
47 |
48 |
55 |
56 |
59 |
63 |
64 |
87 |
88 |
99 |
100 |
105 |
106 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/ic_launcher_background.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
10 |
15 |
20 |
25 |
30 |
35 |
40 |
45 |
50 |
55 |
60 |
65 |
70 |
75 |
80 |
85 |
90 |
95 |
100 |
105 |
110 |
115 |
120 |
125 |
130 |
135 |
140 |
145 |
150 |
155 |
160 |
165 |
170 |
171 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env sh
2 |
3 | #
4 | # Copyright 2015 the original author or authors.
5 | #
6 | # Licensed under the Apache License, Version 2.0 (the "License");
7 | # you may not use this file except in compliance with the License.
8 | # You may obtain a copy of the License at
9 | #
10 | # https://www.apache.org/licenses/LICENSE-2.0
11 | #
12 | # Unless required by applicable law or agreed to in writing, software
13 | # distributed under the License is distributed on an "AS IS" BASIS,
14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | # See the License for the specific language governing permissions and
16 | # limitations under the License.
17 | #
18 |
19 | ##############################################################################
20 | ##
21 | ## Gradle start up script for UN*X
22 | ##
23 | ##############################################################################
24 |
25 | # Attempt to set APP_HOME
26 | # Resolve links: $0 may be a link
27 | PRG="$0"
28 | # Need this for relative symlinks.
29 | while [ -h "$PRG" ] ; do
30 | ls=`ls -ld "$PRG"`
31 | link=`expr "$ls" : '.*-> \(.*\)$'`
32 | if expr "$link" : '/.*' > /dev/null; then
33 | PRG="$link"
34 | else
35 | PRG=`dirname "$PRG"`"/$link"
36 | fi
37 | done
38 | SAVED="`pwd`"
39 | cd "`dirname \"$PRG\"`/" >/dev/null
40 | APP_HOME="`pwd -P`"
41 | cd "$SAVED" >/dev/null
42 |
43 | APP_NAME="Gradle"
44 | APP_BASE_NAME=`basename "$0"`
45 |
46 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
47 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
48 |
49 | # Use the maximum available, or set MAX_FD != -1 to use that value.
50 | MAX_FD="maximum"
51 |
52 | warn () {
53 | echo "$*"
54 | }
55 |
56 | die () {
57 | echo
58 | echo "$*"
59 | echo
60 | exit 1
61 | }
62 |
63 | # OS specific support (must be 'true' or 'false').
64 | cygwin=false
65 | msys=false
66 | darwin=false
67 | nonstop=false
68 | case "`uname`" in
69 | CYGWIN* )
70 | cygwin=true
71 | ;;
72 | Darwin* )
73 | darwin=true
74 | ;;
75 | MINGW* )
76 | msys=true
77 | ;;
78 | NONSTOP* )
79 | nonstop=true
80 | ;;
81 | esac
82 |
83 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
84 |
85 |
86 | # Determine the Java command to use to start the JVM.
87 | if [ -n "$JAVA_HOME" ] ; then
88 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
89 | # IBM's JDK on AIX uses strange locations for the executables
90 | JAVACMD="$JAVA_HOME/jre/sh/java"
91 | else
92 | JAVACMD="$JAVA_HOME/bin/java"
93 | fi
94 | if [ ! -x "$JAVACMD" ] ; then
95 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
96 |
97 | Please set the JAVA_HOME variable in your environment to match the
98 | location of your Java installation."
99 | fi
100 | else
101 | JAVACMD="java"
102 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
103 |
104 | Please set the JAVA_HOME variable in your environment to match the
105 | location of your Java installation."
106 | fi
107 |
108 | # Increase the maximum file descriptors if we can.
109 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
110 | MAX_FD_LIMIT=`ulimit -H -n`
111 | if [ $? -eq 0 ] ; then
112 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
113 | MAX_FD="$MAX_FD_LIMIT"
114 | fi
115 | ulimit -n $MAX_FD
116 | if [ $? -ne 0 ] ; then
117 | warn "Could not set maximum file descriptor limit: $MAX_FD"
118 | fi
119 | else
120 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
121 | fi
122 | fi
123 |
124 | # For Darwin, add options to specify how the application appears in the dock
125 | if $darwin; then
126 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
127 | fi
128 |
129 | # For Cygwin or MSYS, switch paths to Windows format before running java
130 | if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then
131 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
132 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
133 |
134 | JAVACMD=`cygpath --unix "$JAVACMD"`
135 |
136 | # We build the pattern for arguments to be converted via cygpath
137 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
138 | SEP=""
139 | for dir in $ROOTDIRSRAW ; do
140 | ROOTDIRS="$ROOTDIRS$SEP$dir"
141 | SEP="|"
142 | done
143 | OURCYGPATTERN="(^($ROOTDIRS))"
144 | # Add a user-defined pattern to the cygpath arguments
145 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
146 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
147 | fi
148 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
149 | i=0
150 | for arg in "$@" ; do
151 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
152 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
153 |
154 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
155 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
156 | else
157 | eval `echo args$i`="\"$arg\""
158 | fi
159 | i=`expr $i + 1`
160 | done
161 | case $i in
162 | 0) set -- ;;
163 | 1) set -- "$args0" ;;
164 | 2) set -- "$args0" "$args1" ;;
165 | 3) set -- "$args0" "$args1" "$args2" ;;
166 | 4) set -- "$args0" "$args1" "$args2" "$args3" ;;
167 | 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
168 | 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
169 | 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
170 | 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
171 | 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
172 | esac
173 | fi
174 |
175 | # Escape application args
176 | save () {
177 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
178 | echo " "
179 | }
180 | APP_ARGS=`save "$@"`
181 |
182 | # Collect all arguments for the java command, following the shell quoting and substitution rules
183 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
184 |
185 | exec "$JAVACMD" "$@"
186 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Android_App_Template
2 | [国内链接gitee](https://gitee.com/maoxm/Android_App_Template)
3 | 安卓App工具类和模板代码,工具类一般可以直接使用,模板类主要用来参考,引入到自己的项目时可能会报错,请自行修改。
4 | 开发安卓前,请去了解 Jetpack 和 Hilt ,能使你的开发方便很多。
5 |
6 | ## [工具类,在“/app/src/main/java/utils/”目录下](/app/src/main/java/utils)
7 | 1. [获取全局Context的工具类,无须传入Context;get_context_no_dependence_anything/](/app/src/main/java/utils/get_context_no_dependence_anything)
8 | 2. [Utils工具;Utils.java](/app/src/main/java/utils/Utils.java)
9 | 包含:获取MIME类型、判断字符串是否为IP地址(模板)、分享到第三方(不用集成第三方SDK)、WiFi连接判断、获取其他语言的字符串、HarmonyOS判断、HarmonyOS系统版本号获取、判断activity是否正在显示
10 | 3. [AES加解密,字节数组与16进制字符串互转;aes/](/app/src/main/java/utils/encryption/aes)、[Android 加密工具](https://developer.android.google.cn/guide/topics/security/cryptography)、[Android 密钥库系统](https://developer.android.google.cn/training/articles/keystore)
11 | 4. [App启动icon不显示在 Launcher 上的方法:在启动 Activity 的 intent-filter 中加点料](/app/src/main/AndroidManifest.xml)
12 | 5. [获取视频文件的第一帧,远程或本地视频都可](/app/src/main/java/utils/Utils.java#L309)
13 | 6. [判断谷歌Play商店是否安装](/app/src/main/java/utils/Utils.java#L349)
14 |
15 | ## [模板,在“/app/src/main/java/template/”目录下](/app/src/main/java/template)
16 | 1. [RecyclerView分组的模板代码;recyclerview_group/](/app/src/main/java/template/recyclerview_group)
17 | 2. [自定义HUD指示器模板代码,改造AlertDialog,可以禁止用户交互和允许用户交互;ProgressHUD.java](/app/src/main/java/template/ProgressHUD.java)
18 | 3. [获取本地图片或视频的缩略图;ThumbnailImage.java](/app/src/main/java/template/ThumbnailImage.java)
19 | 4. [安卓8.0官方BottomNavigationView使用的问题;BottomNavigationFragment.java](/app/src/main/java/template/BottomNavigationFragment.java)
20 | 5. [Fragment的壳Activity,主要是想App就用这一个Activity就够了,其他的都用Fragment;fragment_activity/](/app/src/main/java/template/fragment_activity)
21 | 6. [使用系统的文件多选,文件夹(目录)选择器;FileMultipleSelectionFragment.java,已过时,最新方法请参考第32条](/app/src/main/java/template/FileMultipleSelectionFragment.java)
22 | 7. [自定义改造Toast;ToastUtils.java](/app/src/main/java/template/ToastUtils.java)
23 | 8. [Okhttp3上传或者下载文件的模板;OkHttp3UploadDownload.java](/app/src/main/java/template/OkHttp3UploadDownload.java)
24 | 9. [WebView常用设置, 文件选择适配;WebViewActivity.java](/app/src/main/java/template/WebViewActivity.java)
25 | 10. [UDP模板;UDP.java](/app/src/main/java/template/UDP.java)
26 | 11. [给RecyclerView的Item添加上下文菜单(ContextMenu)和点击事件(onClick)模板,极简;RecyclerViewItem.java](/app/src/main/java/template/RecyclerViewItem.java)
27 | 12. [获取外置SD卡(TF卡)的绝对路径;SdcardFragment.java](/app/src/main/java/template/SdcardFragment.java)
28 | 13. [修改AlertDialog的主题;AlertDialogTheme.java](/app/src/main/java/template/AlertDialogTheme.java)、[R.style.AlertDialog](/app/src/main/res/values/styles.xml)
29 | 14. [仿iOS的弹出框,但API和AlertDialog.Builder一致;AlertDialogTheme.java#Builder](/app/src/main/java/template/AlertDialogTheme.java)、[R.style.AlertDialogTheme](/app/src/main/res/values/styles.xml)
30 | 15. [使用DownloadManager下载APK,并且安装;DownloadUtils.java](/app/src/main/java/template/DownloadUtils.java)、[FileProvider](/app/src/main/res/xml/share_dir.xml)
31 | 16. [BottomSheetDialog去掉背景,方便自定义圆角等;BottomSheetDialogTheme.java](/app/src/main/java/template/BottomSheetDialogTheme.java)、[R.style.BottomSheetBgNullTheme](/app/src/main/res/values/styles.xml)
32 | 17. [仿iOS导航箭头图标,用的矢量图(vector),去掉了系统创建vector的多余的空白;](/app/src/main/res/drawable)[R.drawable.v_back](/app/src/main/res/drawable/v_back.xml)、[R.drawable.v_next](/app/src/main/res/drawable/v_next.xml)
33 | 18. [单击时间间隔控制,使用的是聚合模式,而不是abstract类;SingleClickController.java](/app/src/main/java/template/SingleClickController.java)
34 | 19. [多击(谷歌工程师写的),使用的是聚合模式;MultipleClicksController.java](/app/src/main/java/template/MultipleClicksController.java)
35 | 20. [系统日历事件提醒增删和系统闹钟增删;CalendarAndAlarmClock.java](/app/src/main/java/template/CalendarAndAlarmClock.java)
36 | 21. [透明状态栏,App顶部栏与状态栏(StatusBar)颜色一体化,沉浸(jin)式状态栏;R.style.TranslucentBarTheme](/app/src/main/res/values/styles.xml)、[API>=30透明状态栏,及延长启动页(可当广告页)时间;TranslucentBarActivity.java](/app/src/main/java/template/TranslucentBarActivity.java)
37 | 22. [最简、最省存储的启动页设置;R.style.LauncherTheme](/app/src/main/res/values/styles.xml)
38 | 23. [获取WiFi列表,获取当前链接的WiFi名称,API>=29连接WiFi,扫描WiFi和蓝牙等外设的建议;WiFiActivity.java](/app/src/main/java/template/WiFiActivity.java)
39 | 24. [图片创建缩略图;ThumbnailImage.java#createThumbImage](/app/src/main/java/template/ThumbnailImage.java)
40 | 25. [文字转语音(TTS);UtilTemplates.java#speak](/app/src/main/java/template/UtilTemplates.java#L67)
41 | 26. [获取对应 density 下的原图;UtilTemplates.java#getNoScaledImage](/app/src/main/java/template/UtilTemplates.java#L105)
42 | 27. [获取剪切板的内容;UtilTemplates.java#getClipboardText](/app/src/main/java/template/UtilTemplates.java#L114)
43 | 28. [获取指定文件夹大小;UtilTemplates.java#getDirSize](/app/src/main/java/template/UtilTemplates.java#L138)
44 | 29. [获取存储可用空间大小;UtilTemplates.java#getAvailableSpace](/app/src/main/java/template/UtilTemplates.java#L163)
45 | 30. [各种自建证书加载;UtilTemplates.java#getSSLSocketFactory](/app/src/main/java/template/UtilTemplates.java#L248)
46 | 31. [自定义悬浮可拖动按钮;FloatDragBtnActivity.java](/app/src/main/java/template/FloatDragBtnActivity.java)
47 | 32. [安卓自带图片选择器的正确打开方式;ImagePickActivity.java](/app/src/main/java/template/ImagePickActivity.java)
48 | 33. [EditText输入限制;UtilTemplates.java#editTextLimiter](/app/src/main/java/template/UtilTemplates.java#L378)
49 | 34. [把本地 aar 文件发布到本地 maven 源,可以像远程 maven 库一样引入](/publishingTemp/build.gradle.kts)
50 | 35. [keystore文件的指纹计算方法](/app/src/main/java/template/FingerprintUtils.java)
51 | 36. [RxJava3使用](/app/src/main/java/template/RxJava3Templates.java)
52 | 37. [创建一种不在主线程工作的 Handler,子线程 Handler,非主线程 Handler](/app/src/main/java/template/UtilTemplates.java#L481)
53 | 38. [Java Optional类的用法](/app/src/main/java/template/UtilTemplates.java#L493)
54 | 39. [自定义弹框 PopupWindow ](/app/src/main/java/template/UtilTemplates.java#L537)
55 | 40. [TabLayout + ViewPager2 使用](/app/src/main/java/template/UtilTemplates.java#L551)
56 | 41. [圆环倒计时动画](/app/src/main/java/template/CircleProgressView.java)
57 |
58 |
59 | ## 长见识(自己去搜,去了解,去使用)
60 | 1. 并发:ReentrantLock CountDownLatch CyclicBarrier Phaser ReadWriteLock StampedLock Semaphore Exchanger LockSupport Condition
61 | 2. App内部角标 BadgeDrawable;MediaSession 框架
62 | 3. AndroidUtilCode 非常好的工具类,有些功能不知道怎么实现可以参考,Github上能搜到
63 | 4. WifiManager.WifiLock 的 WIFI_MODE_FULL_HIGH_PERF 模式可以防止WiFi在息屏时休眠
64 | 5. HTTP上传文件的断点续传协议可参考(苹果公司为其NSURLSession上传文件定制的):https://datatracker.ietf.org/doc/draft-ietf-httpbis-resumable-upload/
65 | 6. Android 官方性能监控和检测,也介绍了要引入的库[https://developer.android.google.cn/topic/performance/inspecting-overview?hl=zh-cn](https://developer.android.google.cn/topic/performance/inspecting-overview?hl=zh-cn)
66 | 7. 自定义指定 JDK Home 路径可以在项目根目录的[gradle.properties](gradle.properties)中添加 org.gradle.java.home 参数
67 | 8. 第三方依赖下载加速,阿里云 Maven 仓库镜像介绍:[https://developer.aliyun.com/mvn/guide](https://developer.aliyun.com/mvn/guide)。 有些源没有及时同步国外的源,导致有些库文件还是会从国外源下载,所以多配几个国内源,降低这种概率,说不定总有一个源及时同步了。建议用 Android Studio 内的按钮去同步下载第三方库,不要用 gradlew build 等命令去同步下载第三方库,因为奇怪的JDK环境可能导致一些奇奇怪怪的问题导致同步失败。第一次同步最好打开 Android Studio 的 build 视图,查看 Download info,及时发现哪些库会最终使用国外源,可及时打开代理或者VPN等。
68 | 9. gradle 下载加速,腾讯云 gradle 下载地址,按需更新链接中的版本号即可:[https://mirrors.cloud.tencent.com/gradle/gradle-7.6.3-all.zip](https://mirrors.cloud.tencent.com/gradle/gradle-7.6.3-all.zip) 。必须使用"-all.zip"文件,否则项目同步还是会下载 gradle 的 src 依赖
--------------------------------------------------------------------------------
/app/src/main/java/template/ImagePickActivity.java:
--------------------------------------------------------------------------------
1 | package template;
2 |
3 | import android.content.Intent;
4 | import android.net.Uri;
5 | import android.os.Bundle;
6 | import android.provider.MediaStore;
7 |
8 | import androidx.activity.result.ActivityResult;
9 | import androidx.activity.result.ActivityResultCallback;
10 | import androidx.activity.result.ActivityResultLauncher;
11 | import androidx.activity.result.PickVisualMediaRequest;
12 | import androidx.activity.result.contract.ActivityResultContracts;
13 | import androidx.appcompat.app.AppCompatActivity;
14 |
15 | import java.util.List;
16 |
17 | public class ImagePickActivity extends AppCompatActivity {
18 |
19 | // registerForActivityResult 可以在构造的时候调用
20 | private ActivityResultLauncher lip = registerForActivityResult(new ActivityResultContracts.GetContent(), new ActivityResultCallback() {
21 | @Override
22 | public void onActivityResult(Uri result) {
23 | // 这里拿到的是 文件的uri
24 | // 这种方式读取数据是不需要 Manifest.permission.READ_EXTERNAL_STORAGE 权限
25 | // getContentResolver().openInputStream(result);
26 | }
27 | });
28 |
29 | // 把文件写到沙盒之外时用的路径选择器,选择器中还可以编辑指定文件名。调用方法:fileExporter.launch("默认的文件名.json")
30 | final ActivityResultLauncher fileExporter = registerForActivityResult(
31 | new ActivityResultContracts.CreateDocument("application/json"), uri -> {
32 | if (uri != null) { // 返回文件完整路径
33 | }
34 | });
35 |
36 | @Override
37 | protected void onCreate(Bundle savedInstanceState) {
38 | super.onCreate(savedInstanceState);
39 |
40 | // 方式1,这种直接打开的文件选择器,但是经过了 "image/*" 过滤:
41 | ActivityResultLauncher imagePickLauncher1 = registerForActivityResult(new ActivityResultContracts.GetContent(), new ActivityResultCallback() {
42 | @Override
43 | public void onActivityResult(Uri result) {
44 | // 这里拿到的是 文件的uri
45 | // 这种方式读取数据是不需要 Manifest.permission.READ_EXTERNAL_STORAGE 权限
46 | // getContentResolver().openInputStream(result);
47 | }
48 | });
49 | // 使用
50 | imagePickLauncher1.launch("image/*");
51 |
52 | // 方式2,这种方式会有图片选择器或文件选择器两种方式弹窗提供选择:
53 | ActivityResultLauncher imagePickLauncher2 = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback() {
54 | @Override
55 | public void onActivityResult(ActivityResult result) {
56 | if (null == result || result.getResultCode() != RESULT_OK || result.getData() == null || result.getData().getData() == null) return;
57 | // 这种方式读取数据是不需要 Manifest.permission.READ_EXTERNAL_STORAGE 权限
58 | // getContentResolver().openInputStream(result.getData().getData());
59 | }
60 | });
61 | // 使用
62 | imagePickLauncher2.launch(new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI));
63 | // 这个应该是拍照,还有一些别的参数要设置,另外研究吧
64 | // imagePickLauncher2.launch(new Intent(MediaStore.ACTION_IMAGE_CAPTURE));
65 |
66 | /*
67 | 方式3:必须是API 33 (安卓13),才能使用
68 | https://developer.android.google.cn/about/versions/13/features/photopicker?hl=zh-cn
69 | */
70 | ActivityResultLauncher imagePickLauncher3 = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> {
71 | if (null == result || result.getResultCode() != RESULT_OK || result.getData() == null || result.getData().getData() == null) return;
72 | // 这种方式读取数据是不需要 Manifest.permission.READ_EXTERNAL_STORAGE 权限
73 | // getContentResolver().openInputStream(result.getData().getData());
74 | });
75 | // 使用
76 | Intent intent = new Intent(MediaStore.ACTION_PICK_IMAGES);
77 | // 默认图片视频都可选,这里可以自己过滤
78 | intent.setType("image/*");
79 | // intent.setType("video/*");
80 | imagePickLauncher3.launch(intent);
81 |
82 | /*
83 | 方式4:
84 | 搭载 Android 11(API 级别 30)或更高版本 1.7.0 版或更高版本的 androidx.activity 库
85 | https://developer.android.google.cn/training/data-storage/shared/photopicker?hl=zh-cn
86 | def activity_version = "1.7.0"
87 | // Java language implementation
88 | implementation "androidx.activity:activity:$activity_version"
89 | // Kotlin
90 | implementation "androidx.activity:activity-ktx:$activity_version"
91 | */
92 | // 选择单个媒体文件
93 | ActivityResultLauncher imagePickLauncher4 = registerForActivityResult(new ActivityResultContracts.PickVisualMedia(), new ActivityResultCallback() {
94 | @Override
95 | public void onActivityResult(Uri result) {
96 | // 这里拿到的是 图片的uri
97 | // 这种方式读取数据是不需要 Manifest.permission.READ_EXTERNAL_STORAGE 权限
98 | // getContentResolver().openInputStream(result);
99 | // 默认情况下,系统会授予应用对媒体文件的访问权限,直到设备重启或应用停止运行。如果您的应用执行长时间运行的工作(例如在后台上传大型文件),您可能需要将此访问权限保留更长时间。为此,请调用
100 | getContentResolver().takePersistableUriPermission(result, Intent.FLAG_GRANT_READ_URI_PERMISSION);
101 | }
102 | });
103 | // 使用
104 | // 只视频
105 | // new PickVisualMediaRequest.Builder().setMediaType(ActivityResultContracts.PickVisualMedia.VideoOnly.INSTANCE).build();
106 | // 默认是图片和视频都包含
107 | imagePickLauncher4.launch(new PickVisualMediaRequest.Builder().build());
108 |
109 | // 选择多个媒体项,maxItems为最大可选数量。最大数量查询 MediaStore.getPickImagesMaxLimit()
110 | ActivityResultLauncher imagePickLauncher6 = registerForActivityResult(new ActivityResultContracts.PickMultipleVisualMedia(9), new ActivityResultCallback>() {
111 | @Override
112 | public void onActivityResult(List result) {
113 | // 这里拿到的是 图片的uri
114 | // 这种方式读取数据是不需要 Manifest.permission.READ_EXTERNAL_STORAGE 权限
115 | // getContentResolver().openInputStream(result);
116 | }
117 | });
118 | // 使用
119 | imagePickLauncher6.launch(new PickVisualMediaRequest.Builder().build());
120 |
121 | // 方式5: 此方式可以指定多个文件类型
122 | ActivityResultLauncher imagePickLauncher5 = registerForActivityResult(new ActivityResultContracts.OpenDocument(), new ActivityResultCallback() {
123 | @Override
124 | public void onActivityResult(Uri result) {
125 | // 这里拿到的是 文件的uri
126 | // 这种方式读取数据是不需要 Manifest.permission.READ_EXTERNAL_STORAGE 权限
127 | // getContentResolver().openInputStream(result);
128 | }
129 | });
130 | // 使用
131 | imagePickLauncher5.launch(new String[]{"image/*", "video/*", ""});
132 |
133 | // 方式6: 选择多个文件
134 | ActivityResultLauncher imagePickLauncher7 = registerForActivityResult(new ActivityResultContracts.OpenMultipleDocuments(), new ActivityResultCallback>() {
135 | @Override
136 | public void onActivityResult(List list) {
137 | }
138 | });
139 | // 使用
140 | imagePickLauncher7.launch(new String[]{"image/*", "video/*", ""});
141 |
142 | // 还有很多好用的可以自己去发觉
143 | }
144 | }
--------------------------------------------------------------------------------
/app/src/main/java/template/TranslucentBarActivity.java:
--------------------------------------------------------------------------------
1 | package template;
2 |
3 | import android.animation.Animator;
4 | import android.animation.AnimatorListenerAdapter;
5 | import android.animation.ObjectAnimator;
6 | import android.os.Build;
7 | import android.os.Bundle;
8 | import android.os.Handler;
9 | import android.os.Looper;
10 | import android.view.View;
11 | import android.view.ViewGroup;
12 | import android.view.Window;
13 | import android.widget.ImageView;
14 |
15 | import androidx.appcompat.app.AppCompatActivity;
16 | import androidx.core.graphics.Insets;
17 | import androidx.core.view.ViewCompat;
18 | import androidx.core.view.WindowCompat;
19 | import androidx.core.view.WindowInsetsCompat;
20 |
21 | import min.test.android_app_template.R;
22 |
23 | public class TranslucentBarActivity extends AppCompatActivity {
24 |
25 | //R.style.LauncherTheme、R.style.TranslucentBarTheme 这两个里面的介绍很重要
26 | @Override
27 | protected void onCreate(Bundle savedInstanceState) {
28 | super.onCreate(savedInstanceState);
29 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
30 | Window window = getWindow();
31 | // 这个会把底部的导航栏的背面也用上,官方注释说可以与WindowInsets.Type.statusBars()等配合,但是没测试出来效果
32 | // window.setDecorFitsSystemWindows(false);
33 | WindowCompat.setDecorFitsSystemWindows(window, false);
34 | // 高亮显示状态栏,字体黑色
35 | // ViewCompat.getWindowInsetsController(window.getDecorView()).setAppearanceLightStatusBars(true);
36 | // 抬高底部方式一:
37 | ViewCompat.setOnApplyWindowInsetsListener(window.getDecorView().findViewById(android.R.id.content), (v, insets) -> {
38 | // displayCutout 是刘海区域
39 | Insets systemInsets = insets.getInsets(WindowInsetsCompat.Type.systemBars() | WindowInsetsCompat.Type.displayCutout());
40 | v.setPadding(0, 0, 0, systemInsets.bottom);
41 | // 将内容限制在安全区域内,window.getDecorView().findViewById(android.R.id.content) 可能要换成其子视图
42 | // v.setPadding(systemInsets.left, systemInsets.top, systemInsets.right, systemInsets.bottom);
43 | return insets;
44 | });
45 | // // 高亮显示状态栏,字体黑色
46 | // window.getDecorView().getWindowInsetsController().setSystemBarsAppearance(WindowInsetsController.APPEARANCE_LIGHT_STATUS_BARS, WindowInsetsController.APPEARANCE_LIGHT_STATUS_BARS);
47 | // // 抬高底部方式二:
48 | // // 貌似这样也能获取导航栏高度。Activity的初始创建显示线程内getInsets得到为null,可以放到runOnUiThread()中
49 | // ViewCompat.getRootWindowInsets(window.getDecorView().findViewById(android.R.id.content)).getInsets(WindowInsetsCompat.Type.navigationBars()).bottom;
50 | // // 获取导航栏高度
51 | // int resourceId = getResources().getIdentifier("navigation_bar_height", "dimen", "android");
52 | // if (0 != resourceId) {
53 | // int navigation_bar_height = getResources().getDimensionPixelSize(resourceId);
54 | // LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) window.getDecorView().findViewById(android.R.id.content).getLayoutParams();
55 | // // 防止底部被导航栏遮住
56 | // layoutParams.bottomMargin = navigation_bar_height;
57 | //// window.getDecorView().findViewById(android.R.id.content).setPadding(0, 0, 0, navigation_bar_height);
58 | // }
59 | } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
60 | getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
61 | }
62 | }
63 |
64 | private Handler handler;
65 | private View splashView;
66 | /**
67 | * 可当广告页
68 | * 在最上层view中加入一个和启动页一样的页面,假装延长启动页的显示时间,等资源加载完成后移除假的启动页:
69 | * 在主题中 有两种设置启动页的方式,选其一:
70 | * android:windowBackground 只能设置 图片资源 或 layer-list等图层的资源文件
71 | * android:windowSplashscreenContent (安卓8.0以上) 能设置 图片资源 或 layer-list等图层资源文件 或 layout
72 | */
73 | private void initSplash() {
74 | /**
75 | * 使用layout去匹配启动页,layout中的imageview的 底部margin 和 layer-list的图片item bottom的值一样
76 | * 当 android:windowSplashscreenContent 设置的是layout 时,layout加入 android.R.id.content 的view 或 DecorView中
77 | * 都一样,人眼看不出切换差异
78 | * 当 android:windowSplashscreenContent 设置的是layer-list等图层 或图片 时,layout加入 android.R.id.content 的view 或
79 | * DecorView 都会有底部导航栏的高度的切换差异感,下面会有去掉差异的方法
80 | * 当使用 android:windowBackground 做启动页时,layout加入 DecorView 无切换差异感,而加入 android.R.id.content 的view,
81 | * 有差异感
82 | */
83 | /*ViewGroup vg = (ViewGroup) getLayoutInflater().inflate(R.layout.launch_splash, null);
84 | splashView = vg;
85 | ((ViewGroup) getWindow().getDecorView().findViewById(android.R.id.content)).addView(vg);
86 | // ((ViewGroup) getWindow().getDecorView()).addView(vg);
87 | //去掉差异感
88 | int resourceId = getResources().getIdentifier("navigation_bar_height", "dimen", "android");
89 | if (resourceId != 0) {
90 | View iv = vg.getChildAt(0);
91 | RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) iv.getLayoutParams();
92 | lp.bottomMargin -= getResources().getDimensionPixelSize(resourceId);//+或-,请根据测试调,测试多次,否则可能有上次的缓存导致调试不准确
93 | }*/
94 |
95 | /**
96 | * android:windowBackground 和 android:windowSplashscreenContent 对图片的拉伸效果不一样
97 | * 当使用 android:windowBackground 作为启动页时,此ImageView适合添加到DecorView中,人眼看不出切换差异,适合全屏大图。
98 | * 但使用 android:windowSplashscreenContent 做启动页时,不要加入到DecorView,会有一个底部导航栏的差异,
99 | * 可以加入到 android.R.id.content 的view中,不会有底部导航栏的差异,人眼看不出切换差异,适合非全屏的小图
100 | * android:windowSplashscreenContent 与 android:windowBackground 不能同时存在,否则 以 android:windowSplashscreenContent
101 | * 为主
102 | */
103 | ImageView iv = new ImageView(this);
104 | ViewGroup.LayoutParams layoutParams = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
105 | iv.setLayoutParams(layoutParams);
106 | iv.setScaleType(ImageView.ScaleType.FIT_XY);
107 | splashView = iv;
108 | iv.setImageResource(R.drawable.launcher_splash);
109 | ((ViewGroup) getWindow().getDecorView()).addView(iv);
110 | // ((ViewGroup) getWindow().getDecorView().findViewById(android.R.id.content)).addView(iv);
111 | handler = new Handler(Looper.getMainLooper());
112 | handler.postDelayed(this::hideSplashView, 5000);
113 | }
114 |
115 | private AnimatorListenerAdapter animatorAdapter;
116 | //动画隐藏启动页
117 | private synchronized void hideSplashView() {
118 | if (splashView == null || null != animatorAdapter) return;
119 | animatorAdapter = new AnimatorListenerAdapter() {
120 | @Override
121 | public void onAnimationEnd(Animator animation) {
122 | super.onAnimationEnd(animation);
123 | ((ViewGroup)splashView.getParent()).removeView(splashView);
124 | splashView = null;
125 | animatorAdapter = null;
126 | }
127 | };
128 | ObjectAnimator animator = ObjectAnimator.ofFloat(splashView, "alpha", 1f, 0f);
129 | animator.setDuration(300);//时间
130 | animator.addListener(animatorAdapter);
131 | animator.start();
132 | // getWindow().getDecorView().setBackground(null);
133 | // getWindow().setBackgroundDrawable(null);
134 | }
135 | }
--------------------------------------------------------------------------------
/app/src/main/java/template/DownloadUtils.java:
--------------------------------------------------------------------------------
1 | package template;
2 |
3 | import android.annotation.SuppressLint;
4 | import android.app.DownloadManager;
5 | import android.content.BroadcastReceiver;
6 | import android.content.ContentUris;
7 | import android.content.ContentValues;
8 | import android.content.Context;
9 | import android.content.Intent;
10 | import android.content.IntentFilter;
11 | import android.database.Cursor;
12 | import android.net.Uri;
13 | import android.os.Build;
14 | import android.os.Environment;
15 |
16 | import androidx.core.content.FileProvider;
17 |
18 | import java.io.File;
19 |
20 | public class DownloadUtils {
21 | //下载器
22 | private DownloadManager dm;
23 | private Context mContext;
24 | //下载任务ID
25 | private long downloadId;
26 | private String mUrl;
27 | private File file;
28 |
29 | public static DownloadUtils du;
30 |
31 | public DownloadUtils(Context context, String url) {
32 | mContext = context;
33 | mUrl = url;
34 | }
35 |
36 | public static void downloadAPK(Context context, String url) {
37 | du = new DownloadUtils(context, url);
38 | du.downloadAPK();
39 | }
40 |
41 | //下载apk
42 | private void downloadAPK() {
43 | //创建下载请求
44 | DownloadManager.Request request = new DownloadManager.Request(Uri.parse(mUrl));
45 | //移动网络情况下是否允许漫游
46 | request.setAllowedOverRoaming(false);
47 | //在通知栏中显示,默认就是显示的
48 | request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE);
49 | //隐藏通知栏 manifest必须配置权限:android.permission.DOWNLOAD_WITHOUT_NOTIFICATION;
50 | // request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_HIDDEN);
51 | request.setTitle("正在下载最新APK");
52 | request.setDescription("my.apk");
53 | request.setVisibleInDownloadsUi(true);
54 |
55 | //设置下载的路径
56 | file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS),
57 | "my.apk");
58 | if (file.exists()) file.delete();
59 | //设置文件存放路径,路径必须是Context.getExternalFilesDir()目录下的,或Environment.getExternalStoragePublicDirectory()目录下的,否则不支持;还可能需要有Manifest.permission.WRITE_EXTERNAL_STORAGE,具体请看注释。
60 | request.setDestinationUri(Uri.fromFile(file));//Context.getExternalFilesDir(null),API29以上此目录下不需要读写权限
61 | //获取DownloadManager
62 | if (dm == null)
63 | dm = (DownloadManager) mContext.getSystemService(Context.DOWNLOAD_SERVICE);
64 | if (dm != null) {
65 | //将请求加入队列,加入后会给该任务返回id,通过该id可以取消任务、重启任务、获取下载的文件等等
66 | downloadId = dm.enqueue(request);
67 | }
68 |
69 | //注册广播接收者,监听下载状态
70 | mContext.registerReceiver(receiver,
71 | new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
72 | }
73 |
74 | //广播监听下载的各个状态
75 | private BroadcastReceiver receiver = new BroadcastReceiver() {
76 | @Override
77 | public void onReceive(Context context, Intent intent) {
78 | checkStatus();
79 | long downloadId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, 0);
80 | }
81 | };
82 |
83 | //检查下载状态
84 | private void checkStatus() {
85 | switch (getStatus()) {
86 | case DownloadManager.STATUS_PAUSED://下载暂停
87 | break;
88 |
89 | case DownloadManager.STATUS_PENDING://下载延迟
90 | break;
91 |
92 | case DownloadManager.STATUS_RUNNING://正在下载
93 | break;
94 |
95 | case DownloadManager.STATUS_SUCCESSFUL://下载完成
96 | du = null;
97 | mContext.unregisterReceiver(receiver);
98 | installAPK();//下载完成安装APK
99 | break;
100 |
101 | case DownloadManager.STATUS_FAILED://下载失败
102 | du = null;
103 | mContext.unregisterReceiver(receiver);
104 | break;
105 | }
106 | }
107 |
108 | @SuppressLint("Range")
109 | public int getStatus() {
110 | int status = 0;
111 | DownloadManager.Query query = new DownloadManager.Query();
112 | //通过id查找
113 | query.setFilterById(downloadId);
114 | Cursor cursor = dm.query(query);
115 | if (cursor.moveToFirst()) {
116 | status = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS));
117 | }
118 | cursor.close();
119 | return status;
120 | }
121 |
122 | private void installAPK() {
123 | Intent intent = new Intent(Intent.ACTION_VIEW);
124 | // 由于没有在Activity环境下启动Activity,设置下面的标签
125 | intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
126 | //Android7.0(24)以上要使用FileProvider
127 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
128 | //"test.mxm.FileProvider"在AndroidManifest.xml注册
129 | Uri apkUri = FileProvider.getUriForFile(mContext, "test.mxm.FileProvider", file);
130 | //添加这一句表示对目标应用临时授权该Uri所代表的文件
131 | intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
132 | intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
133 | } else {
134 | intent.setDataAndType(Uri.fromFile(file),
135 | "application/vnd.android.package-archive");
136 | }
137 | mContext.startActivity(intent);
138 | }
139 |
140 | /*private final String TAG = "DownloadUtils";
141 | //修改文件权限
142 | private void setPermission(String absolutePath) {
143 | String command = "chmod " + "777" + " " + absolutePath;
144 | Runtime runtime = Runtime.getRuntime();
145 | try {
146 | runtime.exec(command);
147 | } catch (IOException e) {
148 | Log.e(TAG, "setPermission: ", e);
149 | }
150 | }*/
151 |
152 | // 这个几个常量值在AOSP能找到 https://github.com/aosp-mirror/platform_frameworks_base/blob/master/core/java/android/provider/Downloads.java
153 | private static final String CONTENT_URI = "content://downloads/my_downloads";
154 | private static final int CONTROL_RUN = 0;
155 | private static final int CONTROL_PAUSED = 1;
156 | private static boolean resumeDownload(Context context, long id) {
157 | return controlDownload(context, id, CONTROL_RUN);
158 | }
159 |
160 | private static boolean pauseDownload(Context context, long id) {
161 | return controlDownload(context, id, CONTROL_PAUSED);
162 | }
163 |
164 | private static boolean controlDownload(Context context, long id, int control) {
165 | int updatedRows = 0;
166 | ContentValues controls = new ContentValues();
167 | // 以下写法可参考 DownloadManager.forceDownload() 方法 和 https://github.com/aosp-mirror/platform_frameworks_base/blob/master/core/java/android/provider/Downloads.java
168 | controls.put("control", control); // Resume Control Value
169 | // controls.put(DownloadManager.COLUMN_STATUS, 190); // 190: STATUS_PENDING
170 | try {
171 | updatedRows = context.getContentResolver().update(
172 | // Uri.parse(CONTENT_URI),
173 | // controls,
174 | // DownloadManager.COLUMN_ID + "=?",
175 | // new String[]{ String.valueOf(id) }
176 | ContentUris.withAppendedId(Uri.parse(CONTENT_URI), id),
177 | controls, null, null
178 | );
179 | } catch (Exception ignored) {}
180 |
181 | return updatedRows > 0;
182 | }
183 | }
184 |
--------------------------------------------------------------------------------
/app/src/main/java/template/recyclerview_group/SectionItemDecoration.java:
--------------------------------------------------------------------------------
1 | package template.recyclerview_group;
2 |
3 | import android.content.Context;
4 | import android.graphics.Canvas;
5 | import android.graphics.Color;
6 | import android.graphics.Paint;
7 | import android.graphics.Rect;
8 | import android.util.TypedValue;
9 | import android.view.View;
10 |
11 | import androidx.recyclerview.widget.LinearLayoutManager;
12 | import androidx.recyclerview.widget.RecyclerView;
13 |
14 | import java.util.ArrayList;
15 | import java.util.List;
16 |
17 | /**
18 | * 有分类title的 ItemDecoration
19 | */
20 | public class SectionItemDecoration extends RecyclerView.ItemDecoration {
21 | public String titles[];
22 | public int titlePositions[];//不包含titles[0]的位置
23 | public boolean titleDocksAtTheTop = false;//是否停靠在顶部
24 | private Paint mPaint;
25 | private Rect mBounds;//用于存放测量文字Rect
26 |
27 | private int mTitleBgHeight;//title的高
28 | private int seperatorHeight = 1;//分割线的高度
29 | private static int COLOR_TITLE_BG = Color.parseColor("#FFDFDFDF");
30 | private static int COLOR_TITLE_FONT = Color.parseColor("#FF000000");
31 | private static int mTitleFontSize;//title字体大小
32 |
33 |
34 | public SectionItemDecoration(Context context) {
35 | super();
36 | mPaint = new Paint();
37 | mBounds = new Rect();
38 | mTitleBgHeight = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 30, context.getResources().getDisplayMetrics());
39 | mTitleFontSize = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 16, context.getResources().getDisplayMetrics());
40 | mPaint.setTextSize(mTitleFontSize);
41 | mPaint.setAntiAlias(true);
42 | }
43 |
44 | @Override
45 | public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
46 | super.onDraw(c, parent, state);
47 |
48 | final int left = parent.getPaddingLeft();
49 | final int right = parent.getRight() - parent.getPaddingRight();
50 | // 获取当前屏幕可见 item 数量,而不是 RecyclerView 所有的 item 数量
51 | final int childCount = parent.getChildCount();
52 |
53 | View child;
54 | RecyclerView.LayoutParams params;
55 | int position;
56 | int bottom;
57 | // parent.getChildViewHolder()
58 | for (int i = titleDocksAtTheTop? 1 : 0; i < childCount; i++) {//有悬浮标题时,第0个item不用绘制
59 | child = parent.getChildAt(i);
60 | params = (RecyclerView.LayoutParams) child.getLayoutParams();
61 | position = params.getViewLayoutPosition();
62 | // position = params.getViewAdapterPosition();
63 | bottom = child.getTop() - params.topMargin;
64 |
65 | if (0 == position || (position = titleIndexAt(position)) > 0) {
66 | drawTitleArea(c, left, bottom - mTitleBgHeight, right, bottom, titles[position]);
67 | } else if (i > 0) {//画分割线,第0个不用绘制
68 | mPaint.setColor(COLOR_TITLE_BG);
69 | c.drawRect(left, bottom - seperatorHeight, right, bottom, mPaint);
70 | }
71 | }
72 | }
73 |
74 | /**
75 | * 绘制Title区域背景和文字的方法
76 | */
77 | private void drawTitleArea(Canvas c, int bgLeft, int bgTop, int bgRight, int bgBottom, String title) {//最先调用,绘制在最下层
78 | //绘制背景
79 | mPaint.setColor(COLOR_TITLE_BG);
80 | c.drawRect(bgLeft, bgTop, bgRight, bgBottom, mPaint);
81 | //绘制文字
82 | mPaint.setColor(COLOR_TITLE_FONT);
83 | mPaint.getTextBounds(title, 0, title.length(), mBounds);
84 |
85 | c.drawText(title, bgLeft,
86 | bgBottom - (mTitleBgHeight/2 - mBounds.height()/2),//y是baseline的位置,这里用文字的底部粗略当baseline
87 | mPaint);
88 | // Paint.FontMetrics fontMetrics = mPaint.getFontMetrics();
89 | // float distance = (fontMetrics.bottom - fontMetrics.top)/2 - fontMetrics.bottom;
90 | // float baseline = (bgTop + bgBottom)/2 + distance;//基准线
91 | /*
92 | * 对于大部分中文英文,distance用top和bottom计算,有偏差,字体被偏下了一点点,
93 | * 应该用ascent和descent计算,
94 | * 部分国家的特殊字符的上下高度会超过descent,ascent,用top和bottom计算
95 | */
96 | }
97 |
98 | @Override
99 | public void onDrawOver(Canvas c, RecyclerView parent, RecyclerView.State state) {//最后调用 绘制在最上层
100 | super.onDrawOver(c, parent, state);
101 | if (!titleDocksAtTheTop) return;//不用停靠在顶部
102 |
103 | final int position = ((LinearLayoutManager) parent.getLayoutManager()).findFirstVisibleItemPosition();
104 | if (RecyclerView.NO_POSITION == position) {// 越界检查
105 | return;
106 | }
107 |
108 | String title = null;
109 | if (0 == position || null == titlePositions || position < titlePositions[0]) {
110 | title = titles[0];
111 | } else if (null != titlePositions) {
112 | for (int i = titlePositions.length - 1; i > -1; --i) {
113 | if (position >= titlePositions[i]) {//只要在此范围内,就有标题
114 | title = titles[i + 1];
115 | break;
116 | }
117 | }
118 | }
119 | if (null == title) {
120 | return;
121 | }
122 |
123 | //第一个可见条目的位置
124 | // View child = manager.findViewByPosition(position);
125 | final View child = parent.getChildAt(0);//获取可见的最上面的一个;这种方式获取会不会有问题
126 | //最上面的item底部的高度<=标题背景的高度,且下一个item含有标题
127 | if (child.getBottom() <= mTitleBgHeight && titleIndexAt(position + 1) > 0) {
128 | c.translate(0, child.getBottom() - mTitleBgHeight);//上移
129 | }
130 |
131 | final int top = parent.getPaddingTop();
132 | drawTitleArea(c, parent.getPaddingLeft(), top,
133 | parent.getRight() - parent.getPaddingRight(),
134 | top + mTitleBgHeight, title);
135 | }
136 |
137 | @Override
138 | public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
139 | super.getItemOffsets(outRect, view, parent, state);
140 | // int position = ((RecyclerView.LayoutParams) view.getLayoutParams()).getViewLayoutPosition();
141 | // int position = parent.getLayoutManager().getPosition(view);
142 | int position = parent.getChildAdapterPosition(view);
143 | if (0 == position || titleIndexAt(position) > 0) {
144 | outRect.top = mTitleBgHeight;
145 | } else {
146 | outRect.top = seperatorHeight;
147 | }
148 | }
149 |
150 | private int titleIndexAt(int position) {
151 | if (null == titlePositions) return 0;
152 | for (int i = 0; i < titlePositions.length; ++i) {
153 | if (position == titlePositions[i]) {
154 | return i+1;
155 | }
156 | }
157 | return 0;
158 | }
159 |
160 | public static void setGroup(SectionItemDecoration decoration, SectionRVAdapter adapter, List titles, ArrayList> group) {
161 | int sections = group.size();
162 | if (sections == 0) {
163 | decoration.titlePositions = null;
164 | decoration.titles = null;
165 | adapter.count = 0;
166 | adapter.sectionFirstItemPosition = null;
167 | return;
168 | }
169 | decoration.titles = titles.toArray(new String[titles.size()]);
170 |
171 | int count = group.get(0).size();
172 | if (sections > 1) {//有多个分组
173 | //计算从第二组开始的,每组第一项的位置
174 | int[] sectionFirstItemPosition = new int[sections - 1];
175 | for (int i = 1; i < sections; i++) {
176 | sectionFirstItemPosition[i-1] = count;
177 | count += group.get(i).size();
178 | }
179 | decoration.titlePositions = sectionFirstItemPosition;
180 | adapter.sectionFirstItemPosition = sectionFirstItemPosition;
181 | } else {
182 | decoration.titlePositions = null;
183 | adapter.sectionFirstItemPosition = null;
184 | }
185 | adapter.count = count;
186 | }
187 | }
188 |
--------------------------------------------------------------------------------
/app/src/main/java/template/FileMultipleSelectionFragment.java:
--------------------------------------------------------------------------------
1 | package template;
2 |
3 |
4 | import android.app.Fragment;
5 | import android.content.ClipData;
6 | import android.content.ContentResolver;
7 | import android.content.ContentUris;
8 | import android.content.Context;
9 | import android.content.Intent;
10 | import android.database.Cursor;
11 | import android.net.Uri;
12 | import android.os.Build;
13 | import android.os.Bundle;
14 | import android.os.Environment;
15 | import android.provider.DocumentsContract;
16 | import android.provider.MediaStore;
17 | import android.util.Log;
18 | import android.view.LayoutInflater;
19 | import android.view.View;
20 | import android.view.ViewGroup;
21 |
22 | import androidx.annotation.RequiresApi;
23 |
24 | import static android.app.Activity.RESULT_OK;
25 |
26 |
27 | public class FileMultipleSelectionFragment extends Fragment {
28 |
29 | Context context;
30 |
31 | public FileMultipleSelectionFragment() {
32 | }
33 |
34 | @Override
35 | public void onAttach(Context context) {
36 | super.onAttach(context);
37 | this.context = context;
38 | }
39 |
40 | @Override
41 | public View onCreateView(LayoutInflater inflater, ViewGroup container,
42 | Bundle savedInstanceState) {
43 | View view = inflater.inflate(android.R.layout.simple_list_item_1, container, false);
44 |
45 | return view;
46 | }
47 |
48 |
49 | @Override
50 | public void onActivityResult(int requestCode, int resultCode, Intent data) {
51 | super.onActivityResult(requestCode, resultCode, data);
52 |
53 | if (requestCode != FILE_SELECT || RESULT_OK != resultCode || null == data) return;//调用系统的文件选择器
54 | ContentResolver cr = getActivity().getContentResolver();
55 | ClipData clipData = data.getClipData();
56 | if (null != clipData) {//多选
57 | for (int i = 0; i < clipData.getItemCount(); i++) {
58 | Uri uri = clipData.getItemAt(i).getUri();
59 | Log.i("---getClipData", "onActivityResult: " + uri.getPath());
60 | Log.i("---getClipData", "onActivityResult: " + uri.toString());
61 | // Log.i("---getClipData", "onActivityResult: " + getRealFilePath(cr, uri));
62 | }
63 | } else {
64 | Uri uri = data.getData();//单选
65 | // Log.i("---getData", "onActivityResult: " + getRealFilePath(cr, data.getData()));
66 | Log.i("---getData", "onActivityResult: " + uri.toString());
67 | }
68 | }
69 |
70 | private static final int FILE_SELECT = 1;
71 | private void showFileChooser() {//使用系统文件选择器
72 | Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
73 | intent.setType("*/*");
74 | intent.addCategory(Intent.CATEGORY_OPENABLE);
75 | intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);//允许多选
76 | try {
77 | //虽然设置了允许多选,但有些文件管理器不支持多选
78 | startActivityForResult(Intent.createChooser(intent, "请选择文件"), FILE_SELECT);
79 | } catch (android.content.ActivityNotFoundException ex) {
80 | // Potentially direct the user to the Market with a Dialog
81 | // Toast.makeText(this, "Please install a File Manager.", Toast.LENGTH_SHORT).show();
82 | }
83 |
84 | //这个是文件夹选择器: https://github.com/googlesamples/android-DirectorySelection
85 | // Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);
86 | // startActivityForResult(intent, 1);
87 |
88 | }
89 | }
90 |
91 | /**
92 | * 专为Android4.4设计的从Uri获取文件绝对路径,以前的方法已不好使
93 | */
94 | class ConvertUriToFilePath {
95 | /**
96 | * Get a file path from a Uri. This will get the the path for Storage Access
97 | * Framework Documents, as well as the _data field for the MediaStore and
98 | * other file-based ContentProviders.
99 | *
100 | * @param context The context.
101 | * @param uri The Uri to query.
102 | */
103 | @RequiresApi(api = Build.VERSION_CODES.KITKAT)
104 | public static String getPathFromURI(final Context context, final Uri uri) {
105 |
106 | final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
107 |
108 | // DocumentProvider
109 | if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
110 | // ExternalStorageProvider
111 | if (isExternalStorageDocument(uri)) {
112 | final String docId = DocumentsContract.getDocumentId(uri);
113 | final String[] split = docId.split(":");
114 | final String type = split[0];
115 |
116 | if ("primary".equalsIgnoreCase(type)) {
117 | return Environment.getExternalStorageDirectory() + "/" + split[1];
118 | }
119 | }
120 | // DownloadsProvider
121 | else if (isDownloadsDocument(uri)) {
122 |
123 | final String id = DocumentsContract.getDocumentId(uri);
124 | final Uri contentUri = ContentUris.withAppendedId(
125 | Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
126 |
127 | return getDataColumn(context, contentUri, null, null);
128 | }
129 | // MediaProvider
130 | else if (isMediaDocument(uri)) {
131 | final String docId = DocumentsContract.getDocumentId(uri);
132 | final String[] split = docId.split(":");
133 | final String type = split[0];
134 |
135 | Uri contentUri = null;
136 | if ("image".equals(type)) {
137 | contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
138 | } else if ("video".equals(type)) {
139 | contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
140 | } else if ("audio".equals(type)) {
141 | contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
142 | }
143 |
144 | final String selection = "_id=?";
145 | final String[] selectionArgs = new String[]{
146 | split[1]
147 | };
148 |
149 | return getDataColumn(context, contentUri, selection, selectionArgs);
150 | }
151 | }
152 | // MediaStore (and general)
153 | else if ("content".equalsIgnoreCase(uri.getScheme())) {
154 | return getDataColumn(context, uri, null, null);
155 | }
156 | // File
157 | else if ("file".equalsIgnoreCase(uri.getScheme())) {
158 | return uri.getPath();
159 | }
160 |
161 | return null;
162 | }
163 |
164 | /**
165 | * Get the value of the data column for this Uri. This is useful for
166 | * MediaStore Uris, and other file-based ContentProviders.
167 | *
168 | * @param context The context.
169 | * @param uri The Uri to query.
170 | * @param selection (Optional) Filter used in the query.
171 | * @param selectionArgs (Optional) Selection arguments used in the query.
172 | * @return The value of the _data column, which is typically a file path.
173 | */
174 | public static String getDataColumn(Context context, Uri uri, String selection,
175 | String[] selectionArgs) {
176 |
177 | Cursor cursor = null;
178 | final String column = "_data";
179 | final String[] projection = {
180 | column
181 | };
182 |
183 | try {
184 | cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
185 | null);
186 | if (cursor != null && cursor.moveToFirst()) {
187 | final int column_index = cursor.getColumnIndexOrThrow(column);
188 | return cursor.getString(column_index);
189 | }
190 | } finally {
191 | if (cursor != null)
192 | cursor.close();
193 | }
194 | return null;
195 | }
196 |
197 |
198 | /**
199 | * @param uri The Uri to check.
200 | * @return Whether the Uri authority is ExternalStorageProvider.
201 | */
202 | public static boolean isExternalStorageDocument(Uri uri) {
203 | return "com.android.externalstorage.documents".equals(uri.getAuthority());
204 | }
205 |
206 | /**
207 | * @param uri The Uri to check.
208 | * @return Whether the Uri authority is DownloadsProvider.
209 | */
210 | public static boolean isDownloadsDocument(Uri uri) {
211 | return "com.android.providers.downloads.documents".equals(uri.getAuthority());
212 | }
213 |
214 | /**
215 | * @param uri The Uri to check.
216 | * @return Whether the Uri authority is MediaProvider.
217 | */
218 | public static boolean isMediaDocument(Uri uri) {
219 | return "com.android.providers.media.documents".equals(uri.getAuthority());
220 | }
221 | }
222 |
--------------------------------------------------------------------------------
/app/src/main/java/template/AlertDialogTheme.java:
--------------------------------------------------------------------------------
1 | package template;
2 |
3 | import android.app.AlertDialog;
4 | import android.content.Context;
5 | import android.content.DialogInterface;
6 | import android.graphics.Color;
7 | import android.graphics.drawable.GradientDrawable;
8 | import android.graphics.drawable.InsetDrawable;
9 | import android.text.TextUtils;
10 | import android.util.Log;
11 | import android.util.TypedValue;
12 | import android.view.LayoutInflater;
13 | import android.view.View;
14 | import android.widget.Button;
15 | import android.widget.TextView;
16 |
17 | import androidx.annotation.StringRes;
18 |
19 | import min.test.android_app_template.R;
20 |
21 | //https://www.jianshu.com/p/06a3bbb7ce79
22 | public class AlertDialogTheme {
23 | private static final String TAG = "AlertDialogTheme";
24 |
25 | /* 主要是看R.style.AlertDialog和AppTheme中的alertDialogTheme */
26 | public static void test(Context context) {
27 | StringBuilder sb = new StringBuilder();
28 | for (int i = 0; i < 6; ++i) {
29 | sb.append("消息消息消息消息消息消息消息消息消息消");
30 | }
31 | //设置了全局alertDialogTheme
32 | // AlertDialog dialog = new AlertDialog.Builder(context)
33 | //单个使用
34 | AlertDialog dialog = new AlertDialog.Builder(context, R.style.AlertDialog)
35 | .setTitle("标题")
36 | .setMessage(sb.toString())
37 | .setNegativeButton("Cancel", null)//android.R.id.button2
38 | .setNeutralButton("Neutral", null)//android.R.id.button3
39 | .setPositiveButton("OK", null)//android.R.id.button1
40 | .show();
41 |
42 | //可以通过这种方法修改消息体和按钮,以下所有view只能在show()之后获取,create()之后都不行
43 | TextView text = dialog.findViewById(android.R.id.message);
44 | text.setTextSize(20);
45 | Button btn1 = dialog.findViewById(android.R.id.button1);
46 | Button btn2 = dialog.findViewById(android.R.id.button2);
47 | Button btn3 = dialog.findViewById(android.R.id.button3);
48 | //也可以这么获取
49 | // Button btn1 = dialog.getButton(DialogInterface.BUTTON_POSITIVE);
50 | // Button btn2 = dialog.getButton(DialogInterface.BUTTON_NEGATIVE);
51 | // Button btn3 = dialog.getButton(DialogInterface.BUTTON_NEUTRAL);
52 | Log.e(TAG, "btn1: " + btn1.getText());
53 | Log.e(TAG, "btn2: " + btn2.getText());
54 | Log.e(TAG, "btn3: " + btn3.getText());
55 | }
56 |
57 | public void test2(Context context) {
58 | new Builder(context)
59 | .setTitle("title")
60 | .setMessage("hello")
61 | .setPositiveButton("OK", new DialogInterface.OnClickListener() {
62 | @Override
63 | public void onClick(DialogInterface dialog, int which) {
64 | Log.e(TAG, "onClick: Ok");
65 | }
66 | })
67 | .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
68 | @Override
69 | public void onClick(DialogInterface dialog, int which) {
70 | Log.e(TAG, "onClick: Cancel");
71 | }
72 | })
73 | .show();
74 | }
75 | }
76 |
77 | /**
78 | * 仿iOS的Alert,但API尽量和AlertDialog.Builder一致
79 | */
80 | class Builder {
81 | private Context context;
82 | public Builder(Context context) {
83 | this.context = context;
84 | }
85 |
86 | private CharSequence mTitle;
87 | public Builder setTitle(CharSequence title) {
88 | mTitle = title;
89 | return this;
90 | }
91 | public Builder setTitle(@StringRes int titleId) {
92 | mTitle = context.getText(titleId);
93 | return this;
94 | }
95 |
96 | private CharSequence mMessage;
97 | public Builder setMessage(CharSequence message) {
98 | mMessage = message;
99 | return this;
100 | }
101 | public Builder setMessage(@StringRes int messageId) {
102 | mMessage = context.getText(messageId);
103 | return this;
104 | }
105 |
106 | private CharSequence leftBtnText;
107 | private DialogInterface.OnClickListener leftBtnClick;
108 | public Builder setNegativeButton(CharSequence text, DialogInterface.OnClickListener onClickListener) {
109 | leftBtnText = text;
110 | leftBtnClick = onClickListener;
111 | return this;
112 | }
113 | public Builder setNegativeButton(@StringRes int textId, DialogInterface.OnClickListener onClickListener) {
114 | leftBtnText = context.getText(textId);
115 | leftBtnClick = onClickListener;
116 | return this;
117 | }
118 |
119 | private CharSequence rightBtnText;
120 | private DialogInterface.OnClickListener rightBtnClick;
121 | public Builder setPositiveButton(CharSequence text, DialogInterface.OnClickListener onClickListener) {
122 | rightBtnText = text;
123 | rightBtnClick = onClickListener;
124 | return this;
125 | }
126 | public Builder setPositiveButton(@StringRes int textId, DialogInterface.OnClickListener onClickListener) {
127 | rightBtnText = context.getText(textId);
128 | rightBtnClick = onClickListener;
129 | return this;
130 | }
131 |
132 | private boolean mCancelable = true;
133 | public Builder setCancelable(boolean cancelable) {
134 | mCancelable = cancelable;
135 | return this;
136 | }
137 |
138 | private DialogInterface.OnCancelListener mOnCancelListener;
139 | public Builder setOnCancelListener(DialogInterface.OnCancelListener onCancelListener) {
140 | mOnCancelListener = onCancelListener;
141 | return this;
142 | }
143 |
144 | private DialogInterface.OnDismissListener mOnDismissListener;
145 | public Builder setOnDismissListener(DialogInterface.OnDismissListener onDismissListener) {
146 | mOnDismissListener = onDismissListener;
147 | return this;
148 | }
149 |
150 | private DialogInterface.OnKeyListener mOnKeyListener;
151 | public Builder setOnKeyListener(DialogInterface.OnKeyListener onKeyListener) {
152 | mOnKeyListener = onKeyListener;
153 | return this;
154 | }
155 |
156 | public AlertDialog create() {
157 | View view = LayoutInflater.from(context).inflate(R.layout.dialog_2_btn_alert, null, false);
158 |
159 | AlertDialog dialog = new AlertDialog.Builder(context)//R.style.AlertDialogTheme
160 | .setView(view)
161 | .setCancelable(mCancelable)
162 | .setOnCancelListener(mOnCancelListener)
163 | .setOnDismissListener(mOnDismissListener)
164 | .setOnKeyListener(mOnKeyListener)
165 | .create();
166 |
167 | //设置AlertDialog背景,和使用R.style.AlertDialogTheme创建的AlertDialog效果相同
168 | GradientDrawable drawable = new GradientDrawable();
169 | drawable.setShape(GradientDrawable.RECTANGLE);
170 | drawable.setColor(Color.WHITE);
171 | drawable.setCornerRadius(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 10,
172 | context.getResources().getDisplayMetrics()));
173 | InsetDrawable iDrawable = new InsetDrawable(drawable,
174 | (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 26,
175 | context.getResources().getDisplayMetrics()));
176 | dialog.getWindow().setBackgroundDrawable(iDrawable);
177 |
178 | //设置自定义视图dialog_2_btn_alert
179 | TextView tvTitle = view.findViewById(R.id.tvTitle);
180 | TextView tvMessage = view.findViewById(R.id.tvMessage);
181 | TextView btnLeft = view.findViewById(R.id.btn2);
182 | TextView btnRight = view.findViewById(R.id.btn1);
183 |
184 | if (!TextUtils.isEmpty(mTitle)) {
185 | tvTitle.setText(mTitle);
186 | } else {
187 | tvTitle.setVisibility(View.GONE);
188 | }
189 | if (!TextUtils.isEmpty(mMessage)) {
190 | tvMessage.setText(mMessage);
191 | } else {
192 | tvMessage.setVisibility(View.GONE);
193 | }
194 |
195 | if (!TextUtils.isEmpty(leftBtnText)) {
196 | btnLeft.setText(leftBtnText);
197 | btnLeft.setOnClickListener(new DialogOnClick(dialog, leftBtnClick, DialogInterface.BUTTON_NEGATIVE));
198 | } else {
199 | btnLeft.setVisibility(View.GONE);
200 | }
201 |
202 | if (!TextUtils.isEmpty(rightBtnText)) {
203 | btnRight.setText(rightBtnText);
204 | btnRight.setOnClickListener(new DialogOnClick(dialog, rightBtnClick, DialogInterface.BUTTON_POSITIVE));
205 | } else {
206 | btnRight.setVisibility(View.GONE);
207 | }
208 |
209 | return dialog;
210 | }
211 |
212 | public AlertDialog show() {
213 | AlertDialog dialog = create();
214 | dialog.show();
215 | return dialog;
216 | }
217 | }
218 |
219 | class DialogOnClick implements View.OnClickListener {
220 | private DialogInterface mDialog;
221 | private DialogInterface.OnClickListener mOnClickListener;
222 | private int mWhichButton;
223 |
224 | public DialogOnClick(DialogInterface dialog, DialogInterface.OnClickListener onClickListener, int whichButton) {
225 | mDialog = dialog;
226 | mOnClickListener = onClickListener;
227 | mWhichButton = whichButton;
228 | }
229 |
230 | @Override
231 | public void onClick(View v) {
232 | mDialog.dismiss();
233 | if (null != mOnClickListener) {
234 | mOnClickListener.onClick(mDialog, mWhichButton);
235 | }
236 | mDialog = null;
237 | mOnClickListener = null;
238 | }
239 | }
--------------------------------------------------------------------------------
/app/src/main/java/utils/encryption/aes/AES.java:
--------------------------------------------------------------------------------
1 | package utils.encryption.aes;
2 |
3 | import android.annotation.SuppressLint;
4 | import android.os.Build;
5 | import android.text.TextUtils;
6 | import android.util.Log;
7 |
8 | import androidx.annotation.IntDef;
9 |
10 | import java.io.UnsupportedEncodingException;
11 | import java.nio.charset.StandardCharsets;
12 | import java.security.InvalidAlgorithmParameterException;
13 | import java.security.InvalidKeyException;
14 | import java.security.NoSuchAlgorithmException;
15 | import java.security.NoSuchProviderException;
16 | import java.security.Provider;
17 | import java.security.SecureRandom;
18 |
19 | import javax.crypto.BadPaddingException;
20 | import javax.crypto.Cipher;
21 | import javax.crypto.IllegalBlockSizeException;
22 | import javax.crypto.KeyGenerator;
23 | import javax.crypto.NoSuchPaddingException;
24 | import javax.crypto.spec.IvParameterSpec;
25 | import javax.crypto.spec.SecretKeySpec;
26 |
27 | /*
28 | * 安卓系统提供了多种密钥算法:
29 | * https://developer.android.google.cn/guide/topics/security/cryptography
30 | * https://developer.android.google.cn/training/articles/keystore
31 | */
32 | //https://zhuanlan.zhihu.com/p/24255780
33 | public class AES {
34 | private static final String TAG = "AES";
35 |
36 | private final static String SHA1_PRNG = "SHA1PRNG";
37 |
38 | /*
39 | * 生成随机数,可以当做动态的密钥 加密和解密的密钥必须一致,不然将不能解密
40 | */
41 | public static String generateKey() {
42 | try {
43 | SecureRandom localSecureRandom = SecureRandom.getInstance(SHA1_PRNG);
44 | byte[] bytesKey = new byte[16];
45 | localSecureRandom.nextBytes(bytesKey);
46 | String strKey = byte2HexString(bytesKey);
47 | return strKey;
48 | } catch (Exception e) {
49 | e.printStackTrace();
50 | }
51 | return null;
52 | }
53 |
54 | private static final char[] hex = new char[]{
55 | '0', '1', '2', '3', '4', '5', '6', '7',
56 | '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
57 | };
58 | //字节数组转16进制字符串
59 | private static String byte2HexString(byte[] buf) {
60 | char[] chs = new char[buf.length * 2];
61 | // StringBuilder sb = new StringBuilder(buf.length * 2);//字符串很长的时候用此类
62 | // String tp;
63 | int index = 0;
64 | for (byte b : buf) {
65 | //一:
66 | // sb.append(String.format("%02X", b & 0xFF));//性能最差,差的不止一个数量级的
67 | //二:性能第三
68 | // sb.append(Integer.toHexString((b >>> 4) & 0x0F));//byte会被强转成int类型,从而带来符号问题,所以需要(& 0x0F)
69 | // sb.append(Integer.toHexString(b & 0x0F));
70 | //三:性能第二
71 | // tp = Integer.toHexString(b & 0xFF);//byte会被强转成int类型,同理
72 | // if (tp.length() < 2) sb.append('0');
73 | // sb.append(tp);
74 | //四:性能最好
75 | // sb.append(hex[(b >>> 4) & 0x0F]);
76 | // sb.append(hex[b & 0x0F]);
77 | chs[index] = hex[(b >>> 4) & 0x0F];
78 | ++index;
79 | chs[index] = hex[b & 0x0F];
80 | ++index;
81 | }
82 | // return sb.toString();
83 | return new String(chs);
84 | }
85 |
86 | //16进制转字节数组
87 | private static byte[] hexString2Byte(String hexStr) {
88 | final int len = hexStr.length();
89 | if (len < 1) return null;
90 | byte[] result = new byte[len / 2];
91 | // i/2 == i>>1
92 | // for (int i = 0; i < len; i+=2) {
93 | // result[i>>1] = (byte) Integer.parseInt(hexStr.substring(i, i + 2), 16);//出错抛异常
94 | // }
95 | // for (int i = 0; i < len; i+=2) {
96 | // result[i>>1] = (byte) ((Character.digit((int)hexStr.charAt(i), 16) << 4)
97 | // | Character.digit((int)hexStr.charAt(i + 1), 16));//出错无抛异常
98 | // }
99 | for (int i = 0; i < len; i+=2) {
100 | result[i>>1] = (byte) ((digit(hexStr.charAt(i)) << 4) | digit(hexStr.charAt(i + 1)));//出错抛异常
101 | }
102 | return result;
103 | }
104 |
105 | private static int digit(char codePoint) {
106 | int result = -1;
107 | if ('0' <= codePoint && codePoint <= '9') {
108 | result = codePoint - '0';
109 | } else if ('a' <= codePoint && codePoint <= 'f') {
110 | result = 10 + (codePoint - 'a');
111 | } else if ('A' <= codePoint && codePoint <= 'F') {
112 | result = 10 + (codePoint - 'A');
113 | } else {
114 | throw new NumberFormatException("For input char: \"" + codePoint + "\"");
115 | }
116 | return result;
117 | }
118 |
119 | // 向量
120 | private static final byte[] IV = new byte[]{8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 6, 5};
121 |
122 | /*
123 | 单片机参考: https://blog.csdn.net/chengjunchengjun/article/details/109322987
124 |
125 | PKCS5Padding
126 | PKCS7Padding
127 | NoPadding
128 | ZerosPadding
129 | ISO10126Padding
130 |
131 | 总结一下,就是用了 NoPadding 就代表着你对这个数据是否可以被完整分组负有责任,如果不能被完整分组就会报错或者抛出异常。
132 |
133 | 然后 ZerosPadding 意思就是在数据块末尾补0x00,注意如果刚开始已经完整分组了也需要补一整个分组的0x00,否则无法解密。
134 |
135 | PKCS7Padding 就是数据个数最后少几个就填充多少个数,具体的做法可以:数据的个数先取余16,然后16减去余数。
136 | 例如{1,2,3,4,5,6,7,8,9},总共9个数值,取余16后是9,需要补充7个7,则最后数据变为{1,2,3,4,5,6,7,8,9,7,7,7,7,7,7,7}
137 |
138 | PKCS5Padding,PKCS7Padding的子集,块大小固定为8字节。在AES加密当中其实是没有pkcs5的,
139 | 因为AES的分块是16B而pkcs5只能用于8B,所以我们在AES加密中所说的pkcs5指的就是pkcs7。
140 |
141 | 由于使用 PKCS7Padding/PKCS5Padding 填充时,最后一个字节肯定为填充数据的长度,所以在解密后可以准确删除填充的数据,
142 | 而使用 ZeroPadding 填充时,没办法区分真实数据与填充数据,所以只适合以\0结尾的字符串加解密。
143 | 为了改善这种不足,ISO10126Padding 采用不足的n-1位补随机数,最后一位补n的做法。
144 | */
145 | /**
146 | * AES加密
147 | * @param data 要加密的数据
148 | * @param key 密钥,长度必须是8的整倍数?
149 | * @return 加密后的数据
150 | */
151 | public static byte[] encryptAES128CBC(byte[] data, byte[] key) {
152 | try {
153 | // iOS 只支持 PKCS7Padding 加密,或者 iOS 也用NoPadding自己补齐,Android PKCS7Padding 和 PKCS5Padding 都支持。AES/CBC/PKCS7Padding AES/ECB/PKCS5Padding
154 | @SuppressLint("GetInstance")
155 | Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
156 |
157 | cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key, "AES"), new IvParameterSpec(IV));
158 | int blockSize = cipher.getBlockSize();
159 | int length = data.length;
160 | if (length % blockSize == 0) return cipher.doFinal(data);
161 |
162 | // 使用 NoPadding 就要自己补齐不足的字节
163 | length = length + (blockSize - (length % blockSize));
164 | byte[] newData = new byte[length];
165 | System.arraycopy(data, 0, newData, 0, data.length);
166 | return cipher.doFinal(newData);
167 | } catch (NoSuchAlgorithmException | InvalidKeyException | InvalidAlgorithmParameterException | NoSuchPaddingException | BadPaddingException | IllegalBlockSizeException e) {
168 | Log.e(TAG, "aes128encrypt: ", e);
169 | }
170 |
171 | return null;
172 | }
173 |
174 | public static byte[] decryptUseAES128CBC(byte[] data, byte[] key) {
175 | try {
176 | @SuppressLint("GetInstance")
177 | Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
178 | cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(key, "AES"), new IvParameterSpec(IV));
179 | return trimBytes(cipher.doFinal(data));
180 | } catch (NoSuchAlgorithmException | InvalidKeyException | InvalidAlgorithmParameterException | NoSuchPaddingException | BadPaddingException | IllegalBlockSizeException e) {
181 | Log.e(TAG, "aes128encrypt: ", e);
182 | }
183 |
184 | return null;
185 | }
186 |
187 | public static byte[] trimBytes(byte[] bytes) {
188 | int useLen;
189 | for (useLen = bytes.length - 1; useLen >= 0; useLen--) {
190 | if (0x00 != bytes[useLen]) {
191 | byte[] newBytes = new byte[useLen + 1];
192 | System.arraycopy(bytes, 0, newBytes, 0, newBytes.length);
193 | return newBytes;
194 | }
195 | }
196 | if (bytes.length == 16) {
197 | return new byte[]{bytes[0]};
198 | }
199 | return bytes;
200 | }
201 |
202 | public static byte[] encryptAES128CBCPKCS7(byte[] data, byte[] key) {
203 | try {
204 | // iOS 只支持 PKCS7Padding 加密,或者 iOS 也用NoPadding自己补齐,Android PKCS7Padding 和 PKCS5Padding 都支持。AES/CBC/PKCS7Padding AES/ECB/PKCS5Padding
205 | @SuppressLint("GetInstance")
206 | Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
207 |
208 | // ECB 不需要 IvParameterSpec
209 | cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key, "AES"), new IvParameterSpec(IV));
210 | return cipher.doFinal(data);
211 | } catch (NoSuchAlgorithmException | InvalidKeyException | InvalidAlgorithmParameterException | NoSuchPaddingException | BadPaddingException | IllegalBlockSizeException e) {
212 | Log.e(TAG, "aes128encrypt: ", e);
213 | }
214 |
215 | return null;
216 | }
217 |
218 | public static byte[] decryptUseAES128CBCPKCS7(byte[] data, byte[] key) {
219 | try {
220 | @SuppressLint("GetInstance")
221 | Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
222 | // ECB 不需要 IvParameterSpec
223 | cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(key, "AES"), new IvParameterSpec(IV));
224 | return cipher.doFinal(data);
225 | } catch (NoSuchAlgorithmException | InvalidKeyException | InvalidAlgorithmParameterException | NoSuchPaddingException | BadPaddingException | IllegalBlockSizeException e) {
226 | Log.e(TAG, "aes128encrypt: ", e);
227 | }
228 |
229 | return null;
230 | }
231 | }
232 |
--------------------------------------------------------------------------------
/app/src/main/java/template/CalendarAndAlarmClock.java:
--------------------------------------------------------------------------------
1 | package template;
2 |
3 | import android.Manifest;
4 | import android.app.Activity;
5 | import android.content.ContentUris;
6 | import android.content.ContentValues;
7 | import android.content.Intent;
8 | import android.content.pm.PackageManager;
9 | import android.database.Cursor;
10 | import android.net.Uri;
11 | import android.provider.AlarmClock;
12 | import android.provider.CalendarContract;
13 | import android.widget.Toast;
14 |
15 | import androidx.core.app.ActivityCompat;
16 |
17 | import org.json.JSONArray;
18 | import org.json.JSONException;
19 | import org.json.JSONObject;
20 |
21 | import java.util.ArrayList;
22 | import java.util.Calendar;
23 | import java.util.TimeZone;
24 |
25 | /**
26 | * https://developer.android.com/guide/topics/providers/calendar-provider
27 | * https://www.jianshu.com/p/4820e02b2ee4
28 | */
29 | public class CalendarAndAlarmClock {
30 |
31 | private static Uri calanderURL = CalendarContract.Calendars.CONTENT_URI;
32 | private static Uri calanderEventURL = CalendarContract.Events.CONTENT_URI;
33 | private static Uri calanderRemiderURL = CalendarContract.Reminders.CONTENT_URI;
34 |
35 | private static long calenderId = -1;
36 |
37 | /**
38 | * 是否没有读写权限
39 | * @param activity
40 | * @return true没有读写权限, false有读写权限
41 | */
42 | public static boolean hasNoReadWritePermission(Activity activity) {
43 | return ActivityCompat.checkSelfPermission(activity, Manifest.permission.READ_CALENDAR) != PackageManager.PERMISSION_GRANTED ||
44 | ActivityCompat.checkSelfPermission(activity, Manifest.permission.WRITE_CALENDAR) != PackageManager.PERMISSION_GRANTED;
45 | }
46 | /**
47 | * 请求读写权限
48 | * 需要重写的方法:
49 | * @see ActivityCompat.OnRequestPermissionsResultCallback#onRequestPermissionsResult(int, String[], int[])
50 | * 用户操作后回调重写方法
51 | * */
52 | public static void requestReadWritePermission(Activity activity, int requestCode) {
53 | ActivityCompat.requestPermissions(activity, new String[]{Manifest.permission.READ_CALENDAR, Manifest.permission.WRITE_CALENDAR}, requestCode);
54 | }
55 |
56 | private static void init(Activity activity) {
57 | if (calenderId <= 0) {
58 | Cursor userCursor = activity.getContentResolver()
59 | .query(calanderURL, null, null, null, null);
60 | //如果小于1代表没有账户
61 | if (userCursor.getCount() < 1) {
62 | //添加账户
63 | calenderId = initCalendars(activity, "mintest");
64 | } else {
65 | //注意:是向最后一个账户添加,开发者可以根据需要改变添加事件 的账户
66 | userCursor.moveToLast();
67 | calenderId = userCursor.getLong(userCursor.getColumnIndex(CalendarContract.Calendars._ID));
68 | }
69 | userCursor.close();
70 | }
71 | }
72 |
73 | /**
74 | * 添加一个属于自己的账户,方便以后取这个账户的提醒事件
75 | *
76 | * @param activity
77 | * @param accountName 账户名
78 | */
79 | private static long initCalendars(Activity activity, String accountName) {
80 | /*
81 | * 小米默认账户
82 | * allowedReminders=0,1
83 | * sync_events=1
84 | * canModifyTimeZone=1
85 | * canOrganizerRespond=1
86 | * maxReminders=5
87 | * _id=1
88 | * visible=1
89 | * calendar_color=-30720
90 | * account_name=account_name_local
91 | * account_type=LOCAL
92 | * calendar_displayName=calendar_displayname_local
93 | * deleted=0
94 | * ownerAccount=owner_account_local
95 | * calendar_access_level=700
96 | * canPartiallyUpdate=0
97 | */
98 | ContentValues value = new ContentValues();
99 | value.put(CalendarContract.Calendars.NAME, "com.min.test");
100 |
101 | value.put(CalendarContract.Calendars.ACCOUNT_NAME, accountName);//日历账户名称
102 | value.put(CalendarContract.Calendars.ACCOUNT_TYPE, "com.android.exchange");
103 | value.put(CalendarContract.Calendars.CALENDAR_DISPLAY_NAME, accountName);
104 | value.put(CalendarContract.Calendars.VISIBLE, 1);
105 | value.put(CalendarContract.Calendars.CALENDAR_COLOR, -30720);
106 | value.put(CalendarContract.Calendars.CALENDAR_ACCESS_LEVEL, CalendarContract.Calendars.CAL_ACCESS_OWNER);
107 | value.put(CalendarContract.Calendars.SYNC_EVENTS, 1);
108 | value.put(CalendarContract.Calendars.CALENDAR_TIME_ZONE, TimeZone.getDefault().getID());
109 | value.put(CalendarContract.Calendars.OWNER_ACCOUNT, accountName);
110 | value.put(CalendarContract.Calendars.CAN_ORGANIZER_RESPOND, 0);
111 |
112 | Uri calendarUri = CalendarContract.Calendars.CONTENT_URI;
113 | calendarUri = calendarUri.buildUpon()
114 | .appendQueryParameter(CalendarContract.CALLER_IS_SYNCADAPTER, "true")
115 | .appendQueryParameter(CalendarContract.Calendars.ACCOUNT_NAME, accountName)
116 | .appendQueryParameter(CalendarContract.Calendars.ACCOUNT_TYPE, "com.android.exchange")
117 | .build();
118 | //插入账号数据
119 | Uri uri = activity.getContentResolver().insert(calendarUri, value);
120 | if (null != uri) {
121 | return ContentUris.parseId(uri);
122 | }
123 | return -1;
124 | }
125 |
126 | /**
127 | * 日期时间转时间戳
128 | * @param time 时间 格式 yyyy/mm/dd/hh/mm
129 | * @return
130 | */
131 | private static long getTime(String time) {
132 | Calendar calendar = Calendar.getInstance();
133 | String[] startTime = time.split("/");
134 | calendar.set(Calendar.YEAR, Integer.parseInt(startTime[0]));//年
135 | calendar.set(Calendar.MONTH, Integer.parseInt(startTime[1])-1);//月
136 | calendar.set(Calendar.DAY_OF_MONTH, Integer.parseInt(startTime[2]));//日
137 | calendar.set(Calendar.HOUR_OF_DAY, Integer.parseInt(startTime[3]));//时
138 | calendar.set(Calendar.MINUTE, Integer.parseInt(startTime[4]));//分
139 | return calendar.getTimeInMillis();
140 | }
141 |
142 | /**
143 | * 获取日历事件
144 | *
145 | * @param context
146 | */
147 | public static JSONArray queryCalendarEvent(Activity context, long eventId) throws JSONException {
148 | Uri uri = calanderEventURL;
149 | if (eventId > 0) {
150 | uri = ContentUris.withAppendedId(calanderEventURL, eventId);
151 | }
152 | Cursor cursor = context.getContentResolver()
153 | .query(uri, null,
154 | CalendarContract.Events.MUTATORS + " = ?",
155 | new String[]{context.getPackageName()}, null);
156 | JSONArray ja = new JSONArray();
157 | JSONObject jo;
158 | while (cursor.moveToNext()) {
159 | jo = new JSONObject();
160 | jo.put("title", cursor.getString(cursor.getColumnIndex(CalendarContract.Events.TITLE)));
161 | jo.put("description", cursor.getString(cursor.getColumnIndex(CalendarContract.Events.DESCRIPTION)));
162 | jo.put("dtStart", cursor.getString(cursor.getColumnIndex(CalendarContract.Events.DTSTART)));
163 | String rrule = cursor.getString(cursor.getColumnIndex(CalendarContract.Events.RRULE));
164 | if (null != rrule) {
165 | String[] keyValues = rrule.split(";");
166 |
167 | String[] keyValue = keyValues[0].split("=");
168 | jo.put("freq", keyValue[1].toLowerCase());
169 |
170 | keyValue = keyValues[1].split("=");
171 | jo.put("interval", keyValue[1]);
172 | }
173 | ja.put(jo);
174 | }
175 | cursor.close();
176 | return ja;
177 | }
178 |
179 | /**
180 | * 添加日历事件或更新
181 | *
182 | * @param context
183 | * @param title 日程标题
184 | * @param description 备注信息
185 | * @param dtStart 提醒开始时间, 时间戳
186 | * @param freq 频率
187 | * @param interval 频率间隔
188 | * @return
189 | */
190 | public static int addCalendarEvent(Activity context, long eventId, String title, String description, long dtStart, String freq, short interval) {
191 | if (dtStart <= 0) {
192 | Toast.makeText(context, "提醒开始时间不能为空!", Toast.LENGTH_SHORT).show();
193 | return -1;
194 | }
195 |
196 | init(context);
197 |
198 | //rrule组装
199 | switch (freq.toLowerCase()) {
200 | case "daily"://天
201 | break;
202 | case "weekly"://周
203 | {
204 | Calendar calendar = Calendar.getInstance();
205 | calendar.setTimeInMillis(dtStart);
206 | String[] weeklys = new String[]{"SU", "MO", "TU", "WE", "TH", "FR", "SA"};
207 | String wk = ";BYDAY=" + weeklys[calendar.get(Calendar.DAY_OF_WEEK) - 1];
208 | }
209 | break;
210 | case "monthly"://月
211 | break;
212 | case "yearly"://年
213 | break;
214 | }
215 |
216 | //FREQ=WEEKLY;INTERVAL=2;WKST=SU;BYDAY=WE //WKST得根据地区调整?
217 | String rrlue = "FREQ=" + freq.toUpperCase() + ";INTERVAL" + interval;
218 |
219 | ContentValues event = new ContentValues();
220 | // 插入账户
221 | event.put(CalendarContract.Events.CALENDAR_ID, 1);
222 | // event.put(CalendarContract.Events.MUTATORS, context.getPackageName());//同步的包名,不用自己设置,系统默认设置成自己的包名
223 | event.put(CalendarContract.Events.TITLE, title);
224 | event.put(CalendarContract.Events.DESCRIPTION, description);
225 | event.put(CalendarContract.Events.DURATION, "P10M");//我们默认持续时间10分钟
226 | event.put(CalendarContract.Events.RRULE, rrlue);//重复规则,https://www.cnblogs.com/ice5/p/14023771.html
227 | // event.put(CalendarContract.Events.HAS_ALARM, true);//是否含有提醒,这个不用设置,关联Reminders是会自动设置为true
228 | // event.put(CalendarContract.Events.ALLOWED_REMINDERS, CalendarContract.Reminders.METHOD_ALERT);//是否提示,默认0,1
229 | event.put(CalendarContract.Events.DTSTART, dtStart);//提醒开始时间
230 | event.put(CalendarContract.Events.EVENT_TIMEZONE, TimeZone.getDefault().getID()); //这个是时区,必须有,
231 | Uri newEvent;
232 | if (eventId <= 0) {
233 | //添加事件
234 | newEvent = context.getContentResolver().insert(calanderEventURL, event);
235 | } else {
236 | Uri uri = ContentUris.withAppendedId(calanderEventURL, eventId);
237 | return context.getContentResolver().update(uri, event, null, null);
238 | }
239 | if (null == newEvent) {
240 | return -1;
241 | }
242 |
243 | //事件提醒的设定
244 | ContentValues values = new ContentValues();
245 | values.put(CalendarContract.Reminders.EVENT_ID, ContentUris.parseId(newEvent));
246 | values.put(CalendarContract.Reminders.METHOD, CalendarContract.Reminders.METHOD_ALERT);
247 | if (context.getContentResolver().insert(calanderRemiderURL, values) == null) {
248 | return -1;
249 | }
250 | return 0;
251 | }
252 |
253 | /**
254 | * 删除日历事件
255 | */
256 | public static int deleteCalendarEvent(Activity context, long id) {
257 | return context.getContentResolver().delete(ContentUris.withAppendedId(CalendarContract.Events.CONTENT_URI, id), null, null);
258 | }
259 |
260 | //必须的权限:
261 | private void createAlarm(Activity activity, String message, int hour, int minutes, int resId) {
262 | ArrayList testDays = new ArrayList<>();
263 | testDays.add(Calendar.MONDAY);//周一
264 | testDays.add(Calendar.TUESDAY);//周二
265 | testDays.add(Calendar.FRIDAY);//周五
266 |
267 | String packageName = activity.getPackageName();
268 | Uri ringtoneUri = Uri.parse("android.resource://" + packageName + "/" + resId);
269 |
270 | Intent intent = new Intent(AlarmClock.ACTION_SET_ALARM)//ACTION_DISMISS_ALARM
271 | //闹钟的小时
272 | .putExtra(AlarmClock.EXTRA_HOUR, hour)
273 | //闹钟的分钟
274 | .putExtra(AlarmClock.EXTRA_MINUTES, minutes)
275 | //响铃时提示的信息
276 | .putExtra(AlarmClock.EXTRA_MESSAGE, message)
277 | //用于指定该闹铃触发时是否振动
278 | .putExtra(AlarmClock.EXTRA_VIBRATE, true)
279 | //一个 content: URI,用于指定闹铃使用的铃声,也可指定 VALUE_RINGTONE_SILENT 以不使用铃声。
280 | //如需使用默认铃声,则无需指定此 extra。
281 | .putExtra(AlarmClock.EXTRA_RINGTONE, ringtoneUri)
282 | //对于一次性闹铃,无需指定此 extra
283 | .putExtra(AlarmClock.EXTRA_DAYS, testDays)
284 | //如果为true,则调用startActivity()不会进入手机的闹钟设置界面
285 | .putExtra(AlarmClock.EXTRA_SKIP_UI, true);
286 | if (intent.resolveActivity(activity.getPackageManager()) != null) {
287 | activity.startActivity(intent);
288 | }
289 | }
290 | }
291 |
--------------------------------------------------------------------------------