打开手机自带的应用商店

需求背景:
因为各种原因,需要打开手机自带的应用商店

核心代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42

import android.content.Context
import android.content.Intent
import android.net.Uri

object MarketUtils {
const val XIAOMI_MARKET = "com.xiaomi.market"
const val HUAWEI_MARKET = "com.huawei.appmarket"
const val OPPO_MARKET = "com.oppo.market"
const val OPPO_MARKET2 = "com.heytap.market"
const val VIVO_MARKET = "com.bbk.appstore"
const val MEIZU_MARKET = "com.meizu.mstore"
const val YYB_MARKET = "com.tencent.android.qqdownloader"

fun startTargetMarket(context: Context, deepLink: String, packageName: String) {
//"deeplink": "market://details?id=com.taobao.taobao&..."
try {
val uri = Uri.parse(deepLink)
val intent = Intent(Intent.ACTION_VIEW, uri)
intent.setPackage(packageName)
context.startActivity(intent)
} catch (e: Exception) {
e.printStackTrace()
val uri = Uri.parse(deepLink)
val intent = Intent(Intent.ACTION_VIEW, uri)
context.startActivity(intent)
}
}

/**
* 跳转到腾讯应用宝
*/
private fun startTencentMarket(context: Context, deepLink: String) {
val uri: Uri = Uri.parse(deepLink) // "market://details?id=com.taobao.taobao&..."
val intent = Intent(Intent.ACTION_VIEW, uri)
intent.setClassName(
"com.tencent.android.qqdownloader",
"com.tencent.pangu.link.LinkProxyActivity"
)
context.startActivity(intent)
}
}

测试代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
private fun initView() {
//
val deepLink =
"market://details?id=com.taobao.taobao&ref=&caller=com.taobao.taobao&token=OWNjY2YyNGNiYzYwYTNkMCMxNjQ5NjQ2NTA0OTA5IzEjY29tLnRhb2Jhby50YW9iYW8jS29iZS8yNEAwZjY1NGI3ZGZlZWJlZWI2NTk3MTkyNWE4ZDFhZTc1Zg==&style=1&m=adapi_2049933&tk_con=eyJ0cmFja0lkIjoiN2VkOGI0ZWM2YjAwN2FmNjkzZDc0ODJkYTBlNzgyMDMiLCJkZXZpY2VJZCI6Ijg2Mzg5NDAzMjE1ODg3NyIsImFwcElkIjoiMjMzNCIsInZlcnNpb25JZCI6IjAiLCJlbnRlcklkIjoiMTQiLCJwYWdlSWQiOiIxMDAwMDEiLCJhYiI6IjFfMF85IiwiYWRJZCI6IjQwNzA2ODY5OCIsInQiOiIxNjQ5NjQ2NTA0OTA3IiwidiI6InYxIn0%3D&tk_ref=%7B%22adId%22%3A%22407068698%22%2C%22trackId%22%3A%227ed8b4ec6b007af693d7482da0e78203%22%7D"
xiaomi_market.setOnClickListener {
MarketUtils.startTargetMarket(this, deepLink, MarketUtils.XIAOMI_MARKET)
}
huawei_market.setOnClickListener {
MarketUtils.startTargetMarket(this, deepLink, MarketUtils.HUAWEI_MARKET)
}
oppo_market.setOnClickListener {
if (android.os.Build.VERSION.SDK_INT >= 28) {
MarketUtils.startTargetMarket(this, deepLink, MarketUtils.OPPO_MARKET2)
} else {
MarketUtils.startTargetMarket(this, deepLink, MarketUtils.OPPO_MARKET)
}
}
vivo_market.setOnClickListener {
MarketUtils.startTargetMarket(this, deepLink, MarketUtils.VIVO_MARKET)
}
meizu_market.setOnClickListener {
MarketUtils.startTargetMarket(this, deepLink, MarketUtils.MEIZU_MARKET)
}
yyb_market.setOnClickListener {
MarketUtils.startTargetMarket(this, deepLink, MarketUtils.YYB_MARKET)
}
}

自定义TextView实现多个文案切换炫酷动画

当显示2个或2个以上文案时,每隔2秒切换气泡文案
4C3FBC04FF667DAAEF17AA6B8F8F7A46

核心实现代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115

import android.animation.ValueAnimator
import android.content.Context
import android.util.AttributeSet
import android.util.Log
import androidx.appcompat.widget.AppCompatTextView

class TextViewSwitcher @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0
) : AppCompatTextView(context, attrs, defStyleAttr) {

private var strs: List<String>? = null
private var startPos: Int = 0
private val timeStep = 2000L // 2S
private val TAG = "TextViewSwitcher"

private val showNext = Runnable {
showNextStr()
}

override fun onAttachedToWindow() {
Log.d(TAG, "onAttachedToWindow: ")
super.onAttachedToWindow()
val size = strs?.size ?: 0
if (size > 1) {
handler.postDelayed(showNext, timeStep)
}
}

override fun onDetachedFromWindow() {
Log.d(TAG, "onDetachedFromWindow: ")
handler.removeCallbacks(showNext)
super.onDetachedFromWindow()
}

fun setTextList(strs: List<String>?, startPos: Int = 0) {
Log.d(TAG, "setTextList: ")
if (strs.isNullOrEmpty()) return
this.strs = strs
this.startPos = startPos
if (strs.size == 1) {
text = strs[0]
} else {
this.startPos = startPos % strs.size
text = strs[this.startPos]
}
}

private fun showNextStr() {
var startPos = this.startPos + 1
val size = strs?.size ?: 0
if (size <= 1) return
if (startPos >= size) startPos %= size

this.startPos = startPos
changeTextWithAnimator(this, strs?.get(startPos))

handler.postDelayed(showNext, timeStep)
}

private fun changeTextWithAnimator(
textView: AppCompatTextView?,
nextContent: String?
) {
if (textView != null) {
val animator = ValueAnimator.ofFloat(0f, 2f)
animator.duration = 400
var changed = false
textView.pivotX = 0f
val height = textView.measuredHeight
if (height > 0) {
textView.pivotY = height.toFloat()
}

val startWidth = textView.measuredWidth
var endWidth = 0
val params = textView.layoutParams
animator.addUpdateListener { animation ->
val value = animation.animatedValue as Float
when {
value < 1f -> {
textView.rotation = 360 - value * 60
textView.alpha = 1 - value
}
value > 1f -> {
textView.alpha = value - 1
textView.rotation = 360 - (2 - value) * 60
if (!changed) {
changed = true
textView.text = nextContent

val measureSpec = MeasureSpec.makeMeasureSpec(
0,
MeasureSpec.UNSPECIFIED
)
textView.measure(measureSpec, measureSpec)
endWidth = textView.measuredWidth

Log.d(TAG, "changeTextWithAnimator: endWidth=$endWidth")
} else {
if (endWidth > 0) {
params.width =
(startWidth + (endWidth - startWidth) * (value - 1)).toInt()
textView.layoutParams = params
}
}
}
}
}
animator.start()
}
}
}

由于动画要在顶部浮层,这样动画才能不被父类容器的大小所限制和切割,所以,直接在PopWindow中显示。
具体代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.PopupWindow

object HomePromptView {
@JvmStatic
fun showTipPopView(view: View, typedStr: String?): PopupWindow {

val rootView = LayoutInflater.from(view.context).inflate(R.layout.home_prompt_layout, null)
val promptTv = rootView.findViewById<TextViewSwitcher>(R.id.tv_prompt)
promptTv.setTextList(typedStr?.split("|"))
rootView.isClickable = false

// PopWindow
val popTipWid = PopupWindow(
rootView,
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT
)
popTipWid.isTouchable = false

// android.view.WindowManager$BadTokenException:
// Unable to add window -- token null is not valid;
// is your activity running?
try {
popTipWid.showAtLocation(view.rootView, 0, 0, 0)
layoutPromptLocation(promptTv, view)
// popTipWid.showAsDropDown(view, UiUtils.dip2px(39), -UiUtils.dip2px(48))
view.addOnLayoutChangeListener { view, i, i2, i3, i4, i5, i6, i7, i8 ->
layoutPromptLocation(promptTv, view)
}
} catch (e: Exception) {
e.printStackTrace()
}
return popTipWid
}


private fun layoutPromptLocation(
promptTv: TextViewSwitcher,
view: View
) {
try {
val params = promptTv.layoutParams as ViewGroup.MarginLayoutParams
val location = IntArray(2)
view.getLocationInWindow(location)
params.topMargin =
location[1] - UiUtils.getStatusBarHeight(view.context) + UiUtils.dip2px(4)
params.leftMargin = location[0] + UiUtils.dip2px(25)
promptTv.layoutParams = params
} catch (e: Exception) {
e.printStackTrace()
}
}

@JvmStatic
fun dismissTipPopView(popTipWid: PopupWindow?) {
popTipWid?.dismiss()
}

}

添加布局代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/transparent">

<******.TextViewSwitcher
android:id="@+id/tv_prompt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/common_ui_shape_red_heavy_prompt"
android:maxLines="1"
android:paddingStart="5dp"
android:paddingTop="1.5dp"
android:paddingEnd="5dp"
android:paddingBottom="1.5dp"
android:textColor="@color/white"
android:textSize="10sp"
tools:text="硬核安利">

</******.TextViewSwitcher>

</FrameLayout>

drawable:

1
2
3
4
5
6
7
8
9
10
11
12
13
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<corners
android:bottomRightRadius="9dp"
android:topLeftRadius="9dp"
android:topRightRadius="9dp" />
<solid android:color="#FF5E79" />
<stroke
android:width="0.5dp"
android:color="@color/white" />
</shape>

SpannableString 之显示查看全文

SpannableString 之显示查看全文

显示内容超出规定的行数之后,显示 展开收起

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
import android.content.Context;
import android.graphics.Color;
import android.os.Build;
import android.text.Layout;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.StaticLayout;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.style.AlignmentSpan;
import android.text.style.ClickableSpan;
import android.text.style.StyleSpan;
import android.util.AttributeSet;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.Transformation;

import androidx.annotation.ColorInt;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.AppCompatTextView;

import java.lang.reflect.Field;

/**
* Description : 显示展开和收起
* PackageName : com.mrtrying.widget
* Created by mrtrying on 2019/4/17 17:21.
* e_mail : ztanzeyu@gmail.com
*/
public class ExpandableTextView extends AppCompatTextView {
private static final String TAG = ExpandableTextView.class.getSimpleName();

public static final String ELLIPSIS_STRING = new String(new char[]{'\u2026'});
private static final String DEFAULT_OPEN_SUFFIX = " 展开";
private static final String DEFAULT_CLOSE_SUFFIX = " 收起";
volatile boolean animating = false;
boolean isClosed = false;
private int mMaxLines = getMaxLines();
private int initWidth = 0;
private CharSequence originalText;

private SpannableStringBuilder mOpenSpannableStr, mCloseSpannableStr;

private boolean hasAnimation = false;
private Animation mOpenAnim, mCloseAnim;
private int mOpenHeight, mCLoseHeight;
private boolean mExpandable;
private boolean mCloseInNewLine;
@Nullable
private SpannableString mOpenSuffixSpan, mCloseSuffixSpan;
private String mOpenSuffixStr = DEFAULT_OPEN_SUFFIX;
private String mCloseSuffixStr = "";
private int mOpenSuffixColor, mCloseSuffixColor;
private int mNormalColor = Color.parseColor("#FF222222");

private View.OnClickListener mOnClickListener;

private CharSequenceToSpannableHandler mCharSequenceToSpannableHandler;
private IOnOpenSuffixSpanListener onOpenSuffixSpanListener;

public ExpandableTextView(Context context) {
super(context);
initialize();
}

public ExpandableTextView(Context context, AttributeSet attrs) {
super(context, attrs);
initialize();
}

public ExpandableTextView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
initialize();
}

/**
* 初始化
*/
private void initialize() {
mOpenSuffixColor = mCloseSuffixColor = Color.parseColor("#FF0091FF");
setMovementMethod(CustomLinkMovementMethod.getInstance());
// setIncludeFontPadding(false);
updateOpenSuffixSpan();
updateCloseSuffixSpan();
}

@Override
public boolean hasOverlappingRendering() {
return false;
}

public void setOriginalText(CharSequence originalText) {
this.originalText = originalText;
mExpandable = false;
mCloseSpannableStr = new SpannableStringBuilder();
final int maxLines = mMaxLines;
SpannableStringBuilder tempText = charSequenceToSpannable(originalText);
mOpenSpannableStr = charSequenceToSpannable(originalText);

if (maxLines != -1) {
Layout layout = createStaticLayout(tempText);
mExpandable = layout.getLineCount() > maxLines;
if (mExpandable) {
//拼接展开内容
if (mCloseInNewLine) {
mOpenSpannableStr.append("\n");
}
if (mCloseSuffixSpan != null) {
mOpenSpannableStr.append(mCloseSuffixSpan);
}
//计算原文截取位置
int endPos = layout.getLineEnd(maxLines - 1);
if (originalText.length() <= endPos) {
mCloseSpannableStr = charSequenceToSpannable(originalText);
} else {
mCloseSpannableStr = charSequenceToSpannable(originalText.subSequence(0, endPos));
}
SpannableStringBuilder tempText2 = charSequenceToSpannable(mCloseSpannableStr).append(ELLIPSIS_STRING);
if (mOpenSuffixSpan != null) {
tempText2.append(mOpenSuffixSpan);
}
//循环判断,收起内容添加展开后缀后的内容
Layout tempLayout = createStaticLayout(tempText2);
while (tempLayout.getLineCount() > maxLines) {
int lastSpace = mCloseSpannableStr.length() - 1;
if (lastSpace == -1) {
break;
}
if (originalText.length() <= lastSpace) {
mCloseSpannableStr = charSequenceToSpannable(originalText);
} else {
mCloseSpannableStr = charSequenceToSpannable(originalText.subSequence(0, lastSpace));
}
tempText2 = charSequenceToSpannable(mCloseSpannableStr).append(ELLIPSIS_STRING);
if (mOpenSuffixSpan != null) {
tempText2.append(mOpenSuffixSpan);
}
tempLayout = createStaticLayout(tempText2);

}
int lastSpace = mCloseSpannableStr.length();
// - mOpenSuffixSpan.length();
// if(lastSpace >= 0 && originalText.length() > lastSpace){
// CharSequence redundantChar = originalText.subSequence(lastSpace, lastSpace + mOpenSuffixSpan.length());
// int offset = hasEnCharCount(redundantChar) - hasEnCharCount(mOpenSuffixSpan) + 1;
// lastSpace = offset <= 0 ? lastSpace : lastSpace - offset;
// mCloseSpannableStr = charSequenceToSpannable(originalText.subSequence(0, lastSpace));
// }
//计算收起的文本高度
mCLoseHeight = tempLayout.getHeight() + getPaddingTop() + getPaddingBottom();
// mCloseSpannableStr.setSpan(new ClickableSpan() {
// @Override
// public void onClick(@NonNull View widget) {
// if (mOnClickListener != null) {
// mOnClickListener.onClick(widget);
// }
// }
//
// @Override
// public void updateDrawState(@NonNull TextPaint ds) {
// super.updateDrawState(ds);
// ds.setColor(mNormalColor);
// ds.setUnderlineText(false);
// }
// }, 0, length, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
}
}
isClosed = mExpandable;
if (mExpandable) {
// mCloseSpannableStr.setSpan(new ClickableSpan() {
// @Override
// public void onClick(@NonNull View widget) {
// if(listener!=null){
// listener.onClick(widget);
// }
// }
//
// @Override
// public void updateDrawState(@NonNull TextPaint ds) {
// super.updateDrawState(ds);
// ds.setColor(mNormalColor);
// ds.setUnderlineText(false);
// }
// }, 0, mCloseSpannableStr.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
mCloseSpannableStr.append(ELLIPSIS_STRING);
if (mOpenSuffixSpan != null) {
mCloseSpannableStr.append(mOpenSuffixSpan);
}
setMovementMethod(CustomLinkMovementMethod.getInstance());
setClickable(false);
setLongClickable(false);
setText(mCloseSpannableStr);

} else {
// mOpenSpannableStr.setSpan(new ClickableSpan() {
// @Override
// public void onClick(@NonNull View widget) {
// if (mOnClickListener != null) {
// mOnClickListener.onClick(widget);
// }
// }
//
// @Override
// public void updateDrawState(@NonNull TextPaint ds) {
// super.updateDrawState(ds);
// ds.setColor(mNormalColor);
// ds.setUnderlineText(false);
// }
// }, 0, mOpenSpannableStr.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
setText(mOpenSpannableStr);
}
}

private int hasEnCharCount(CharSequence str) {
int count = 0;
if (!TextUtils.isEmpty(str)) {
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if (c >= ' ' && c <= '~') {
count++;
}
}
}
return count;
}

private void switchOpenClose() {
if (mExpandable) {
isClosed = !isClosed;
if (isClosed) {
close();
} else {
open();
}
}
}

/**
* 设置是否有动画
*
* @param hasAnimation
*/
public void setHasAnimation(boolean hasAnimation) {
this.hasAnimation = hasAnimation;
}

/**
* 展开
*/
private void open() {
if (hasAnimation) {
Layout layout = createStaticLayout(mOpenSpannableStr);
mOpenHeight = layout.getHeight() + getPaddingTop() + getPaddingBottom();
executeOpenAnim();
} else {
ExpandableTextView.super.setMaxLines(Integer.MAX_VALUE);
setText(mOpenSpannableStr);
if (mOpenCloseCallback != null) {
mOpenCloseCallback.onOpen();
}
}
}

/**
* 收起
*/
private void close() {
if (hasAnimation) {
executeCloseAnim();
} else {
ExpandableTextView.super.setMaxLines(mMaxLines);
setText(mCloseSpannableStr);
if (mOpenCloseCallback != null) {
mOpenCloseCallback.onClose();
}
}
}

/**
* 执行展开动画
*/
private void executeOpenAnim() {
//创建展开动画
if (mOpenAnim == null) {
mOpenAnim = new ExpandCollapseAnimation(this, mCLoseHeight, mOpenHeight);
mOpenAnim.setFillAfter(true);
mOpenAnim.setAnimationListener(new Animation.AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
ExpandableTextView.super.setMaxLines(Integer.MAX_VALUE);
setText(mOpenSpannableStr);
}

@Override
public void onAnimationEnd(Animation animation) {
// 动画结束后textview设置展开的状态
getLayoutParams().height = mOpenHeight;
requestLayout();
animating = false;
}

@Override
public void onAnimationRepeat(Animation animation) {

}
});
}

if (animating) {
return;
}
animating = true;
clearAnimation();
// 执行动画
startAnimation(mOpenAnim);
}

/**
* 执行收起动画
*/
private void executeCloseAnim() {
//创建收起动画
if (mCloseAnim == null) {
mCloseAnim = new ExpandCollapseAnimation(this, mOpenHeight, mCLoseHeight);
mCloseAnim.setFillAfter(true);
mCloseAnim.setAnimationListener(new Animation.AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {

}

@Override
public void onAnimationEnd(Animation animation) {
animating = false;
ExpandableTextView.super.setMaxLines(mMaxLines);
setText(mCloseSpannableStr);
getLayoutParams().height = mCLoseHeight;
requestLayout();
}

@Override
public void onAnimationRepeat(Animation animation) {

}
});
}

if (animating) {
return;
}
animating = true;
clearAnimation();
// 执行动画
startAnimation(mCloseAnim);
}

/**
* @param spannable
* @return
*/
private Layout createStaticLayout(SpannableStringBuilder spannable) {
int contentWidth = initWidth - getPaddingLeft() - getPaddingRight();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
StaticLayout.Builder builder = StaticLayout.Builder.obtain(spannable, 0, spannable.length(), getPaint(), contentWidth);
builder.setAlignment(Layout.Alignment.ALIGN_NORMAL);
builder.setIncludePad(getIncludeFontPadding());
builder.setLineSpacing(getLineSpacingExtra(), getLineSpacingMultiplier());
return builder.build();
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
return new StaticLayout(spannable, getPaint(), contentWidth, Layout.Alignment.ALIGN_NORMAL,
getLineSpacingMultiplier(), getLineSpacingExtra(), getIncludeFontPadding());
} else {
return new StaticLayout(spannable, getPaint(), contentWidth, Layout.Alignment.ALIGN_NORMAL,
getFloatField("mSpacingMult", 1f), getFloatField("mSpacingAdd", 0f), getIncludeFontPadding());
}
}

private float getFloatField(String fieldName, float defaultValue) {
float value = defaultValue;
if (TextUtils.isEmpty(fieldName)) {
return value;
}
try {
// 获取该类的所有属性值域
Field[] fields = this.getClass().getDeclaredFields();
for (Field field : fields) {
if (TextUtils.equals(fieldName, field.getName())) {
value = field.getFloat(this);
break;
}
}
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return value;
}


/**
* @param charSequence
* @return
*/
private SpannableStringBuilder charSequenceToSpannable(@NonNull CharSequence charSequence) {
SpannableStringBuilder spannableStringBuilder = null;
if (mCharSequenceToSpannableHandler != null) {
spannableStringBuilder = mCharSequenceToSpannableHandler.charSequenceToSpannable(charSequence);
}
if (spannableStringBuilder == null) {
spannableStringBuilder = new SpannableStringBuilder(charSequence);
}
return spannableStringBuilder;
}

/**
* 初始化TextView的可展示宽度
*
* @param width
*/
public void initWidth(int width) {
initWidth = width;
}

@Override
public void setMaxLines(int maxLines) {
this.mMaxLines = maxLines;
super.setMaxLines(maxLines);
}

/**
* 设置展开后缀text
*
* @param openSuffix
*/
public void setOpenSuffix(String openSuffix, IOnOpenSuffixSpanListener onOpenSuffixSpanListener) {
mOpenSuffixStr = openSuffix;
this.onOpenSuffixSpanListener = onOpenSuffixSpanListener;
updateOpenSuffixSpan();
}

public void setNewOpenSuffix(String openSuffix, IOnOpenSuffixSpanListener onOpenSuffixSpanListener) {
mOpenSuffixStr = openSuffix;
this.onOpenSuffixSpanListener = onOpenSuffixSpanListener;
updateNewOpenSuffixSpan();
}


/**
* 设置展开后缀文本颜色
*
* @param openSuffixColor
*/
public void setOpenSuffixColor(@ColorInt int openSuffixColor) {
mOpenSuffixColor = openSuffixColor;
updateOpenSuffixSpan();
}

/**
* 设置收起后缀text
*
* @param closeSuffix
*/
public void setCloseSuffix(String closeSuffix) {
mCloseSuffixStr = closeSuffix;
updateCloseSuffixSpan();
}

/**
* 设置收起后缀文本颜色
*
* @param closeSuffixColor
*/
public void setCloseSuffixColor(@ColorInt int closeSuffixColor) {
mCloseSuffixColor = closeSuffixColor;
updateCloseSuffixSpan();
}

/**
* 收起后缀是否另起一行
*
* @param closeInNewLine
*/
public void setCloseInNewLine(boolean closeInNewLine) {
mCloseInNewLine = closeInNewLine;
updateCloseSuffixSpan();
}

public interface IOnOpenSuffixSpanListener {
void onClick();
}

/**
* 更新展开后缀Spannable
*/
private void updateOpenSuffixSpan() {
if (TextUtils.isEmpty(mOpenSuffixStr)) {
mOpenSuffixSpan = null;
return;
}
mOpenSuffixSpan = new SpannableString(mOpenSuffixStr);

mOpenSuffixSpan.setSpan(new ClickableSpan() {
@Override
public void onClick(@NonNull View widget) {
if (onOpenSuffixSpanListener != null) {
onOpenSuffixSpanListener.onClick();
} else {
switchOpenClose();
}
}

@Override
public void updateDrawState(@NonNull TextPaint ds) {
super.updateDrawState(ds);
ds.setColor(mOpenSuffixColor);
ds.setUnderlineText(false);
}
}, 0, mOpenSuffixStr.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}

private void updateNewOpenSuffixSpan() {
if (TextUtils.isEmpty(mOpenSuffixStr)) {
mOpenSuffixSpan = null;
return;
}
mOpenSuffixSpan = new SpannableString(mOpenSuffixStr);

mOpenSuffixSpan.setSpan(new ClickableSpan() {
@Override
public void onClick(@NonNull View widget) {
if (onOpenSuffixSpanListener != null) {
onOpenSuffixSpanListener.onClick();
} else {
switchOpenClose();
}
}

@Override
public void updateDrawState(@NonNull TextPaint ds) {
super.updateDrawState(ds);
ds.setColor(mOpenSuffixColor);
ds.setUnderlineText(false);
}
}, 0, mOpenSuffixStr.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}


/**
* 更新收起后缀Spannable
*/
private void updateCloseSuffixSpan() {
if (TextUtils.isEmpty(mCloseSuffixStr)) {
mCloseSuffixSpan = null;
return;
}
mCloseSuffixSpan = new SpannableString(mCloseSuffixStr);
mCloseSuffixSpan.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), 0, mCloseSuffixStr.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
if (mCloseInNewLine) {
AlignmentSpan alignmentSpan = new AlignmentSpan.Standard(Layout.Alignment.ALIGN_OPPOSITE);
mCloseSuffixSpan.setSpan(alignmentSpan, 0, 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
mCloseSuffixSpan.setSpan(new ClickableSpan() {
@Override
public void onClick(@NonNull View widget) {
switchOpenClose();
}

@Override
public void updateDrawState(@NonNull TextPaint ds) {
super.updateDrawState(ds);
ds.setColor(mCloseSuffixColor);
ds.setUnderlineText(false);
}
}, 1, mCloseSuffixStr.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}

public void setContentClickListener(View.OnClickListener onClickListener) {
mOnClickListener = onClickListener;
}

public OpenAndCloseCallback mOpenCloseCallback;

public void setOpenAndCloseCallback(OpenAndCloseCallback callback) {
this.mOpenCloseCallback = callback;
}

public interface OpenAndCloseCallback {
void onOpen();

void onClose();
}

/**
* 设置文本内容处理
*
* @param handler
*/
public void setCharSequenceToSpannableHandler(CharSequenceToSpannableHandler handler) {
mCharSequenceToSpannableHandler = handler;
}

public interface CharSequenceToSpannableHandler {
@NonNull
SpannableStringBuilder charSequenceToSpannable(CharSequence charSequence);
}

class ExpandCollapseAnimation extends Animation {
private final View mTargetView;//动画执行view
private final int mStartHeight;//动画执行的开始高度
private final int mEndHeight;//动画结束后的高度

ExpandCollapseAnimation(View target, int startHeight, int endHeight) {
mTargetView = target;
mStartHeight = startHeight;
mEndHeight = endHeight;
setDuration(400);
}

@Override
protected void applyTransformation(float interpolatedTime, Transformation t) {
mTargetView.setScrollY(0);
//计算出每次应该显示的高度,改变执行view的高度,实现动画
mTargetView.getLayoutParams().height = (int) ((mEndHeight - mStartHeight) * interpolatedTime + mStartHeight);
mTargetView.requestLayout();
}
}

}

控件使用方式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
val tvContent = holder.getView<ExpandableTextView>(R.id.tv_content)
tvContent.movementMethod = LinkMovementMethod.getInstance()
tvContent.isClickable = false
tvContent.isLongClickable = false
val builder = SpannableStringBuilder()
if (item.spoiler && spoilerEnable) builder.append(" ")
if (item.talkList != null && item.talkList.size > 0) {
val talk = item.talkList[0]
val startIndex = builder.length
builder.append("#")
builder.append(talk.name)
builder.append(" ")
val clickableSpan = object : ClickableSpan() {
override fun onClick(view: View) {
talkClickListener?.invoke(item, holder.adapterPosition)
}

override fun updateDrawState(ds: TextPaint) {
ds.color =
if (talk.enable) Color.parseColor("#1890FF")
else Color.parseColor("#85888F")
}
}
builder.setSpan(
clickableSpan,
startIndex,
builder.length,
Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
)
}
builder.append(it)
tvContent.initWidth(UiUtils.getScreenWidth() - UiUtils.dip2px(16 * 2 + 36 + 9))
tvContent.setOpenSuffix("查看全文") {
listener.invoke(item, null)
}
tvContent.setOriginalText(builder)

SettingsHelper

SettingsHelper

SettingsHelper 自启动设置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.provider.Settings
import android.util.Log

/**
* 跳转自启动页面
*/
object AutoStartHelper {
private val hashMap = mutableMapOf<String, List<String>>().apply {
put(
"Xiaomi", listOf(
"com.miui.securitycenter/com.miui.permcenter.autostart.AutoStartManagementActivity",
"com.miui.securitycenter"
)
)
put(
"samsung", listOf(
"com.samsung.android.sm_cn/com.samsung.android.sm.ui.ram.AutoRunActivity",
"com.samsung.android.sm_cn/com.samsung.android.sm.ui.appmanagement.AppManagementActivity",
"com.samsung.android.sm_cn/com.samsung.android.sm.ui.cstyleboard.SmartManagerDashBoardActivity",
"com.samsung.android.sm_cn/.ui.ram.RamActivity",
"com.samsung.android.sm_cn/.app.dashboard.SmartManagerDashBoardActivity",
"com.samsung.android.sm/com.samsung.android.sm.ui.ram.AutoRunActivity",
"com.samsung.android.sm/com.samsung.android.sm.ui.appmanagement.AppManagementActivity",
"com.samsung.android.sm/com.samsung.android.sm.ui.cstyleboard.SmartManagerDashBoardActivity",
"com.samsung.android.sm/.ui.ram.RamActivity",
"com.samsung.android.sm/.app.dashboard.SmartManagerDashBoardActivity",
"com.samsung.android.lool/com.samsung.android.sm.ui.battery.BatteryActivity",
"com.samsung.android.sm_cn",
"com.samsung.android.sm"
)
)
put(
"HUAWEI", listOf(
"com.huawei.systemmanager/.startupmgr.ui.StartupNormalAppListActivity",
"com.huawei.systemmanager/.appcontrol.activity.StartupAppControlActivity",
"com.huawei.systemmanager/.optimize.process.ProtectActivity",
"com.huawei.systemmanager/.optimize.bootstart.BootStartActivity",
// "com.huawei.systemmanager/com.huawei.permissionmanager.ui.MainActivity", // 这个是隐私-权限管理,但是没有自启动权限!!!
"com.android.settings/com.android.settings.Settings$" + "AppAndNotificationDashboardActivity", // 鸿蒙系统,应用和服务,列表中有应用启动管理
"com.huawei.systemmanager"
)
)
put(
"vivo", listOf(
"com.iqoo.secure/.ui.phoneoptimize.BgStartUpManager",
"com.vivo.permissionmanager/.activity.BgStartUpManagerActivity",
"com.vivo.permissionmanager/.activity.SoftPermissionDetailActivity",
"com.iqoo.secure/.safeguard.PurviewTabActivity",
"com.iqoo.secure",
"com.vivo.permissionmanager"
)
)
put(
"Meizu", listOf(
"com.meizu.safe/.permission.SmartBGActivity",
"com.meizu.safe/.permission.PermissionMainActivity",
"com.meizu.safe"
)
)
put(
"OPPO", listOf(
"com.coloros.safecenter/.startupapp.StartupAppListActivity",
"com.coloros.safecenter/.permission.startup.StartupAppListActivity",
"com.oppo.safe/.permission.startup.StartupAppListActivity",
"com.coloros.oppoguardelf/com.coloros.powermanager.fuelgaue.PowerUsageModelActivity",
"com.coloros.safecenter/com.coloros.privacypermissionsentry.PermissionTopActivity",
"com.coloros.safecenter",
"com.oppo.safe",
"com.coloros.oppoguardelf"
)
)
put(
"oneplus", listOf(
"com.oneplus.security/.chainlaunch.view.ChainLaunchAppListActivity",
"com.oneplus.security"
)
)
put(
"letv", listOf(
"com.letv.android.letvsafe/.AutobootManageActivity",
"com.letv.android.letvsafe/.BackgroundAppManageActivity",
"com.letv.android.letvsafe"
)
)
put(
"zte", listOf(
"com.zte.heartyservice/.autorun.AppAutoRunManager",
"com.zte.heartyservice"
)
)
//金立
put(
"F", listOf(
"com.gionee.softmanager/.MainActivity",
"com.gionee.softmanager"
)
)
//以下为未确定(厂商名也不确定)
put(
"smartisanos", listOf(
"com.smartisanos.security/.invokeHistory.InvokeHistoryActivity",
"com.smartisanos.security"
)
)
//360
put(
"360", listOf(
"com.yulong.android.coolsafe/.ui.activity.autorun.AutoRunListActivity",
"com.yulong.android.coolsafe"
)
)
//360
put(
"ulong", listOf(
"com.yulong.android.coolsafe/.ui.activity.autorun.AutoRunListActivity",
"com.yulong.android.coolsafe"
)
)
//酷派
put(
"coolpad" /*厂商名称不确定是否正确*/, listOf(
"com.yulong.android.security/com.yulong.android.seccenter.tabbarmain",
"com.yulong.android.security"
)
)
//联想
put(
"lenovo" /*厂商名称不确定是否正确*/, listOf(
"com.lenovo.security/.purebackground.PureBackgroundActivity",
"com.lenovo.security"
)
)
put(
"htc" /*厂商名称不确定是否正确*/, listOf(
"com.htc.pitroad/.landingpage.activity.LandingPageActivity",
"com.htc.pitroad"
)
)
//华硕
put(
"asus" /*厂商名称不确定是否正确*/, listOf(
"com.asus.mobilemanager/.MainActivity",
"com.asus.mobilemanager"
)
)
//酷派
put(
"YuLong", listOf(
"com.yulong.android.softmanager/.SpeedupActivity",
"com.yulong.android.security/com.yulong.android.seccenter.tabbarmain",
"com.yulong.android.security"
)
)
}

fun startAutoBootSetting(context: Context?) {
Log.e("AutoStartHelper", "当前手机型号为:" + Build.MANUFACTURER)
var result = false

run start0@{
for ((manufacturer, componentNameList) in hashMap) {
if (Build.MANUFACTURER.equals(manufacturer, ignoreCase = true)) {
for (actName in componentNameList) {
try {
var intent: Intent? = null
if (actName.contains("/")) {
intent = Intent()
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
intent.component = ComponentName.unflattenFromString(actName)
if (actName.contains("SoftPermissionDetailActivity")) {
intent.putExtra("packagename", context?.packageName)
}
}
// else {
// // 跳转到对应的安全管家/安全中心
// intent = context?.packageManager?.getLaunchIntentForPackage(actName)
// }
intent?.let {
context?.startActivity(intent)
result = true
return@start0
}
} catch (e: Exception) {
e.printStackTrace()
}
}
}
}
}

if (!result) {
try {
// 跳转到app详情设置
val intent = Intent()
intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
intent.action = Settings.ACTION_APPLICATION_DETAILS_SETTINGS
intent.data = Uri.fromParts("package", context?.packageName, null)
context?.startActivity(intent)
} catch (e: Exception) {
e.printStackTrace()
}
}
}

SpannableString 之居中显示 ImageSpan

自定义布局:SpannableString 之居中显示 ImageSpan

image-20220104185114603
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class CenteredImageSpan(context: Context, drawableRes: Int) : ImageSpan(context, drawableRes) {
override fun draw(
canvas: Canvas,
text: CharSequence,
start: Int,
end: Int,
x: Float,
top: Int,
y: Int,
bottom: Int,
paint: Paint
) {
// image to draw
val b = drawable
// font metrics of text to be replaced
val fm = paint.fontMetricsInt
var transY = ((y + fm.descent + y + fm.ascent) / 2 - b.bounds.bottom / 2)
// to check the last line.(当 image 在单独一行显示时可能会存在这个问题)
if (transY > bottom - b.bounds.bottom) transY = bottom - b.bounds.bottom
canvas.save()
canvas.translate(x, transY.toFloat())
b.draw(canvas)
canvas.restore()
}
}
1
2
3
4
5
6
7
8
9
10
11
val spanStr = SpannableStringBuilder()
spanStr.append("# ")
spanStr.append(title)
val imageSpan = CenteredImageSpan(this, R.mipmap.ic_topic_detail_jinghao_black)
spanStr.setSpan(imageSpan, 0, 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
// corner
spanStr.append(" #")
val len = spanStr.length
val cornerSpan = CenteredImageSpan(this, R.mipmap.ic_topic_detail_remen)
spanStr.setSpan(cornerSpan, len - 1, len, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
binding.ctTalkDetailInfo.talkNameTv.text = spanStr

FileProvider 的使用

FileProvider 的使用

Dev Doc

https://developer.android.google.cn/reference/androidx/core/content/FileProvider

0x01 定义一个FileProvider

在 androidx 包提供的 FileProvider 提供了 生成文件Uri 的功能。

在 manifest 文件中,声明一个 provider

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<manifest>
...
<application>
...
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}.fileprovider"
android:exported="false"
android:grantUriPermissions="true"
tools:replace="android:authorities">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths"
tools:replace="android:resource" />
</provider>
...
</application>
</manifest>

0x02 可用文件路径配置

在 res/xml/file_paths.xml 下配置可用的文件路径,FileProvider 只能生成配置了的文件Uri。每个你想要生成Uri的文件路径都需要在 paths 下面定义。

1
2
3
4
5
6
7
8
9
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<files-path name="my_images" path="images/"/>
<cache-path name="name" path="path" />
<external-path name="name" path="path" />
<external-files-path name="name" path="path" />
<external-cache-path name="name" path="path" />
<external-media-path name="name" path="path" />
...
</paths>

0x03 生成一个Uri

和其他 app 共享一个文件,你需要生成一个Uri。

1
2
3
4
5
6
7
8
9
File imagePath = new File(Context.getFilesDir(), "my_images");
File newFile = new File(imagePath, "default_image.jpg");

Uri uriForFile;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
uriForFile = FileProvider.getUriForFile(mContext, mContext.getPackageName() + ".fileprovider", newFile);
} else {
uriForFile = Uri.parse("file://" + newFile.toString());
}

getUriForFile() 返回一个 content URI content://com.mydomain.fileprovider/my_images/default_image.jpg.

0x04 授予权限

1
2
3
shareContentIntent.setClipData(ClipData.newRawUri("", contentUri));
shareContentIntent.addFlags(
Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
  1. Put the content URI in an Intent by calling setData().
  2. Call the method Intent.setFlags() with either Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION or both.
  3. Send the Intent to another app. Most often, you do this by calling setResult().

0x05 提供Uri给其他app

1
2
3
4
5
// 使用uri
Intent i = new Intent(Intent.ACTION_VIEW);
i.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
i.setDataAndType(uriForFile, "application/vnd.android.package-archive");
mContext.startActivity(i);
Your browser is out-of-date!

Update your browser to view this website correctly.&npsb;Update my browser now

×