Bug 1369107 - 1. Remove usages of GeckoAppShell.getContext(); r=droeh
authorJim Chen <nchen@mozilla.com>
Fri, 02 Jun 2017 16:13:41 -0400
changeset 412633 b6337d9fa55e9c74a23ecb786f9afa91d21556a7
parent 412632 0a58469c18011216c9f1d0e052f6a0d9bf799543
child 412634 685f48a31f21eaeb7df0529b392d2899f0a5c01f
push id1490
push usermtabara@mozilla.com
push dateMon, 31 Jul 2017 14:08:16 +0000
treeherdermozilla-release@70e32e6bf15e [default view] [failures only]
perfherder[talos] [build metrics] [platform microbench] (compared to previous push)
reviewersdroeh
bugs1369107
milestone55.0a1
first release with
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
last release without
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
Bug 1369107 - 1. Remove usages of GeckoAppShell.getContext(); r=droeh Replace usages of GeckoAppShell.getContext() with getApplicationContext() if possible, or the current Activity if the usage expects an Activity context. MozReview-Commit-ID: 9GOWszgEsQu
mobile/android/base/java/org/mozilla/gecko/BrowserApp.java
mobile/android/base/java/org/mozilla/gecko/DownloadsIntegration.java
mobile/android/base/java/org/mozilla/gecko/ThumbnailHelper.java
mobile/android/base/java/org/mozilla/gecko/prompts/PromptListItem.java
mobile/android/base/java/org/mozilla/gecko/updater/PostUpdateHandler.java
mobile/android/base/java/org/mozilla/gecko/webapps/WebAppActivity.java
mobile/android/tests/browser/chrome/test_jni.html
--- a/mobile/android/base/java/org/mozilla/gecko/BrowserApp.java
+++ b/mobile/android/base/java/org/mozilla/gecko/BrowserApp.java
@@ -1788,17 +1788,17 @@ public class BrowserApp extends GeckoApp
                             menu.findItem(R.id.help).setEnabled(true);
                         }
                     }
                 });
 
                 // Display notification for Mozilla data reporting, if data should be collected.
                 if (AppConstants.MOZ_DATA_REPORTING &&
                         Restrictions.isAllowed(this, Restrictable.DATA_CHOICES)) {
-                    DataReportingNotification.checkAndNotifyPolicy(GeckoAppShell.getContext());
+                    DataReportingNotification.checkAndNotifyPolicy(this);
                 }
                 break;
 
             case "Gecko:DelayedStartup":
                 EventDispatcher.getInstance().unregisterUiThreadListener(this, "Gecko:DelayedStartup");
 
                 // Force tabs panel inflation once the initial pageload is finished.
                 ensureTabsPanelExists();
@@ -1984,22 +1984,22 @@ public class BrowserApp extends GeckoApp
                 break;
 
             case "Experiments:GetActive":
                 final List<String> experiments = SwitchBoard.getActiveExperiments(this);
                 callback.sendSuccess(experiments.toArray(new String[experiments.size()]));
                 break;
 
             case "Experiments:SetOverride":
-                Experiments.setOverride(getContext(), message.getString("name"),
+                Experiments.setOverride(this, message.getString("name"),
                                         message.getBoolean("isEnabled"));
                 break;
 
             case "Experiments:ClearOverride":
-                Experiments.clearOverride(getContext(), message.getString("name"));
+                Experiments.clearOverride(this, message.getString("name"));
                 break;
 
             case "Favicon:Request":
                 final String url = message.getString("url");
                 final boolean shouldSkipNetwork = message.getBoolean("skipNetwork");
 
                 if (TextUtils.isEmpty(url)) {
                     callback.sendError(null);
@@ -2035,17 +2035,17 @@ public class BrowserApp extends GeckoApp
 
             case "Sanitize:ClearHistory":
                 BrowserDB.from(getProfile()).clearHistory(
                         getContentResolver(), message.getBoolean("clearSearchHistory", false));
                 callback.sendSuccess(null);
                 break;
 
             case "Sanitize:ClearSyncedTabs":
-                FennecTabsRepository.deleteNonLocalClientsAndTabs(getContext());
+                FennecTabsRepository.deleteNonLocalClientsAndTabs(this);
                 callback.sendSuccess(null);
                 break;
 
             case "Settings:Show":
                 final Intent settingsIntent = new Intent(this, GeckoPreferences.class);
                 final String resource = message.getString(GeckoPreferences.INTENT_EXTRA_RESOURCES);
 
                 GeckoPreferences.setResourceToOpen(settingsIntent, resource);
@@ -2064,42 +2064,42 @@ public class BrowserApp extends GeckoApp
 
                 Telemetry.addToHistogram("PLACES_PAGES_COUNT", db.getCount(cr, "history"));
                 Telemetry.addToHistogram("FENNEC_BOOKMARKS_COUNT", db.getCount(cr, "bookmarks"));
                 Telemetry.addToHistogram("BROWSER_IS_USER_DEFAULT",
                         (isDefaultBrowser(Intent.ACTION_VIEW) ? 1 : 0));
                 Telemetry.addToHistogram("FENNEC_CUSTOM_HOMEPAGE",
                         (Tabs.hasHomepage(this) ? 1 : 0));
 
-                final SharedPreferences prefs = GeckoSharedPrefs.forProfile(getContext());
+                final SharedPreferences prefs = GeckoSharedPrefs.forProfile(this);
                 final boolean hasCustomHomepanels =
                         prefs.contains(HomeConfigPrefsBackend.PREFS_CONFIG_KEY) ||
                         prefs.contains(HomeConfigPrefsBackend.PREFS_CONFIG_KEY_OLD);
 
                 Telemetry.addToHistogram("FENNEC_HOMEPANELS_CUSTOM", hasCustomHomepanels ? 1 : 0);
 
                 Telemetry.addToHistogram("FENNEC_READER_VIEW_CACHE_SIZE",
-                        SavedReaderViewHelper.getSavedReaderViewHelper(getContext())
+                        SavedReaderViewHelper.getSavedReaderViewHelper(this)
                                              .getDiskSpacedUsedKB());
 
                 if (Versions.feature16Plus) {
                     Telemetry.addToHistogram("BROWSER_IS_ASSIST_DEFAULT",
                             (isDefaultBrowser(Intent.ACTION_ASSIST) ? 1 : 0));
                 }
 
                 Telemetry.addToHistogram("FENNEC_ORBOT_INSTALLED",
-                    ContextUtils.isPackageInstalled(getContext(), "org.torproject.android") ? 1 : 0);
+                    ContextUtils.isPackageInstalled(this, "org.torproject.android") ? 1 : 0);
                 break;
 
             case "Website:AppInstalled":
                 final String name = message.getString("name");
                 final String startUrl = message.getString("start_url");
                 final String manifestPath = message.getString("manifest_path");
                 final LoadFaviconResult loadIconResult = FaviconDecoder
-                    .decodeDataURI(getContext(), message.getString("icon"));
+                    .decodeDataURI(this, message.getString("icon"));
                 if (loadIconResult != null) {
                     final Bitmap icon = loadIconResult
                         .getBestBitmap(GeckoAppShell.getPreferredIconSize());
                     GeckoApplication.createAppShortcut(name, startUrl, manifestPath, icon);
                 } else {
                     Log.e(LOGTAG, "Failed to load icon!");
                 }
 
@@ -2826,19 +2826,19 @@ public class BrowserApp extends GeckoApp
                     delegate.onActivityResult(this, requestCode, resultCode, data);
                 }
 
                 super.onActivityResult(requestCode, resultCode, data);
         }
     }
 
     private void showFirstrunPager() {
-        if (Experiments.isInExperimentLocal(getContext(), Experiments.ONBOARDING3_A)) {
+        if (Experiments.isInExperimentLocal(this, Experiments.ONBOARDING3_A)) {
             Telemetry.startUISession(TelemetryContract.Session.EXPERIMENT, Experiments.ONBOARDING3_A);
-            GeckoSharedPrefs.forProfile(getContext()).edit().putString(Experiments.PREF_ONBOARDING_VERSION, Experiments.ONBOARDING3_A).apply();
+            GeckoSharedPrefs.forProfile(this).edit().putString(Experiments.PREF_ONBOARDING_VERSION, Experiments.ONBOARDING3_A).apply();
             Telemetry.stopUISession(TelemetryContract.Session.EXPERIMENT, Experiments.ONBOARDING3_A);
             return;
         }
 
         if (mFirstrunAnimationContainer == null) {
             final ViewStub firstrunPagerStub = (ViewStub) findViewById(R.id.firstrun_pager_stub);
             mFirstrunAnimationContainer = (FirstrunAnimationContainer) firstrunPagerStub.inflate();
             mFirstrunAnimationContainer.load(getApplicationContext(), getSupportFragmentManager());
@@ -4117,17 +4117,17 @@ public class BrowserApp extends GeckoApp
             startActivity(intent);
         } else {
             // By default this listener is used for lists where the offline reader-view icon
             // is shown - hence we need to redirect to the reader-view page by default.
             // However there are some cases where we might not want to use this, e.g.
             // for topsites where we do not indicate that a page is an offline reader-view bookmark too.
             final String pageURL;
             if (!flags.contains(OnUrlOpenListener.Flags.NO_READER_VIEW)) {
-                pageURL = SavedReaderViewHelper.getReaderURLIfCached(getContext(), url);
+                pageURL = SavedReaderViewHelper.getReaderURLIfCached(this, url);
             } else {
                 pageURL = url;
             }
 
             if (!maybeSwitchToTab(pageURL, flags)) {
                 openUrlAndStopEditing(pageURL);
                 clearSelectedTabApplicationId();
             }
@@ -4141,17 +4141,17 @@ public class BrowserApp extends GeckoApp
             throw new IllegalArgumentException("url must not be null");
         }
         if (flags == null) {
             throw new IllegalArgumentException("flags must not be null");
         }
 
         // We only use onUrlOpenInBackgroundListener for the homepanel context menus, hence
         // we should always be checking whether we want the readermode version
-        final String pageURL = SavedReaderViewHelper.getReaderURLIfCached(getContext(), url);
+        final String pageURL = SavedReaderViewHelper.getReaderURLIfCached(this, url);
 
         final boolean isPrivate = flags.contains(OnUrlOpenInBackgroundListener.Flags.PRIVATE);
 
         int loadFlags = Tabs.LOADURL_NEW_TAB | Tabs.LOADURL_BACKGROUND;
         if (isPrivate) {
             loadFlags |= Tabs.LOADURL_PRIVATE;
         }
 
--- a/mobile/android/base/java/org/mozilla/gecko/DownloadsIntegration.java
+++ b/mobile/android/base/java/org/mozilla/gecko/DownloadsIntegration.java
@@ -13,16 +13,17 @@ import org.mozilla.gecko.util.EventCallb
 import org.mozilla.gecko.util.GeckoBundle;
 
 import java.io.File;
 import java.lang.IllegalArgumentException;
 import java.util.ArrayList;
 import java.util.Collections;
 import java.util.List;
 
+import android.app.Activity;
 import android.app.DownloadManager;
 import android.content.Context;
 import android.content.pm.PackageManager;
 import android.database.Cursor;
 import android.media.MediaScannerConnection;
 import android.media.MediaScannerConnection.MediaScannerConnectionClient;
 import android.net.Uri;
 import android.os.Environment;
@@ -98,17 +99,19 @@ public class DownloadsIntegration implem
 
     private static boolean useSystemDownloadManager() {
         if (!AppConstants.ANDROID_DOWNLOADS_INTEGRATION) {
             return false;
         }
 
         int state = PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
         try {
-            state = GeckoAppShell.getContext().getPackageManager().getApplicationEnabledSetting("com.android.providers.downloads");
+            final PackageManager pm = GeckoAppShell.getApplicationContext()
+                                                   .getPackageManager();
+            state = pm.getApplicationEnabledSetting("com.android.providers.downloads");
         } catch (IllegalArgumentException e) {
             // Download Manager package does not exist
             return false;
         }
 
         return (PackageManager.COMPONENT_ENABLED_STATE_ENABLED == state ||
                 PackageManager.COMPONENT_ENABLED_STATE_DEFAULT == state);
     }
@@ -156,37 +159,46 @@ public class DownloadsIntegration implem
                 mimeType = UNKNOWN_MIME_TYPES.get(0);
             } else {
                 mimeType = aMimeType;
             }
         }
 
         if (useSystemDownloadManager()) {
             final File f = new File(aFile);
-            final DownloadManager dm = (DownloadManager) GeckoAppShell.getContext().getSystemService(Context.DOWNLOAD_SERVICE);
+            final DownloadManager dm = (DownloadManager)
+                    GeckoAppShell.getApplicationContext()
+                                 .getSystemService(Context.DOWNLOAD_SERVICE);
             dm.addCompletedDownload(f.getName(),
                     f.getName(),
                     true, // Media scanner should scan this
                     mimeType,
                     f.getAbsolutePath(),
                     Math.max(1, f.length()), // Some versions of Android require downloads to be at least length 1
                     false); // Don't show a notification.
         } else {
-            final Context context = GeckoAppShell.getContext();
-            final GeckoMediaScannerClient client = new GeckoMediaScannerClient(context, aFile, mimeType);
+            final Activity currentActivity =
+                    GeckoActivityMonitor.getInstance().getCurrentActivity();
+            if (currentActivity == null) {
+                return;
+            }
+            final GeckoMediaScannerClient client =
+                    new GeckoMediaScannerClient(currentActivity, aFile, mimeType);
             client.connect();
         }
     }
 
     public static void removeDownload(final Download download) {
         if (!useSystemDownloadManager()) {
             return;
         }
 
-        final DownloadManager dm = (DownloadManager) GeckoAppShell.getContext().getSystemService(Context.DOWNLOAD_SERVICE);
+        final DownloadManager dm = (DownloadManager)
+                GeckoAppShell.getApplicationContext()
+                             .getSystemService(Context.DOWNLOAD_SERVICE);
 
         Cursor c = null;
         try {
             c = dm.query((new DownloadManager.Query()).setFilterByStatus(DownloadManager.STATUS_SUCCESSFUL));
             if (c == null || !c.moveToFirst()) {
                 return;
             }
 
--- a/mobile/android/base/java/org/mozilla/gecko/ThumbnailHelper.java
+++ b/mobile/android/base/java/org/mozilla/gecko/ThumbnailHelper.java
@@ -62,17 +62,17 @@ public final class ThumbnailHelper {
 
     private final ArrayList<Tab> mPendingThumbnails;    // synchronized access only
     private volatile int mPendingWidth;
     private int mWidth;
     private int mHeight;
     private ByteBuffer mBuffer;
 
     private ThumbnailHelper() {
-        final Resources res = GeckoAppShell.getContext().getResources();
+        final Resources res = GeckoAppShell.getApplicationContext().getResources();
 
         mPendingThumbnails = new ArrayList<>();
         try {
             mPendingWidth = (int) res.getDimension(R.dimen.tab_thumbnail_width);
         } catch (Resources.NotFoundException nfe) {
         }
         mWidth = -1;
         mHeight = -1;
--- a/mobile/android/base/java/org/mozilla/gecko/prompts/PromptListItem.java
+++ b/mobile/android/base/java/org/mozilla/gecko/prompts/PromptListItem.java
@@ -25,17 +25,17 @@ public class PromptListItem {
     public final boolean showAsActions;
     public final boolean isParent;
 
     public Intent mIntent;
     public boolean mSelected;
     public Drawable mIcon;
 
     PromptListItem(GeckoBundle aObject) {
-        Context context = GeckoAppShell.getContext();
+        final Context context = GeckoAppShell.getApplicationContext();
         label = aObject.getString("label", "");
         isGroup = aObject.getBoolean("isGroup");
         inGroup = aObject.getBoolean("inGroup");
         disabled = aObject.getBoolean("disabled");
         id = aObject.getInt("id");
         mSelected = aObject.getBoolean("selected");
 
         GeckoBundle obj = aObject.getBundle("showAsActions");
--- a/mobile/android/base/java/org/mozilla/gecko/updater/PostUpdateHandler.java
+++ b/mobile/android/base/java/org/mozilla/gecko/updater/PostUpdateHandler.java
@@ -50,17 +50,17 @@ public class PostUpdateHandler extends B
     /**
      * Copies the /assets/features folder out of the APK and into the app's data directory.
      */
     private void copyFeaturesFromAPK(BrowserApp browserApp) {
         Log.d(LOGTAG, "Copying system add-ons from APK to dataDir");
 
         final String dataDir = browserApp.getApplicationInfo().dataDir;
         final SharedPreferences prefs = GeckoSharedPrefs.forApp(browserApp);
-        final AssetManager assetManager = browserApp.getContext().getAssets();
+        final AssetManager assetManager = browserApp.getAssets();
 
         try {
             final String[] assetNames = assetManager.list("features");
 
             for (int i = 0; i < assetNames.length; i++) {
                 final String assetPath = "features/" + assetNames[i];
 
                 Log.d(LOGTAG, "Copying '" + assetPath + "' from APK to dataDir");
--- a/mobile/android/base/java/org/mozilla/gecko/webapps/WebAppActivity.java
+++ b/mobile/android/base/java/org/mozilla/gecko/webapps/WebAppActivity.java
@@ -277,15 +277,15 @@ public class WebAppActivity extends Sing
     }
 
     private Bitmap readIconFromManifest(JSONObject manifest) {
         final String iconStr = manifest.optString("cached_icon", null);
         if (iconStr == null) {
             return null;
         }
         final LoadFaviconResult loadIconResult = FaviconDecoder
-            .decodeDataURI(getContext(), iconStr);
+            .decodeDataURI(this, iconStr);
         if (loadIconResult == null) {
             return null;
         }
         return loadIconResult.getBestBitmap(GeckoAppShell.getPreferredIconSize());
     }
 }
--- a/mobile/android/tests/browser/chrome/test_jni.html
+++ b/mobile/android/tests/browser/chrome/test_jni.html
@@ -19,17 +19,17 @@ Migrated from Robocop: https://bugzilla.
     var jenv = null;
     try {
       jenv = JNI.GetForThread();
 
       // Test a simple static method.
       var geckoAppShell = JNI.LoadClass(jenv, "org.mozilla.gecko.GeckoAppShell", {
         static_methods: [
           { name: "getPreferredIconSize", sig: "()I" },
-          { name: "getContext", sig: "()Landroid/content/Context;" },
+          { name: "getApplicationContext", sig: "()Landroid/content/Context;" },
         ],
       });
 
       let iconSize = -1;
       iconSize = geckoAppShell.getPreferredIconSize();
       isnot(iconSize, -1, "icon size is valid");
 
       // Test GeckoNetworkManager methods that are accessed by PaymentsUI.js.
@@ -51,17 +51,17 @@ Migrated from Robocop: https://bugzilla.
           { name: "getClass", sig: "()Ljava/lang/Class;" },
         ],
       });
       JNI.LoadClass(jenv, "java.lang.Class", {
         methods: [
           { name: "getName", sig: "()Ljava/lang/String;" },
         ],
       });
-      is("org.mozilla.gecko.BrowserApp", JNI.ReadString(jenv, geckoAppShell.getContext().getClass().getName()), "class name is correct");
+      is("org.mozilla.gecko.GeckoApplication", JNI.ReadString(jenv, geckoAppShell.getApplicationContext().getClass().getName()), "class name is correct");
     } finally {
       if (jenv) {
         JNI.UnloadClasses(jenv);
       }
     }
   }
 
   test_JNI();