YAOXILONG can you add service to Bluetooth cache cleanup ? import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.IBinder;
import android.util.Log;
import java.io.IOException;
public class BluetoothCacheClearService extends Service {
private static final String TAG = "BluetoothCacheClear";
private BroadcastReceiver shutdownReceiver;
private BroadcastReceiver rebootReceiver;
@Override
public void onCreate() {
super.onCreate();
// Shutdown receiver
shutdownReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (Intent.ACTION_SHUTDOWN.equals(intent.getAction()) ||
Intent.ACTION_POWER_OFF.equals(intent.getAction())) {
Log.d(TAG, "Device is shutting down. Clearing Bluetooth cache.");
clearBluetoothCache();
}
}
};
IntentFilter shutdownFilter = new IntentFilter();
shutdownFilter.addAction(Intent.ACTION_SHUTDOWN);
shutdownFilter.addAction(Intent.ACTION_POWER_OFF); // Some devices use this.
registerReceiver(shutdownReceiver, shutdownFilter);
// Reboot finished receiver (for after a reboot)
rebootReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction())) {
Log.d(TAG, "Device has booted. Clearing Bluetooth cache.");
clearBluetoothCache();
}
}
};
IntentFilter rebootFilter = new IntentFilter(Intent.ACTION_BOOT_COMPLETED);
registerReceiver(rebootReceiver, rebootFilter);
Log.d(TAG, "Service created.");
}
private void clearBluetoothCache() {
try {
// This requires root privileges. There is NO non-root way to reliably clear the Bluetooth cache.
Process process = Runtime.getRuntime().exec("pm clear com.android.bluetooth"); // Or the specific package name for your device.
int result = process.waitFor();
if (result == 0) {
Log.i(TAG, "Bluetooth cache cleared successfully.");
} else {
Log.e(TAG, "Failed to clear Bluetooth cache. Return code: " + result);
}
} catch (IOException | InterruptedException e) {
Log.e(TAG, "Error clearing Bluetooth cache: ", e);
}
}
@Override
public IBinder onBind(Intent intent) {
return null; // This is a started service, not a bound service.
}
@Override
public void onDestroy() {
super.onDestroy();
if (shutdownReceiver != null) {
unregisterReceiver(shutdownReceiver);
}
if (rebootReceiver != null) {
unregisterReceiver(rebootReceiver);
}
Log.d(TAG, "Service destroyed.");
}
}