取得电信网络和手机的相关信息之TelephonyManager与android.provider.settings.System

本文介绍了如何使用Android系统API获取设备的蓝牙、Wi-Fi及飞行模式等状态,并通过ContentResolver与Settings.System交互来读取这些系统设置信息。

      除了SIM卡的相关信息之外,我们可以使用TelephonyManager来获取电信网络的相关信息。例如电信网络国别、电信网络国别、代码、名称、网络类型等。

初次之外,我们要想获得蓝牙、无限网络等手机内置值,我们可以通过android.provider.settings.System来获取。

至于TelephonyManager这个类,我们前边已经介绍过了。现在,我们来看看android.provider.settings.System.

我们可以看出,如果我们想取得System中的值,那么我们必须首先获取一个ContentResolver,然后传递进去,这是为什么呢?其实system本质上是一张表的映射,这么说,你就明白了吧。我们甚至可以通过其提供的各种put方法,将我们的一些值存储到该表中。

源码中有这么一段代码:

 /**
         * The content:// style URL for this table
         */
        public static final Uri CONTENT_URI =
            Uri.parse("content://" + AUTHORITY + "/system");

现在,明白了吧。其中authority是settings

---------------------------------------------------------------

其他可访问的设置信息:

 

package com.example.myapplication; import android.Manifest; import android.annotation.SuppressLint; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothManager; import android.content.ContentResolver; import android.content.Context; import android.content.Intent; import android.content.pm.ApplicationInfo; import android.content.pm.PackageManager; import android.database.Cursor; import android.net.Uri; import android.net.wifi.WifiConfiguration; import android.net.wifi.WifiManager; import android.os.Build; import android.os.Bundle; import android.provider.CallLog; import android.provider.CalendarContract; import android.provider.ContactsContract; import android.provider.MediaStore; import android.provider.Settings; import android.provider.Telephony; import android.telephony.TelephonyManager; import android.util.Log; import android.widget.TextView; import androidx.core.app.ActivityCompat; import androidx.core.content.ContextCompat; import androidx.activity.EdgeToEdge; import androidx.activity.result.ActivityResultLauncher; import androidx.activity.result.contract.ActivityResultContracts; import androidx.appcompat.app.AlertDialog; import androidx.appcompat.app.AppCompatActivity; import androidx.core.graphics.Insets; import androidx.core.view.ViewCompat; import androidx.core.view.WindowInsetsCompat; import com.google.android.gms.location.FusedLocationProviderClient; import com.google.android.gms.location.LocationServices; import com.google.android.gms.location.Priority; import com.google.android.gms.tasks.CancellationTokenSource; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Map; import java.util.Set; public class MainActivity extends AppCompatActivity { private static final String TAG = "InfoCollector"; private TextView tvBasicInfo, tvPhoneInfo, tvLocation, tvContacts, tvSms, tvCallLog, tvCalendar, tvWifi, tvBluetooth, tvInstalledApps, tvBluetoothFiles; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); EdgeToEdge.enable(this); setContentView(R.layout.activity_main); initializeViews(); ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> { Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars()); v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom); return insets; }); collectBasicInfo(); requestPermissionsAndCollectData(); } private void initializeViews() { tvBasicInfo = findViewById(R.id.tvBasicInfo); tvPhoneInfo = findViewById(R.id.tvPhoneInfo); tvLocation = findViewById(R.id.tvLocation); tvContacts = findViewById(R.id.tvContacts); tvSms = findViewById(R.id.tvSms); tvCallLog = findViewById(R.id.tvCallLog); tvCalendar = findViewById(R.id.tvCalendar); tvWifi = findViewById(R.id.tvWifi); tvBluetooth = findViewById(R.id.tvBluetooth); tvInstalledApps = findViewById(R.id.tvInstalledApps); tvBluetoothFiles = findViewById(R.id.tvBluetoothFiles); } private void requestPermissionsAndCollectData() { ActivityResultLauncher<String[]> permissionRequest = registerForActivityResult( new ActivityResultContracts.RequestMultiplePermissions(), permissions -> { collectInstalledApps(); // Phone_Status if (Boolean.TRUE.equals(permissions.get(Manifest.permission.READ_PHONE_STATE))) { collectPhoneInfo(); } else { tvPhoneInfo.setText("Phone Info: Permission denied"); } Boolean fineLocation = permissions.getOrDefault(Manifest.permission.ACCESS_FINE_LOCATION, false); Boolean coarseLocation = permissions.getOrDefault(Manifest.permission.ACCESS_COARSE_LOCATION, false); // Location if (Boolean.TRUE.equals(fineLocation) || Boolean.TRUE.equals(coarseLocation)) { collectLocationInfo(); collectWifiInfo(); } else { tvLocation.setText("Location: Permission denied"); tvWifi.setText("Wifi Info: Location permission denied"); } // Media Files String mediaPermission = Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU ? Manifest.permission.READ_MEDIA_IMAGES : Manifest.permission.READ_EXTERNAL_STORAGE; if (Boolean.TRUE.equals(permissions.get(mediaPermission))) { collectBluetoothTransferredFiles(); } else { tvBluetoothFiles.setText("Permission to read media files was denied."); } // Contacts if (Boolean.TRUE.equals(permissions.get(Manifest.permission.READ_CONTACTS))) { collectContacts(); } else { tvContacts.setText("Permission denied"); } // SMS if (Boolean.TRUE.equals(permissions.get(Manifest.permission.READ_SMS))) { collectSms(); } else { tvSms.setText("Permission denied"); } // Call Log if (Boolean.TRUE.equals(permissions.get(Manifest.permission.READ_CALL_LOG))) { collectCallLog(); } else { tvCallLog.setText("Permission denied"); } // Calendar if (Boolean.TRUE.equals(permissions.get(Manifest.permission.READ_CALENDAR))) { collectCalendarEvents(); } else { tvCalendar.setText("Permission denied"); } // Bluetooth if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { if (Boolean.TRUE.equals(permissions.get(Manifest.permission.BLUETOOTH_CONNECT))) { collectBluetoothInfo(); } else { tvBluetooth.setText("Permission denied"); } } else { collectBluetoothInfo(); } }); ArrayList<String> permissionsToRequest = new ArrayList<>(); permissionsToRequest.add(Manifest.permission.READ_PHONE_STATE); permissionsToRequest.add(Manifest.permission.ACCESS_FINE_LOCATION); permissionsToRequest.add(Manifest.permission.ACCESS_COARSE_LOCATION); permissionsToRequest.add(Manifest.permission.READ_CONTACTS); permissionsToRequest.add(Manifest.permission.READ_SMS); permissionsToRequest.add(Manifest.permission.READ_CALL_LOG); permissionsToRequest.add(Manifest.permission.READ_CALENDAR); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { permissionsToRequest.add(Manifest.permission.BLUETOOTH_CONNECT); } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { permissionsToRequest.add(Manifest.permission.READ_MEDIA_IMAGES); } else { permissionsToRequest.add(Manifest.permission.READ_EXTERNAL_STORAGE); } permissionRequest.launch(permissionsToRequest.toArray(new String[0])); } private void collectBasicInfo() { String manufacturer = Build.MANUFACTURER; String model = Build.MODEL; int apiLevel = Build.VERSION.SDK_INT; String osVersion = Build.VERSION.RELEASE; tvBasicInfo.setText(String.format("Basic Info: %s %s, API %d, OS %s", manufacturer, model, apiLevel, osVersion)); } private void collectInstalledApps() { PackageManager pm = getPackageManager(); StringBuilder appsBuilder = new StringBuilder(); @SuppressLint("QueryPermissionsNeeded") List<ApplicationInfo> apps = pm.getInstalledApplications(PackageManager.GET_META_DATA); for (ApplicationInfo app : apps) { if ((app.flags & ApplicationInfo.FLAG_SYSTEM) == 0) { appsBuilder.append(pm.getApplicationLabel(app)).append("\n"); } } tvInstalledApps.setText(appsBuilder.toString()); } @SuppressLint({"MissingPermission", "HardwareIds"}) private void collectPhoneInfo() { TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE); String imei = "N/A"; if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) { try { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { imei = tm.getImei(); } else { //noinspection deprecation imei = tm.getDeviceId(); } } catch (SecurityException e) { imei = "Error reading IMEI"; } } else { imei = "Not available on Android 10+"; } if (imei == null) imei = "N/A"; String phoneNumber = "N/A"; try { phoneNumber = tm.getLine1Number(); if (phoneNumber == null || phoneNumber.isEmpty()) { phoneNumber = "N/A"; } } catch (SecurityException e) { phoneNumber = "Error reading number"; } tvPhoneInfo.setText(String.format("Phone Info: IMEI=%s, Number=%s", imei, phoneNumber)); } @SuppressLint("MissingPermission") private void collectLocationInfo() { FusedLocationProviderClient fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this); if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) { tvLocation.setText("Location: Permission not granted"); return; } CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); fusedLocationProviderClient.getCurrentLocation(Priority.PRIORITY_HIGH_ACCURACY, cancellationTokenSource.getToken()) .addOnSuccessListener(this, location -> { if (location != null) { tvLocation.setText(String.format("Location: Lat=%.4f, Lon=%.4f", location.getLatitude(), location.getLongitude())); } else { tvLocation.setText("Location: Failed to get current location."); } }) .addOnFailureListener(e -> { tvLocation.setText("Location: Error getting location."); Log.e(TAG, "Error getting current location", e); }); } @SuppressLint("MissingPermission") private void collectContacts() { ContentResolver resolver = getContentResolver(); StringBuilder contactsBuilder = new StringBuilder(); try (Cursor c = resolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, new String[]{ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME, ContactsContract.CommonDataKinds.Phone.NUMBER}, null, null, "display_name ASC")) { if (c != null && c.getCount() > 0) { while (c.moveToNext()) { String name = c.getString(c.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME)); String number = c.getString(c.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Phone.NUMBER)); contactsBuilder.append(String.format("%s: %s\n", name, number)); } tvContacts.setText(contactsBuilder.toString()); } else { tvContacts.setText("No contacts found."); } } catch (Exception e) { tvContacts.setText("Error reading contacts."); Log.e(TAG, "Error reading contacts", e); } } @SuppressLint("MissingPermission") private void collectSms() { ContentResolver resolver = getContentResolver(); StringBuilder smsBuilder = new StringBuilder(); final String[] projection = { Telephony.Sms.ADDRESS, Telephony.Sms.BODY, Telephony.Sms.TYPE, Telephony.Sms.READ, Telephony.Sms.DATE }; try (Cursor c = resolver.query(Telephony.Sms.CONTENT_URI, projection, null, null, "date DESC")) { if (c != null && c.getCount() > 0) { int count = 0; while (c.moveToNext() && count < 20) { String address = c.getString(c.getColumnIndexOrThrow(Telephony.Sms.ADDRESS)); String body = c.getString(c.getColumnIndexOrThrow(Telephony.Sms.BODY)); int type = c.getInt(c.getColumnIndexOrThrow(Telephony.Sms.TYPE)); int read = c.getInt(c.getColumnIndexOrThrow(Telephony.Sms.READ)); long date = c.getLong(c.getColumnIndexOrThrow(Telephony.Sms.DATE)); String typeStr = (type == Telephony.Sms.MESSAGE_TYPE_INBOX) ? "Inbox" : "Sent"; String addressLabel = (type == Telephony.Sms.MESSAGE_TYPE_INBOX) ? "From" : "To"; String readStatus = (read == 1) ? "Read" : "Unread"; String dateStr = new Date(date).toString(); smsBuilder.append(String.format("%s: %s (%s, %s)\nDate: %s\nBody: %s...\n\n", addressLabel, address, typeStr, readStatus, dateStr, body.substring(0, Math.min(body.length(), 40)))); count++; } if (smsBuilder.length() > 0) { tvSms.setText(smsBuilder.toString()); } else { tvSms.setText("No valid SMS found."); } } else { tvSms.setText("No SMS found."); } } catch (Exception e) { tvSms.setText("Error reading SMS. Please check manual permissions."); showPermissionGuideDialog("to read SMS messages"); Log.e(TAG, "Error reading SMS, possibly due to OEM restrictions.", e); } } @SuppressLint("MissingPermission") private void collectCallLog() { ContentResolver resolver = getContentResolver(); StringBuilder callLogBuilder = new StringBuilder(); String[] projection = { CallLog.Calls.NUMBER, CallLog.Calls.TYPE, CallLog.Calls.DURATION, CallLog.Calls.DATE, CallLog.Calls.NUMBER_PRESENTATION }; try (Cursor c = resolver.query(CallLog.Calls.CONTENT_URI, projection, null, null, "date DESC")) { if (c != null && c.getCount() > 0) { int count = 0; while (c.moveToNext() && count < 20) { int presentation = c.getInt(c.getColumnIndexOrThrow(CallLog.Calls.NUMBER_PRESENTATION)); if (presentation != CallLog.Calls.PRESENTATION_ALLOWED) { continue; } String number = c.getString(c.getColumnIndexOrThrow(CallLog.Calls.NUMBER)); int type = c.getInt(c.getColumnIndexOrThrow(CallLog.Calls.TYPE)); long duration = c.getLong(c.getColumnIndexOrThrow(CallLog.Calls.DURATION)); String typeStr; switch (type) { case CallLog.Calls.INCOMING_TYPE: typeStr = "Incoming"; break; case CallLog.Calls.OUTGOING_TYPE: typeStr = "Outgoing"; break; case CallLog.Calls.MISSED_TYPE: typeStr = "Missed"; break; default: typeStr = "Unknown"; } callLogBuilder.append(String.format("%s (%s, %ds)\n", number, typeStr, duration)); count++; } if (callLogBuilder.length() == 0) { tvCallLog.setText("No valid call logs found."); } else { tvCallLog.setText(callLogBuilder.toString()); } } else { tvCallLog.setText("No call logs found."); } } catch (Exception e) { tvCallLog.setText("Error reading Call Log. Please check manual permissions."); showPermissionGuideDialog("to read call logs"); Log.e(TAG, "Error reading Call Log, possibly due to OEM restrictions.", e); } } private void showPermissionGuideDialog(String reason) { new AlertDialog.Builder(this) .setTitle("Permission Required") .setMessage("This app may require extra permissions in your device's security manager to " + reason + ".") .setPositiveButton("Go to Settings", (dialog, which) -> { Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS); Uri uri = Uri.fromParts("package", getPackageName(), null); intent.setData(uri); startActivity(intent); }) .setNegativeButton("Cancel", null) .show(); } @SuppressLint("MissingPermission") private void collectCalendarEvents() { ContentResolver resolver = getContentResolver(); StringBuilder calendarBuilder = new StringBuilder(); try (Cursor c = resolver.query(CalendarContract.Events.CONTENT_URI, new String[]{CalendarContract.Events.TITLE, CalendarContract.Events.DTSTART}, null, null, "dtstart DESC")) { if (c != null && c.getCount() > 0) { int count = 0; while (c.moveToNext() && count < 20) { String title = c.getString(c.getColumnIndexOrThrow(CalendarContract.Events.TITLE)); long startTime = c.getLong(c.getColumnIndexOrThrow(CalendarContract.Events.DTSTART)); calendarBuilder.append(String.format("%s (%s)\n", title, new java.util.Date(startTime).toString())); count++; } tvCalendar.setText(calendarBuilder.toString()); } else { tvCalendar.setText("No calendar events found."); } } catch (Exception e) { tvCalendar.setText("Error reading Calendar."); Log.e(TAG, "Error reading Calendar", e); } } @SuppressLint("MissingPermission") private void collectWifiInfo() { StringBuilder wifiBuilder = new StringBuilder(); if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) { @SuppressWarnings("deprecation") WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE); if (wifiManager != null) { @SuppressWarnings("deprecation") List<WifiConfiguration> configuredNetworks = wifiManager.getConfiguredNetworks(); if (configuredNetworks != null && !configuredNetworks.isEmpty()) { for (WifiConfiguration wifiConfig : configuredNetworks) { wifiBuilder.append(wifiConfig.SSID).append("\n"); } tvWifi.setText(wifiBuilder.toString()); } } } else { tvWifi.setText("Not supported on Android 10+."); } } @SuppressLint("MissingPermission") private void collectBluetoothInfo() { BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE); BluetoothAdapter bluetoothAdapter = (bluetoothManager != null) ? bluetoothManager.getAdapter() : null; if (bluetoothAdapter == null) { tvBluetooth.setText("Bluetooth is not supported."); return; } StringBuilder bluetoothBuilder = new StringBuilder(); try { Set<BluetoothDevice> pairedDevices = bluetoothAdapter.getBondedDevices(); if (pairedDevices != null && !pairedDevices.isEmpty()) { for (BluetoothDevice device : pairedDevices) { bluetoothBuilder.append(String.format("%s (%s)\n", device.getName(), device.getAddress())); } tvBluetooth.setText(bluetoothBuilder.toString()); } else { tvBluetooth.setText("No paired Bluetooth devices found."); } } catch (SecurityException e) { tvBluetooth.setText("Permission denied"); } } @SuppressLint("MissingPermission") private void collectBluetoothTransferredFiles() { ContentResolver resolver = getContentResolver(); StringBuilder filesBuilder = new StringBuilder(); Uri queryUri = MediaStore.Files.getContentUri("external"); String[] projection = { MediaStore.Files.FileColumns.DISPLAY_NAME, MediaStore.Files.FileColumns.DATE_ADDED, MediaStore.Files.FileColumns.SIZE, MediaStore.Files.FileColumns.DATA }; String selection = MediaStore.Files.FileColumns.DATA + " LIKE ? OR " + MediaStore.Files.FileColumns.DATA + " LIKE ?"; String[] selectionArgs = {"%/Download/%", "%/bluetooth/%"}; String sortOrder = MediaStore.Files.FileColumns.DATE_ADDED + " DESC"; try (Cursor c = resolver.query(queryUri, projection, selection, selectionArgs, sortOrder)) { if (c != null && c.getCount() > 0) { filesBuilder.append("Recent files in Download/Bluetooth folders:\n"); int count = 0; while (c.moveToNext() && count < 10) { String name = c.getString(c.getColumnIndexOrThrow(MediaStore.Files.FileColumns.DISPLAY_NAME)); long date = c.getLong(c.getColumnIndexOrThrow(MediaStore.Files.FileColumns.DATE_ADDED)); long size = c.getLong(c.getColumnIndexOrThrow(MediaStore.Files.FileColumns.SIZE)); filesBuilder.append(String.format("- %s (%d KB, %s)\n", name, size / 1024, new Date(date * 1000L).toString())); count++; } if(filesBuilder.length() > 0) { tvBluetoothFiles.setText(filesBuilder.toString()); } else { tvBluetoothFiles.setText("No recent files found in specified folders."); } } else { tvBluetoothFiles.setText("No recent files found in Download/Bluetooth folders."); } } catch (Exception e) { tvBluetoothFiles.setText("Error reading stored files."); Log.e(TAG, "Error reading MediaStore", e); } } } 这是我的代码,需要在哪里补充代码以实现保存的wifi列表查询
最新发布
11-20
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值