我是靠谱客的博主 羞涩冬瓜,最近开发中收集的这篇文章主要介绍Android 10 适配及具体解决办法,一文详解,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

  1. Android Id:

kotlin:

val androidId = Settings.Secure.getString(
context.contentResolver,
Settings.Secure.ANDROID_ID
)

java:

String androidId = Settings.Secure.getString(
context.contentResolver,
Settings.Secure.ANDROID_ID
);

  1. 但是在实际应用中发现, 有Android Id获取失败的情况, 所以就完善了上面的方法

kotlin:

var deviceId = Settings.Secure.getString(
getAppContext().contentResolver,
Settings.Secure.ANDROID_ID
)
if (androidId.isNullOrEmpty()) {
deviceId = getUniquePsuedoID()
}

fun getUniquePsuedoID(): String {
val devIDShort =
“35” + Build.BOARD.length % 10 + Build.BRAND.length % 10 + Build.CPU_ABI.length % 10 + Build.DEVICE.length % 10 + Build.MANUFACTURER.length % 10 + Build.MODEL.length % 10 + Build.PRODUCT.length % 10

// API >= 9 的设备才有 android.os.Build.SERIAL
// http://developer.android.com/reference/android/os/Build.html#SERIAL
// 如果用户更新了系统或 root 了他们的设备,该 API 将会产生重复记录
var serial: String?
try {
serial = android.os.Build::class.java.getField(“SERIAL”).get(null).toString()
return UUID(
devIDShort.hashCode().toLong(),
serial.hashCode().toLong()
).toString()
} catch (exception: Exception) {
serial = “serial”
}
// 最后,组合上述值并生成 UUID 作为唯一 ID
return UUID(devIDShort.hashCode().toLong(), serial!!.hashCode().toLong()).toString()
}

java:

String deviceId = Settings.Secure.getString(
context.contentResolver,
Settings.Secure.ANDROID_ID
);
if(TextUtils.isEmpty(deviceId)) {
deviceId = getUniquePsuedoID()
}

public String getUniquePsuedoID() {
String devIDShort =
“35” + Build.BOARD.length % 10 + Build.BRAND.length % 10 + Build.CPU_ABI.length % 10 + Build.DEVICE.length % 10 + Build.MANUFACTURER.length % 10 + Build.MODEL.length % 10 + Build.PRODUCT.length % 10;

// API >= 9 的设备才有 android.os.Build.SERIAL
// http://developer.android.com/reference/android/os/Build.html#SERIAL
// 如果用户更新了系统或 root 了他们的设备,该 API 将会产生重复记录
String serial;
try {
serial = android.os.Build::class.java.getField(“SERIAL”).get(null).toString()
return UUID(
devIDShort.hashCode().toLong(),
serial.hashCode().toLong()
).toString();
} catch (Exception e) {
serial = “serial”;
}
// 最后,组合上述值并生成 UUID 作为唯一 ID
return UUID((long)devIDShort.hashCode(), (long)serial.hashCode()).toString();
}

限制Activity后台启动

说明: 此项行为变更适用于在 Android Q 上运行的所有应用,甚至包括以 Android 9(API 级别 28)或更低版本为目标平台的应用。此外,即使您的应用以 Android 9 或更低版本为目标平台并且最初安装在运行 Android 9 或更低版本的设备上,该行为变更仍会在设备升级到 Android Q 后生效。

解决方法:

发送全屏通知会自动启动Activity

kotlin:

fun sendNotification(
title: String?,
body: String?,
data: PushMessageNode?,
bitmap: Bitmap?
) {
val intent = Intent(this, PushJumpActivity::class.java)
intent.putExtra(WhatConstants.Intent.FIRE_PUSH_MESSAGE, data)
intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP
val pendingIntent = PendingIntent.getActivity(
this, requestCode, intent,
PendingIntent.FLAG_UPDATE_CURRENT
)

val notificationManager =
this.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager?

if (notificationManager != null) {
val notificationBuilder = NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val mNotificationChannel =
NotificationChannel(
NOTIFICATION_CHANNEL_ID,
NOTIFICATION_CHANNEL_NAME,
NotificationManager.IMPORTANCE_HIGH
)

notificationManager.createNotificationChannel(mNotificationChannel)
}

notificationBuilder
.setSmallIcon(R.mipmap.logo)
.setLargeIcon(
bitmap ?: BitmapFactory.decodeResource(
context,
R.mipmap.logo
)
)
.setContentTitle(title)
.setContentText(body)
.setShowWhen(true)
.setAutoCancel(true)
.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
//设置为全屏通知, 此时若App处于前台, 会为悬挂通知, 无论前台后台, 都会自动启动Acitivity
.setFullScreenIntent(pendingIntent, true)
.setContentIntent(pendingIntent)

notificationManager.notify(
requestCode /* ID of notification */,
notificationBuilder.build()
)

bitmap?.recycle()
}
}

java:

private void sendNotification(String title, String body, PushMessageNode data, Bitmap bitmap) {
Intent intent = new Intent(this, PushJumpActivity.class);
intent.putExtra(WhatConstants.Intent.INSTANCE.getFIRE_PUSH_MESSAGE(), data);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
int requestCode = (int) (Math.random() * 1000) + 1;
PendingIntent pendingIntent = PendingIntent.getActivity(this, requestCode /* Request code */, intent,
PendingIntent.FLAG_UPDATE_CURRENT);

Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationManager notificationManager = null;
notificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
Notification.Builder notificationBuilder;
if (notificationManager != null) {
if (Build.VERSION.SDK_INT >= 26) {
NotificationChannel mNotificationChannel = new NotificationChannel(“1”, “Channel1”, NotificationManager.IMPORTANCE_HIGH);
notificationManager.createNotificationChannel(mNotificationChannel);
notificationBuilder = new Notification.Builder(this, “1”);
} else {
notificationBuilder = new Notification.Builder(this);
}

notificationBuilder = notificationBuilder
.setSmallIcon(R.mipmap.logo)
.setLargeIcon(bitmap != null ? bitmap : BitmapFactory.decodeResource(context.getResources(), R.mipmap.logo))
.setContentTitle(title)
.setContentText(body)
.setShowWhen(true)
.setPriority(Notification.PRIORITY_HIGH)
.setAutoCancel(true)
.setSound(defaultSoundUri)
//设置为全屏通知, 此时若App处于前台, 会为悬挂通知, 无论前台后台, 都会自动启动Acitivity
.setFullScreenIntent(pendingIntent, true);
.setContentIntent(pendingIntent);

notificationManager.notify(requestCode /* ID of notification */, notificationBuilder.build());

if (bitmap != null)
bitmap.recycle();
}
}

获取剪贴板数据

说明: 只有默认输入法(IME)或者是目前处于焦点的应用, 才能访问到剪贴板数据.

这也就是说应用已经不能在后台监听剪贴板数据了, 不过我对目前处于焦点的应用这句话不太了解 . 另外在适配过程中, 遇到了一个问题, 在Acitivity onCreate直接获取剪贴板数据是不能成功获取的, 而在按钮点击的时候是可以的:

class SimpleActivity: AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)

//直接获取剪切板数据
getTextFromClip()
//剪贴板有数据也return “”

//点击按钮获取剪切板数据
view.setOnClickListener {
getClipboardData()
//返回剪贴板的正常数据
}

}

private fun getTextFromClip(): String {
val clipboardManager =
context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager?
if (null == clipboardManager || !clipboardManager.hasPrimaryClip()) {
return “”
}
val clipData = clipboardManager.primaryClip
if (null == clipData || clipData.itemCount < 1) {
return “”
}
val clipText = clipData.getItemAt(0)?.text ?: “”
return clipText.toString()
}
}

后面又对目前处于焦点的应用思考了一下, 应该就是视图加载到窗口上才能获取焦点, 后面经过适配, 在view.post()之后获取剪贴板数据,又参考了这篇文章[Android源码解析]view.post()到底干了啥, 了解到view.post()是在view dispatchAttachedToWindow后执行的, 然后写出方法如下:

kotlin:

/**

  • 获取剪贴板的内容
    */
    fun getClipBoardText(@Nullable activity: Activity?, f: (String) -> Unit) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q && activity != null) {
    getTextFromClipFroAndroidQ(activity, f)
    } else {
    f.invoke(getTextFromClip())
    }
    }

/**

  • AndroidQ 获取剪贴板的内容
    */
    @TargetApi(Build.VERSION_CODES.Q)
    private fun getTextFromClipFroAndroidQ(@NonNull activity: Activity, f: (String) -> Unit) {
    val runnable = Runnable {
    try {
    val clipboardManager =
    activity.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager?
    if (null == clipboardManager || !clipboardManager.hasPrimaryClip()) {
    f.invoke("")
    return@Runnable
    }
    val clipData = clipboardManager.primaryClip
    if (null == clipData || clipData.itemCount < 1) {
    f.invoke("")
    return@Runnable
    }
    val clipText = clipData.getItemAt(0)?.text ?: “”
    f.invoke(clipText.toString())
    return@Runnable
    } catch (e: Exception) {
    f.invoke("")
    return@Runnable
    }
    }
    activity.registerActivityLifecycleCallbacks(object :Application.ActivityLifecycleCallbacks {
    override fun onActivityPaused(activity: Activity) {
    }

override fun onActivityStarted(activity: Activity) {
}

override fun onActivityDestroyed(activity: Activity) {
activity.window?.decorView?.removeCallbacks(runnable)
}

override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) {
}

override fun onActivityStopped(activity: Activity) {
}

override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {
}

override fun onActivityResumed(activity: Activity) {
}
})
activity.window?.decorView?.post(runnable) ?: f.invoke("")
}

private fun getTextFromClip(): String {
try {
//可以使用Application的Context
val clipboardManager =
context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager?
if (null == clipboardManager || !clipboardManager.hasPrimaryClip()) {
return “”
}
val clipData = clipboardManager.primaryClip
if (null == clipData || clipData.itemCount < 1) {
return “”
}
val item = clipData.getItemAt(0) ?: return “”
val clipText = item.text ?: “”
return if (TextUtils.isEmpty(clipText)) “” else clipText.toString()
} catch (e: Exception) {
return “”
}
}

java:

public interface Function {
/** Invokes the function. */
void invoke(String text);
}

void getClipBoardText(@Nullable Activity activity, final Function f) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q && activity != null) {
getTextFromClipFroAndroidQ(activity, f);
} else {
f.invoke(getTextFromClip());
}
}

/**

  • AndroidQ 获取剪贴板的内容
    */
    @TargetApi(Build.VERSION_CODES.Q)
    private void getTextFroClipFromAndroidQ(@NonNull final Activity activity, final Function f) {
    Runnable runnable = new Runnable() {
    @Override
    public void run() {
    ClipboardManager clipboardManager =
    (ClipboardManager)activity.getSystemService(Context.CLIPBOARD_SERVICE);
    if (null == clipboardManager || !clipboardManager.hasPrimaryClip()) {
    f.invoke("");
    return;
    }
    ClipData clipData = clipboardManager.getPrimaryClip();
    if (null == clipData || clipData.getItemCount() < 1) {
    f.invoke("");
    return;
    }
    ClipData.Item item = clipData.getItemA

《Android学习笔记总结+最新移动架构视频+大厂安卓面试真题+项目实战源码讲义》

【docs.qq.com/doc/DSkNLaERkbnFoS0ZF】 完整内容开源分享

t(0);
if (item == null) {

最后

以上就是羞涩冬瓜为你收集整理的Android 10 适配及具体解决办法,一文详解的全部内容,希望文章能够帮你解决Android 10 适配及具体解决办法,一文详解所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(45)

评论列表共有 0 条评论

立即
投稿
返回
顶部