天天看點

Android 8.0 通知欄不顯示

由于 Google Play 現在限制了上傳 APK 的 targetSdkVersion,是以在新項目中就開始把版本号升到最高,這樣一來之前前人寫的一些代碼庫就會出現相容性的問題,比如下載下傳更新 APK 時,FileProvider 問題(我上一篇有講到過)。比如在下載下傳的過程中,之前寫好的通知欄中顯示進度。但是在 targetSdkVersion > 26 時,會被屏蔽掉。

  • Android 8.0 引入了 Notifycation Channel
  • 官方通知文檔:https://developer.android.google.cn/training/notify-user/build-notification

在 new NotificationCompat.Builder(context) 之前适配版本是否大于26 

mNotifyManager = (NotificationManager) mContext
                        .getSystemService(Context.NOTIFICATION_SERVICE);
                
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {

                    NotificationChannel channel = new NotificationChannel("channel_id", "channel", NotificationManager.IMPORTANCE_LOW);

                    channel.setLightColor(Color.GREEN);

                    channel.enableLights(true);

                    channel.enableVibration(true);

                    channel.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);

                    mNotifyManager.createNotificationChannel(channel);
                }
           

 另外 Android 8.0 還需要注意,添加 "允許未知來源" 權限,因為在下載下傳安裝 APK 時,高版本手機需要設定

  • 在 AndroidManifest.xml 添權重限
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />
           
  • 下載下傳完安裝時,需要添加 Flags
Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);//檢測是否允許未知來源
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setDataAndType(uri,
                "application/vnd.android.package-archive");
        context.startActivity(intent);
           

經過測試之後,終于更新了一個版本到市場。