Use ContextCompat.getSystemService().

This commit is contained in:
Isira Seneviratne 2020-07-22 08:10:03 +05:30
parent 8b9c624d75
commit fb8922b252
20 changed files with 59 additions and 36 deletions

View File

@ -6,6 +6,7 @@ import android.app.Instrumentation;
import android.content.Context;
import android.os.Build;
import androidx.core.content.ContextCompat;
import androidx.test.core.app.ApplicationProvider;
import androidx.test.filters.LargeTest;
import androidx.test.platform.app.InstrumentationRegistry;
@ -103,7 +104,7 @@ public class MainActivityEspressoTest {
Context context = instrumentation.getTargetContext();
ActivityManager.MemoryInfo mi = new ActivityManager.MemoryInfo();
ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
ActivityManager activityManager = ContextCompat.getSystemService(context, ActivityManager.class);
activityManager.getMemoryInfo(mi);
long percentAvail = mi.availMem / mi.totalMem;
Log.i(TAG, "RAM: " + mi.availMem + " / " + mi.totalMem + " = " + percentAvail);

View File

@ -7,23 +7,27 @@ import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.os.Process;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import android.text.TextUtils;
import android.util.Log;
import androidx.core.content.ContextCompat;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import org.fdroid.fdroid.FDroidApp;
import org.fdroid.fdroid.Preferences;
import org.fdroid.fdroid.Utils;
import org.fdroid.fdroid.nearby.peers.BonjourPeer;
import javax.jmdns.JmDNS;
import javax.jmdns.ServiceEvent;
import javax.jmdns.ServiceInfo;
import javax.jmdns.ServiceListener;
import java.io.IOException;
import java.lang.ref.WeakReference;
import java.net.InetAddress;
import java.util.HashMap;
import javax.jmdns.JmDNS;
import javax.jmdns.ServiceEvent;
import javax.jmdns.ServiceInfo;
import javax.jmdns.ServiceListener;
/**
* Manage {@link JmDNS} in a {@link HandlerThread}. The start process is in
* {@link HandlerThread#onLooperPrepared()} so that it is always started before
@ -119,8 +123,7 @@ public class BonjourManager {
}
sendBroadcast(STATUS_STARTING, null);
final WifiManager wifiManager = (WifiManager) context.getApplicationContext()
.getSystemService(Context.WIFI_SERVICE);
final WifiManager wifiManager = ContextCompat.getSystemService(context, WifiManager.class);
handlerThread = new HandlerThread("BonjourManager", Process.THREAD_PRIORITY_LESS_FAVORABLE) {
@Override
protected void onLooperPrepared() {

View File

@ -141,7 +141,7 @@ public class SelectAppsView extends SwapView implements LoaderManager.LoaderCall
private LayoutInflater getInflater(Context context) {
if (inflater == null) {
Context themedContext = new ContextThemeWrapper(context, R.style.SwapTheme_AppList_ListItem);
inflater = (LayoutInflater) themedContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
inflater = ContextCompat.getSystemService(themedContext, LayoutInflater.class);
}
return inflater;
}

View File

@ -21,6 +21,7 @@ import android.util.Log;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.NotificationCompat;
import androidx.core.content.ContextCompat;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import org.fdroid.fdroid.FDroidApp;
@ -365,7 +366,7 @@ public class SwapService extends Service {
new IntentFilter(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED));
}
wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
wifiManager = ContextCompat.getSystemService(getApplicationContext(), WifiManager.class);
if (wifiManager != null) {
SwapService.putWifiEnabledBeforeSwap(wifiManager.isWifiEnabled());
}

View File

@ -14,6 +14,7 @@ import android.os.Bundle;
import android.os.Handler;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.loader.app.LoaderManager;
import androidx.loader.content.CursorLoader;
import androidx.loader.content.Loader;
@ -361,7 +362,7 @@ public class SwapSuccessView extends SwapView implements LoaderManager.LoaderCal
@NonNull
private LayoutInflater getInflater(Context context) {
if (inflater == null) {
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
inflater = ContextCompat.getSystemService(context, LayoutInflater.class);
}
return inflater;
}

View File

@ -225,7 +225,7 @@ public class SwapWorkflowActivity extends AppCompatActivity {
localBroadcastManager.registerReceiver(downloaderInterruptedReceiver,
new IntentFilter(Downloader.ACTION_INTERRUPTED));
wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
wifiManager = ContextCompat.getSystemService(getApplicationContext(), WifiManager.class);
wifiApControl = WifiApControl.getInstance(this);
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
@ -490,7 +490,8 @@ public class SwapWorkflowActivity extends AppCompatActivity {
getSwapService().initTimer();
container.removeAllViews();
View view = ((LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE)).inflate(viewRes, container, false);
View view = ContextCompat.getSystemService(this, LayoutInflater.class)
.inflate(viewRes, container, false);
currentView = (SwapView) view;
currentView.setLayoutResId(viewRes);
currentSwapViewLayoutRes = viewRes;

View File

@ -7,7 +7,9 @@ import android.net.Uri;
import android.os.Build;
import android.os.storage.StorageManager;
import android.provider.DocumentsContract;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import java.io.File;
import java.lang.reflect.Array;
@ -47,8 +49,7 @@ public final class TreeUriUtils {
private static String getVolumePath(final String volumeId, Context context) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) return null;
try {
StorageManager mStorageManager =
(StorageManager) context.getSystemService(Context.STORAGE_SERVICE);
StorageManager mStorageManager = ContextCompat.getSystemService(context, StorageManager.class);
Class<?> storageVolumeClazz = Class.forName("android.os.storage.StorageVolume");
Method getVolumeList = mStorageManager.getClass().getMethod("getVolumeList");
Method getUuid = storageVolumeClazz.getMethod("getUuid");

View File

@ -11,6 +11,7 @@ import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import android.text.TextUtils;
import android.util.Log;
@ -88,7 +89,7 @@ public class WifiStateChangeService extends IntentService {
}
Utils.debugLog(TAG, "WiFi change service started.");
NetworkInfo ni = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
wifiManager = (WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE);
wifiManager = ContextCompat.getSystemService(getApplicationContext(), WifiManager.class);
wifiState = wifiManager.getWifiState();
Utils.debugLog(TAG, "ni == " + ni + " wifiState == " + printWifiState(wifiState));
if (ni == null

View File

@ -161,7 +161,7 @@ public class NearbyViewBinder {
storageVolumeText.setVisibility(View.GONE);
requestStorageVolume.setVisibility(View.GONE);
final StorageManager storageManager = (StorageManager) context.getSystemService(Context.STORAGE_SERVICE);
final StorageManager storageManager = ContextCompat.getSystemService(context, StorageManager.class);
for (final StorageVolume storageVolume : storageManager.getStorageVolumes()) {
if (storageVolume.isRemovable() && !storageVolume.isPrimary()) {
Log.i(TAG, "StorageVolume: " + storageVolume);

View File

@ -12,6 +12,8 @@ import android.os.Process;
import android.os.SystemClock;
import androidx.annotation.NonNull;
import androidx.core.app.JobIntentService;
import androidx.core.content.ContextCompat;
import org.apache.commons.io.FileUtils;
import org.fdroid.fdroid.installer.ApkCache;
@ -58,7 +60,7 @@ public class CleanCacheService extends JobIntentService {
SystemClock.elapsedRealtime() + 5000, interval, pending);
} else {
Utils.debugLog(TAG, "Using android-21 JobScheduler for updates");
JobScheduler jobScheduler = (JobScheduler) context.getSystemService(Context.JOB_SCHEDULER_SERVICE);
JobScheduler jobScheduler = ContextCompat.getSystemService(context, JobScheduler.class);
ComponentName componentName = new ComponentName(context, CleanCacheJobService.class);
JobInfo.Builder builder = new JobInfo.Builder(JOB_ID, componentName)
.setRequiresDeviceIdle(true)

View File

@ -42,6 +42,8 @@ import android.os.Environment;
import android.os.StrictMode;
import androidx.annotation.Nullable;
import androidx.collection.LongSparseArray;
import androidx.core.content.ContextCompat;
import android.text.TextUtils;
import android.util.Base64;
import android.util.Log;
@ -428,7 +430,8 @@ public class FDroidApp extends Application {
// submitted via app's git repos, so anyone with commit privs there could submit
// exploits hidden in images. Luckily, F-Droid doesn't need EXIF at all, and
// that is where the JPEG/PNG vulns have been. So it can be entirely stripped.
Display display = ((WindowManager) getSystemService(WINDOW_SERVICE)).getDefaultDisplay();
Display display = ContextCompat.getSystemService(this, WindowManager.class)
.getDefaultDisplay();
int maxSize = GL10.GL_MAX_TEXTURE_SIZE; // see ImageScaleType.NONE_SAFE javadoc
int width = display.getWidth();
if (width > maxSize) {
@ -554,7 +557,7 @@ public class FDroidApp extends Application {
* for end users than experiencing a deterministic crash every time F-Droid is started.
*/
private boolean isAcraProcess() {
ActivityManager manager = (ActivityManager) this.getSystemService(Context.ACTIVITY_SERVICE);
ActivityManager manager = ContextCompat.getSystemService(this, ActivityManager.class);
List<RunningAppProcessInfo> processes = manager.getRunningAppProcesses();
if (processes == null) {
return false;
@ -578,7 +581,7 @@ public class FDroidApp extends Application {
@TargetApi(16)
private int getThreadPoolSize() {
if (Build.VERSION.SDK_INT >= 16) {
ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
ActivityManager activityManager = ContextCompat.getSystemService(this, ActivityManager.class);
ActivityManager.MemoryInfo memInfo = new ActivityManager.MemoryInfo();
if (activityManager != null) {
activityManager.getMemoryInfo(memInfo);

View File

@ -28,6 +28,8 @@ import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import androidx.core.content.ContextCompat;
import androidx.preference.PreferenceManager;
import android.text.format.DateUtils;
import android.util.Log;
@ -457,7 +459,7 @@ public final class Preferences implements SharedPreferences.OnSharedPreferenceCh
* Some users never use WiFi, this lets us check for that state on first run.
*/
public void setDefaultForDataOnlyConnection(Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
ConnectivityManager cm = ContextCompat.getSystemService(context, ConnectivityManager.class);
if (cm == null) {
return;
}

View File

@ -41,6 +41,7 @@ import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.core.app.JobIntentService;
import androidx.core.app.NotificationCompat;
import androidx.core.content.ContextCompat;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import org.fdroid.fdroid.data.Apk;
@ -164,7 +165,7 @@ public class UpdateService extends JobIntentService {
}
} else {
Utils.debugLog(TAG, "Using android-21 JobScheduler for updates");
JobScheduler jobScheduler = (JobScheduler) context.getSystemService(Context.JOB_SCHEDULER_SERVICE);
JobScheduler jobScheduler = ContextCompat.getSystemService(context, JobScheduler.class);
ComponentName componentName = new ComponentName(context, UpdateJobService.class);
JobInfo.Builder builder = new JobInfo.Builder(JOB_ID, componentName)
.setRequiresDeviceIdle(true)
@ -257,7 +258,7 @@ public class UpdateService extends JobIntentService {
super.onCreate();
updateService = this;
notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager = ContextCompat.getSystemService(this, NotificationManager.class);
notificationBuilder = new NotificationCompat.Builder(this, NotificationHelper.CHANNEL_UPDATES)
.setSmallIcon(R.drawable.ic_refresh)

View File

@ -9,6 +9,7 @@ import android.net.NetworkInfo;
import android.os.Build;
import androidx.annotation.NonNull;
import androidx.core.app.JobIntentService;
import androidx.core.content.ContextCompat;
import androidx.core.net.ConnectivityManagerCompat;
import android.util.Log;
@ -79,7 +80,7 @@ public class ConnectivityMonitorService extends JobIntentService {
* cases when looking through the network devices, especially on bad ROMs.
*/
public static int getNetworkState(Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(CONNECTIVITY_SERVICE);
ConnectivityManager cm = ContextCompat.getSystemService(context, ConnectivityManager.class);;
if (cm == null) {
return FLAG_NET_UNAVAILABLE;
}

View File

@ -236,7 +236,7 @@ public class AppSecurityPermissions {
private AppSecurityPermissions(Context context) {
this.context = context;
inflater = (LayoutInflater) this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
inflater = ContextCompat.getSystemService(this.context, LayoutInflater.class);
pm = this.context.getPackageManager();
// Pick up from framework resources instead.
newPermPrefix = this.context.getText(R.string.perms_new_perm_prefix);

View File

@ -18,13 +18,14 @@
package org.fdroid.fdroid.privileged.views;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.net.Uri;
import android.os.Bundle;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.FragmentActivity;
import androidx.viewpager.widget.ViewPager;
import android.view.LayoutInflater;
@ -118,8 +119,7 @@ public class InstallConfirmActivity extends FragmentActivity implements OnCancel
final int n = perms.getPermissionCount(AppSecurityPermissions.WHICH_ALL);
if (n > 0) {
permVisible = true;
LayoutInflater inflater = (LayoutInflater) getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
LayoutInflater inflater = ContextCompat.getSystemService(this, LayoutInflater.class);
View root = inflater.inflate(R.layout.permissions_list, null);
if (scrollView == null) {
scrollView = (CaffeinatedScrollView) root.findViewById(R.id.scrollview);

View File

@ -9,6 +9,7 @@ import android.util.Log;
import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.core.content.ContextCompat;
@RequiresApi(Build.VERSION_CODES.LOLLIPOP)
public class CameraCharacteristicsMinApiLevel21 extends CameraCharacteristicsChecker {
@ -17,7 +18,7 @@ public class CameraCharacteristicsMinApiLevel21 extends CameraCharacteristicsChe
private final CameraManager cameraManager;
protected CameraCharacteristicsMinApiLevel21(final Context context) {
this.cameraManager = (CameraManager) context.getSystemService(Context.CAMERA_SERVICE);
this.cameraManager = ContextCompat.getSystemService(context, CameraManager.class);
}
@Override

View File

@ -25,6 +25,7 @@ import android.annotation.TargetApi;
import android.app.Activity;
import android.app.PendingIntent;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
@ -37,6 +38,7 @@ import android.os.Bundle;
import android.os.Handler;
import androidx.annotation.Nullable;
import androidx.coordinatorlayout.widget.CoordinatorLayout;
import androidx.core.content.ContextCompat;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
@ -702,7 +704,7 @@ public class AppDetailsActivity extends AppCompatActivity
if (Build.VERSION.SDK_INT < 18) {
return BluetoothAdapter.getDefaultAdapter();
}
return ((android.bluetooth.BluetoothManager) getSystemService(BLUETOOTH_SERVICE)).getAdapter();
return ContextCompat.getSystemService(this, BluetoothManager.class).getAdapter();
}
@Override

View File

@ -182,7 +182,7 @@ public class ManageReposActivity extends AppCompatActivity
public String getPrimaryClipAsText() {
CharSequence text = null;
ClipboardManager clipboardManager = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
ClipboardManager clipboardManager = ContextCompat.getSystemService(this, ClipboardManager.class);
if (clipboardManager.hasPrimaryClip()) {
ClipData data = clipboardManager.getPrimaryClip();
if (data.getItemCount() > 0) {
@ -838,7 +838,8 @@ public class ManageReposActivity extends AppCompatActivity
private void checkIfNewRepoOnSameWifi(NewRepoConfig newRepo) {
// if this is a local repo, check we're on the same wifi
if (!TextUtils.isEmpty(newRepo.getBssid())) {
WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
WifiManager wifiManager = ContextCompat.getSystemService(getApplicationContext(),
WifiManager.class);
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
String bssid = wifiInfo.getBSSID();
if (TextUtils.isEmpty(bssid)) { /* not all devices have wifi */

View File

@ -20,7 +20,6 @@
package org.fdroid.fdroid.views.apps;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
@ -96,7 +95,8 @@ public class AppListActivity extends AppCompatActivity implements LoaderManager.
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_SEARCH) {
// Hide the keyboard (http://stackoverflow.com/a/1109108 (when pressing search)
InputMethodManager inputManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
InputMethodManager inputManager = ContextCompat.getSystemService(AppListActivity.this,
InputMethodManager.class);
inputManager.hideSoftInputFromWindow(searchInput.getWindowToken(), 0);
// Change focus from the search input to the app list.
@ -148,7 +148,8 @@ public class AppListActivity extends AppCompatActivity implements LoaderManager.
searchInput.requestFocus();
if (!keyboardStateMonitor.isKeyboardVisible()) {
InputMethodManager inputMethodManager =
(InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
ContextCompat.getSystemService(AppListActivity.this,
InputMethodManager.class);
inputMethodManager.toggleSoftInputFromWindow(v.getApplicationWindowToken(),
InputMethodManager.SHOW_FORCED, 0);
}