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列表查询
最新发布