【干货】Android系统定制基础篇:第五部分(Android关闭selinux、Android设置界面展示CPU序号、Android默认同意蓝牙的配对请求)

1、Android关闭selinux

方法一 修改init.rc,强制关闭selinux
打开init.rc文件,如下位置添加代码:

on init

#disnable security enhanced linux
setenforce 0

方法二 修改cmdline参数 (推荐)
1.查看system/core/init/init.cpp文件。

static void selinux_initialize(bool in_kernel_domain) {
    Timer t;

    selinux_callback cb;
    cb.func_log = selinux_klog_callback;
    selinux_set_callback(SELINUX_CB_LOG, cb);
    cb.func_audit = audit_callback;
    selinux_set_callback(SELINUX_CB_AUDIT, cb);

    if (in_kernel_domain) {
        LOG(INFO) << "Loading SELinux policy";
        if (!selinux_load_policy()) {
            panic();
        }

        bool kernel_enforcing = (security_getenforce() == 1);
        bool is_enforcing = selinux_is_enforcing();
        if (kernel_enforcing != is_enforcing) {
            if (security_setenforce(is_enforcing)) {
                PLOG(ERROR) << "security_setenforce(%s) failed" << (is_enforcing ? "true" : "false");
                security_failure();
            }
        }

        std::string err;
        if (!WriteFile("/sys/fs/selinux/checkreqprot", "0", &err)) {
            LOG(ERROR) << err;
            security_failure();
        }

        // init's first stage can't set properties, so pass the time to the second stage.
        setenv("INIT_SELINUX_TOOK", std::to_string(t.duration().count()).c_str(), 1);
    } else {
        selinux_init_all_handles();
    }
}

2.发现selinux_is_enforcing()方法

static bool selinux_is_enforcing(void)
{
    if (ALLOW_PERMISSIVE_SELINUX) {
        return selinux_status_from_cmdline() == SELINUX_ENFORCING;
    }
    return true;
}

3.再看selinux_status_from_cmdline()。

static selinux_enforcing_status selinux_status_from_cmdline() {
    selinux_enforcing_status status = SELINUX_ENFORCING;

    import_kernel_cmdline(false, [&](const std::string& key, const std::string& value, bool in_qemu) {
        if (key == "androidboot.selinux" && value == "permissive") {
            status = SELINUX_PERMISSIVE;
        }
    });

    return status;
}

4.init进程会读取cmdline中androidboot.selinux字段,该字段有下面两个参数

androidboot.selinux=permissive
androidboot.selinux=enforcing

● enforcing 开启selinux。
● permissive 关闭selinux,但会记录权限的操作,依然会打印下面日志:

[  926.395093] type=1400 audit(1542353454.166:51): avc: denied { getattr } for pid=4179 comm="Thread-4" path="/dev/ttyS0" dev="tmpfs" ino=11498 scontext=u:r:untrusted_app_25:s0:c512,c768 tcontext=u:object_r:serial_device:s0 tclass=chr_file permissive=1

5.修改parameter.txt中androidboot.selinux字段。

FIRMWARE_VER:7.1
MACHINE_MODEL:RK3288
MACHINE_ID:007
MANUFACTURER:rk3288
MAGIC: 0x5041524B
ATAG: 0x00200800
MACHINE: 3288
CHECK_MASK: 0x80
PWR_HLD: 0,0,A,0,1
CMDLINE: console=ttyFIQ0 androidboot.baseband=N/A androidboot.selinux=permissive androidboot.hardware=rk30board androidboot.console=ttyFIQ0 init=/init initrd=0x62000000,0x00800000 mtdparts=rk29xxnand:0x00002000@0x00002000(uboot),0x00002000@0x00004000(trust),0x00002000@0x00006000(misc),0x00008000@0x00008000(resource),0x00010000@0x00010000(kernel),0x00010000@0x00020000(boot),0x00020000@0x00030000(recovery),0x00038000@0x00050000(backup),0x00002000@0x00088000(security),0x00100000@0x0008a000(cache),0x00400000@0x0018a000(system),0x00008000@0x0058a000(metadata),0x00080000@0x00592000(vendor),0x00080000@0x00612000(oem),0x00000400@0x00692000(frp),-@0x00692400(userdata)

2、Android设置界面展示CPU序号

有时候我们需要某个字段做为设备的 唯一标识,常规的有 uuid、序列号、mac地址,但这些字段在重刷固件的情况下可能会变,因此我们可以读取 cpu序列号,这个字段唯一并且永久不变,除非更换 cpu。

应用中获取 cpu 序列号的方法如下:

/**
 * Get cpu serial
 *
 * @return success: cpu serial, failed: "0000000000000000"
 */
public static String getCPUSerial() {
    String cpuAddress = "0000000000000000";

    try {
        Process process = Runtime.getRuntime().exec("cat /proc/cpuinfo");
        InputStreamReader is = new InputStreamReader(process.getInputStream());
        LineNumberReader input = new LineNumberReader(is);

        String str;
        while ((str = input.readLine()) != null) {
            if (!TextUtils.isEmpty(str)) {
                if (str.contains("Serial")) {
                    String cpuStr = str.substring(str.indexOf(":") + 1);
                    cpuAddress = cpuStr.trim();
                    break;
                }
            }
        }
    } catch (IOException e) {
        Log.e(TAG, "getCPUSerial, " + e.getMessage());
    }

    return cpuAddress;
}

为了方便用户查看,我们在『设置->系统->关于->状态信息』中展示此字段。修改如下:

commit 1a3dd6bac1f898160dc608e8b680c7a502292466
Author: shenhb <shenhb@topband.com.cn>
Date:   Wed Mar 25 14:54:17 2020 +0800Settings】状态信息界面展示CPU序列号

diff --git a/packages/apps/Settings/res/values-zh-rCN/strings.xml b/packages/apps/Settings/res/values-zh-rCN/strings.xml
index 0baf96a..2af859d 100755
--- a/packages/apps/Settings/res/values-zh-rCN/strings.xml
+++ b/packages/apps/Settings/res/values-zh-rCN/strings.xml
@@ -1166,6 +1166,7 @@
     <string name="status_wifi_mac_address" msgid="2202206684020765378">"WLAN MAC 地址"</string>
     <string name="status_bt_address" msgid="4195174192087439720">"蓝牙地址"</string>
     <string name="status_serial_number" msgid="2257111183374628137">"序列号"</string>
+    <string name="status_cpu_serial_number">"CPU序列号"</string>
     <string name="status_unavailable" msgid="7862009036663793314">"无法获取"</string>
     <string name="status_up_time" msgid="7294859476816760399">"已开机时间"</string>
     <string name="status_awake_time" msgid="2393949909051183652">"唤醒时间"</string>
diff --git a/packages/apps/Settings/res/values/strings.xml b/packages/apps/Settings/res/values/strings.xml
index b54050d..c786f9a 100755
--- a/packages/apps/Settings/res/values/strings.xml
+++ b/packages/apps/Settings/res/values/strings.xml
@@ -2705,6 +2705,8 @@
     <string name="status_bt_address">Bluetooth address</string>
     <!-- About phone, status item title.  The hardware serial number. [CHAR LIMIT=30]-->
     <string name="status_serial_number">Serial number</string>
+    <!-- About phone, status item title.  The cpu serial number. [CHAR LIMIT=30]-->
+    <string name="status_cpu_serial_number">CPU Serial number</string>
     <!-- About phone, status item value if the actual value is not available. -->
     <string name="status_unavailable">Unavailable</string>
     <!-- About phone, status item title.  How long the device has been running since its last reboot. -->
diff --git a/packages/apps/Settings/res/xml/device_info_status.xml b/packages/apps/Settings/res/xml/device_info_status.xml
old mode 100644
new mode 100755
index b381d04..112505d
--- a/packages/apps/Settings/res/xml/device_info_status.xml
+++ b/packages/apps/Settings/res/xml/device_info_status.xml
@@ -76,6 +76,13 @@
         android:summary="@string/summary_placeholder"
         android:persistent="false" />
     <Preference
+        android:key="cpu_serial_number"
+        android:enabled="false"
+        android:shouldDisableView="false"
+        android:title="@string/status_cpu_serial_number"
+        android:summary="@string/summary_placeholder"
+        android:persistent="false" />
+    <Preference
         android:key="up_time"
         android:enabled="false"
         android:shouldDisableView="false"
diff --git a/packages/apps/Settings/src/com/android/settings/deviceinfo/CPUSerialNumberPreferenceController.java b/packages/apps/Settings/src/com/android/settings/deviceinfo/CPUSerialNumberPreferenceController.java
new file mode 100755
index 0000000..35c7434
--- /dev/null
+++ b/packages/apps/Settings/src/com/android/settings/deviceinfo/CPUSerialNumberPreferenceController.java
@@ -0,0 +1,103 @@
+/*
+ * Copyright (C) 2016 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.settings.deviceinfo;
+
+import android.content.Context;
+import android.os.Build;
+import android.support.v7.preference.Preference;
+import android.support.v7.preference.PreferenceScreen;
+import android.text.TextUtils;
+import android.util.Log;
+
+import com.android.internal.annotations.VisibleForTesting;
+import com.android.settings.core.PreferenceControllerMixin;
+import com.android.settingslib.core.AbstractPreferenceController;
+
+import java.io.IOException;
+import java.io.InputStreamReader;
+import java.io.LineNumberReader;
+
+/**
+ * Created by [email protected]
+ */
+public class CPUSerialNumberPreferenceController extends AbstractPreferenceController implements
+        PreferenceControllerMixin {
+    private static final String TAG = "CPUSerialNumberPreferenceController";
+
+    private static final String KEY_SERIAL_NUMBER = "cpu_serial_number";
+
+    private final String mSerialNumber;
+
+    public CPUSerialNumberPreferenceController(Context context) {
+        this(context, getCPUSerial());
+    }
+
+    @VisibleForTesting
+    CPUSerialNumberPreferenceController(Context context, String serialNumber) {
+        super(context);
+        mSerialNumber = serialNumber;
+    }
+
+    @Override
+    public boolean isAvailable() {
+        return !TextUtils.isEmpty(mSerialNumber);
+    }
+
+    @Override
+    public void displayPreference(PreferenceScreen screen) {
+        super.displayPreference(screen);
+        final Preference pref = screen.findPreference(KEY_SERIAL_NUMBER);
+        if (pref != null) {
+            pref.setSummary(mSerialNumber);
+        }
+    }
+
+    @Override
+    public String getPreferenceKey() {
+        return KEY_SERIAL_NUMBER;
+    }
+
+    /**
+     * Get cpu serial
+     *
+     * @return success: cpu serial, failed: "0000000000000000"
+     */
+    public static String getCPUSerial() {
+        String cpuAddress = "0000000000000000";
+
+        try {
+            Process process = Runtime.getRuntime().exec("cat /proc/cpuinfo");
+            InputStreamReader is = new InputStreamReader(process.getInputStream());
+            LineNumberReader input = new LineNumberReader(is);
+
+            String str;
+            while ((str = input.readLine()) != null) {
+                if (!TextUtils.isEmpty(str)) {
+                    if (str.contains("Serial")) {
+                        String cpuStr = str.substring(str.indexOf(":") + 1);
+                        cpuAddress = cpuStr.trim();
+                        break;
+                    }
+                }
+            }
+        } catch (IOException e) {
+            Log.e(TAG, "getCPUSerial, " + e.getMessage());
+        }
+
+        return cpuAddress;
+    }
+}
diff --git a/packages/apps/Settings/src/com/android/settings/deviceinfo/Status.java b/packages/apps/Settings/src/com/android/settings/deviceinfo/Status.java
old mode 100644
new mode 100755
index 624103a..628c536
--- a/packages/apps/Settings/src/com/android/settings/deviceinfo/Status.java
+++ b/packages/apps/Settings/src/com/android/settings/deviceinfo/Status.java
@@ -82,6 +82,7 @@ public class Status extends SettingsPreferenceFragment implements Indexable {
     private String mUnavailable;
 
     private SerialNumberPreferenceController mSerialNumberPreferenceController;
+    private CPUSerialNumberPreferenceController mCPUSerialNumberPreferenceController;
 
     private Preference mUptime;
     private Preference mBatteryStatus;
@@ -159,6 +160,7 @@ public class Status extends SettingsPreferenceFragment implements Indexable {
         mCM = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
         mWifiManager = (WifiManager) getSystemService(WIFI_SERVICE);
         mSerialNumberPreferenceController = new SerialNumberPreferenceController(getActivity());
+        mCPUSerialNumberPreferenceController = new CPUSerialNumberPreferenceController(getActivity());
 
         addPreferencesFromResource(R.xml.device_info_status);
         mBatteryLevel = findPreference(KEY_BATTERY_LEVEL);
@@ -192,6 +194,7 @@ public class Status extends SettingsPreferenceFragment implements Indexable {
         updateConnectivity();
 
         mSerialNumberPreferenceController.displayPreference(screen);
+        mCPUSerialNumberPreferenceController.displayPreference(screen);
 
         // Remove SimStatus and Imei for Secondary user as it access Phone b/19165700
         // Also remove on Wi-Fi only devices.

3、Android默认同意蓝牙的配对请求

一些不带触摸屏设备,手机端发起蓝牙配对请求后,设备端无法点击确认。因此,在这些设备上我们需要默认同意蓝牙的配对请求。

Android 5.1

commit cd0cc3c5850e46b70857dbda23cf794daac2c015
Author: shenhb <shenhb@topband.com.cn>
Date:   Fri Dec 28 17:08:12 2018 +0800

    【蓝牙】默认同意蓝牙配对

diff --git a/packages/apps/Settings/src/com/android/settings/bluetooth/BluetoothPairingDialog.java b/packages/apps
index 6f5c136..3e679b2 100755
--- a/packages/apps/Settings/src/com/android/settings/bluetooth/BluetoothPairingDialog.java
+++ b/packages/apps/Settings/src/com/android/settings/bluetooth/BluetoothPairingDialog.java
@@ -162,6 +162,11 @@ public final class BluetoothPairingDialog extends AlertActivity implements
          */
         registerReceiver(mReceiver, new IntentFilter(BluetoothDevice.ACTION_PAIRING_CANCEL));
         registerReceiver(mReceiver, new IntentFilter(BluetoothDevice.ACTION_BOND_STATE_CHANGED));
+        
+        // Add by [email protected], for default consent to pairing
+        onClick(null, BUTTON_POSITIVE);
+        finish();
+        // Add end
     }
 
     private void createUserEntryDialog() {

Android 8.1

commit ca7dd7bc70f939a1689ccc394f3ff3a2cf9e981a
Author: shenhb <shenhb@topband.com.cn>
Date:   Fri Mar 13 16:00:51 2020 +0800

    【蓝牙】默认同意蓝牙配对

diff --git a/packages/apps/Settings/src/com/android/settings/bluetooth/BluetoothPairingDialog.java b/packages/apps
old mode 100644
new mode 100755
index 22cb3a6..34facba
--- a/packages/apps/Settings/src/com/android/settings/bluetooth/BluetoothPairingDialog.java
+++ b/packages/apps/Settings/src/com/android/settings/bluetooth/BluetoothPairingDialog.java
@@ -25,6 +25,7 @@ import android.content.Intent;
 import android.content.IntentFilter;
 import android.os.Bundle;
 import android.support.annotation.VisibleForTesting;
+import android.content.DialogInterface;
 
 /**
  * BluetoothPairingDialog asks the user to enter a PIN / Passkey / simple confirmation
@@ -94,6 +95,10 @@ public class BluetoothPairingDialog extends Activity {
         registerReceiver(mReceiver, new IntentFilter(BluetoothDevice.ACTION_PAIRING_CANCEL));
         registerReceiver(mReceiver, new IntentFilter(BluetoothDevice.ACTION_BOND_STATE_CHANGED));
         mReceiverRegistered = true;
+
+        // Add by [email protected], for default consent to pairing
+        bluetoothFragment.onClick(null, DialogInterface.BUTTON_POSITIVE);
+        // Add end
     }
 
     @Override

你可能感兴趣的:(Android,android,java,开发语言)