Cleanup contexts

This commit is contained in:
topjohnwu 2017-10-16 00:54:48 +08:00
parent c036f6d529
commit 896ca2ef6b
25 changed files with 99 additions and 141 deletions

View File

@ -176,8 +176,8 @@ public class MagiskFragment extends Fragment
shownDialog = false; shownDialog = false;
// Trigger state check // Trigger state check
if (Utils.checkNetworkStatus(mm)) { if (Utils.checkNetworkStatus()) {
new CheckUpdates(getActivity()).exec(); new CheckUpdates().exec();
} else { } else {
mSwipeRefreshLayout.setRefreshing(false); mSwipeRefreshLayout.setRefreshing(false);
} }
@ -230,7 +230,7 @@ public class MagiskFragment extends Fragment
private void updateUI() { private void updateUI() {
((MainActivity) getActivity()).checkHideSection(); ((MainActivity) getActivity()).checkHideSection();
boolean hasNetwork = Utils.checkNetworkStatus(getActivity()); boolean hasNetwork = Utils.checkNetworkStatus();
boolean hasRoot = Shell.rootAccess(); boolean hasRoot = Shell.rootAccess();
boolean isUpToDate = mm.magiskVersionCode > 1300; boolean isUpToDate = mm.magiskVersionCode > 1300;

View File

@ -170,9 +170,9 @@ public class MagiskLogFragment extends Fragment {
case 2: case 2:
boolean bool = (boolean) o; boolean bool = (boolean) o;
if (bool) { if (bool) {
getMagiskManager().toast(targetFile.toString(), Toast.LENGTH_LONG); MagiskManager.toast(targetFile.toString(), Toast.LENGTH_LONG);
} else { } else {
getMagiskManager().toast(R.string.logs_save_failed, Toast.LENGTH_LONG); MagiskManager.toast(R.string.logs_save_failed, Toast.LENGTH_LONG);
} }
break; break;
} }

View File

@ -32,6 +32,7 @@ import com.topjohnwu.magisk.utils.Utils;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.lang.ref.WeakReference;
import java.util.List; import java.util.List;
import java.util.Locale; import java.util.Locale;
import java.util.Map; import java.util.Map;
@ -39,6 +40,9 @@ import java.util.concurrent.ExecutionException;
public class MagiskManager extends Application { public class MagiskManager extends Application {
// Global weak reference to self
private static WeakReference<MagiskManager> weakSelf;
public static final String MAGISK_DISABLE_FILE = "/cache/.disable_magisk"; public static final String MAGISK_DISABLE_FILE = "/cache/.disable_magisk";
public static final String MAGISK_HOST_FILE = "/magisk/.core/hosts"; public static final String MAGISK_HOST_FILE = "/magisk/.core/hosts";
public static final String TMP_FOLDER_PATH = "/dev/tmp"; public static final String TMP_FOLDER_PATH = "/dev/tmp";
@ -110,21 +114,17 @@ public class MagiskManager extends Application {
private static Handler mHandler = new Handler(); private static Handler mHandler = new Handler();
private boolean started = false; private boolean started = false;
private static class LoadLocale extends ParallelTask<Void, Void, Void> { private class LoadLocale extends ParallelTask<Void, Void, Void> {
LoadLocale(Context context) {
super(context);
}
@Override @Override
protected Void doInBackground(Void... voids) { protected Void doInBackground(Void... voids) {
getMagiskManager().locales = Utils.getAvailableLocale(getMagiskManager()); locales = Utils.getAvailableLocale();
return null; return null;
} }
@Override @Override
protected void onPostExecute(Void aVoid) { protected void onPostExecute(Void aVoid) {
getMagiskManager().localeDone.publish(); localeDone.publish();
} }
} }
@ -137,15 +137,20 @@ public class MagiskManager extends Application {
// Don't migrate yet, wait and check Magisk version // Don't migrate yet, wait and check Magisk version
suDB = new SuDatabaseHelper(this); suDB = new SuDatabaseHelper(this);
} else { } else {
suDB = new SuDatabaseHelper(Utils.getEncContext(this)); suDB = new SuDatabaseHelper(Utils.getEncContext());
} }
weakSelf = new WeakReference<>(this);
repoDB = new RepoDatabaseHelper(this); repoDB = new RepoDatabaseHelper(this);
defaultLocale = Locale.getDefault(); defaultLocale = Locale.getDefault();
setLocale(); setLocale();
loadConfig(); loadConfig();
} }
public static MagiskManager get() {
return weakSelf.get();
}
public void setLocale() { public void setLocale() {
localeConfig = prefs.getString("locale", ""); localeConfig = prefs.getString("locale", "");
if (localeConfig.isEmpty()) { if (localeConfig.isEmpty()) {
@ -177,12 +182,12 @@ public class MagiskManager extends Application {
snet_version = prefs.getInt("snet_version", -1); snet_version = prefs.getInt("snet_version", -1);
} }
public void toast(String msg, int duration) { public static void toast(String msg, int duration) {
mHandler.post(() -> Toast.makeText(this, msg, duration).show()); mHandler.post(() -> Toast.makeText(weakSelf.get(), msg, duration).show());
} }
public void toast(int resId, int duration) { public static void toast(int resId, int duration) {
mHandler.post(() -> Toast.makeText(this, resId, duration).show()); mHandler.post(() -> Toast.makeText(weakSelf.get(), resId, duration).show());
} }
public void startup() { public void startup() {
@ -190,7 +195,7 @@ public class MagiskManager extends Application {
return; return;
started = true; started = true;
boolean hasNetwork = Utils.checkNetworkStatus(this); boolean hasNetwork = Utils.checkNetworkStatus();
getMagiskInfo(); getMagiskInfo();
@ -204,14 +209,14 @@ public class MagiskManager extends Application {
} }
} }
new LoadLocale(this).exec(); new LoadLocale().exec();
// Root actions // Root actions
if (Shell.rootAccess()) { if (Shell.rootAccess()) {
if (hasNetwork && !Utils.itemExist(BUSYBOXPATH + "/busybox")) { if (hasNetwork && !Utils.itemExist(BUSYBOXPATH + "/busybox")) {
try { try {
// Force synchronous, make sure we have busybox to use // Force synchronous, make sure we have busybox to use
new DownloadBusybox(this).exec().get(); new DownloadBusybox().exec().get();
} catch (InterruptedException | ExecutionException e) { } catch (InterruptedException | ExecutionException e) {
e.printStackTrace(); e.printStackTrace();
} }
@ -265,7 +270,7 @@ public class MagiskManager extends Application {
getSystemService(NotificationManager.class).createNotificationChannel(channel); getSystemService(NotificationManager.class).createNotificationChannel(channel);
} }
LoadModules loadModuleTask = new LoadModules(this); LoadModules loadModuleTask = new LoadModules();
// Start update check job // Start update check job
if (hasNetwork) { if (hasNetwork) {
ComponentName service = new ComponentName(this, UpdateCheckService.class); ComponentName service = new ComponentName(this, UpdateCheckService.class);
@ -275,7 +280,7 @@ public class MagiskManager extends Application {
.setPeriodic(8 * 60 * 60 * 1000) .setPeriodic(8 * 60 * 60 * 1000)
.build(); .build();
((JobScheduler) getSystemService(Context.JOB_SCHEDULER_SERVICE)).schedule(jobInfo); ((JobScheduler) getSystemService(Context.JOB_SCHEDULER_SERVICE)).schedule(jobInfo);
loadModuleTask.setCallBack(() -> new UpdateRepos(this, false).exec()); loadModuleTask.setCallBack(() -> new UpdateRepos(false).exec());
} }
// Fire asynctasks // Fire asynctasks
loadModuleTask.exec(); loadModuleTask.exec();
@ -284,7 +289,6 @@ public class MagiskManager extends Application {
public void getMagiskInfo() { public void getMagiskInfo() {
List<String> ret; List<String> ret;
Shell.registerShell(this);
ret = Shell.sh("su -v"); ret = Shell.sh("su -v");
if (Utils.isValidShellResponse(ret)) { if (Utils.isValidShellResponse(ret)) {
suVersion = ret.get(0); suVersion = ret.get(0);

View File

@ -118,7 +118,7 @@ public class MainActivity extends Activity
&& prefs.getBoolean("magiskhide", false)); && prefs.getBoolean("magiskhide", false));
menu.findItem(R.id.modules).setVisible( menu.findItem(R.id.modules).setVisible(
Shell.rootAccess() && getMagiskManager().magiskVersionCode >= 0); Shell.rootAccess() && getMagiskManager().magiskVersionCode >= 0);
menu.findItem(R.id.downloads).setVisible(Utils.checkNetworkStatus(this) && menu.findItem(R.id.downloads).setVisible(Utils.checkNetworkStatus() &&
Shell.rootAccess() && getMagiskManager().magiskVersionCode >= 0); Shell.rootAccess() && getMagiskManager().magiskVersionCode >= 0);
menu.findItem(R.id.log).setVisible(Shell.rootAccess()); menu.findItem(R.id.log).setVisible(Shell.rootAccess());
menu.findItem(R.id.superuser).setVisible( menu.findItem(R.id.superuser).setVisible(

View File

@ -54,7 +54,7 @@ public class ModulesFragment extends Fragment implements Topic.Subscriber {
mSwipeRefreshLayout.setOnRefreshListener(() -> { mSwipeRefreshLayout.setOnRefreshListener(() -> {
recyclerView.setVisibility(View.GONE); recyclerView.setVisibility(View.GONE);
new LoadModules(getActivity()).exec(); new LoadModules().exec();
}); });
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() { recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {

View File

@ -47,7 +47,7 @@ public class ReposFragment extends Fragment implements Topic.Subscriber {
mSwipeRefreshLayout.setOnRefreshListener(() -> { mSwipeRefreshLayout.setOnRefreshListener(() -> {
recyclerView.setVisibility(View.VISIBLE); recyclerView.setVisibility(View.VISIBLE);
emptyRv.setVisibility(View.GONE); emptyRv.setVisibility(View.GONE);
new UpdateRepos(getActivity(), true).exec(); new UpdateRepos(true).exec();
}); });
getActivity().setTitle(R.string.downloads); getActivity().setTitle(R.string.downloads);

View File

@ -121,14 +121,14 @@ public class SettingsActivity extends Activity implements Topic.Subscriber {
findPreference("clear").setOnPreferenceClickListener((pref) -> { findPreference("clear").setOnPreferenceClickListener((pref) -> {
mm.prefs.edit().remove(UpdateRepos.ETAG_KEY).apply(); mm.prefs.edit().remove(UpdateRepos.ETAG_KEY).apply();
mm.repoDB.clearRepo(); mm.repoDB.clearRepo();
mm.toast(R.string.repo_cache_cleared, Toast.LENGTH_SHORT); MagiskManager.toast(R.string.repo_cache_cleared, Toast.LENGTH_SHORT);
return true; return true;
}); });
hideManager.setOnPreferenceClickListener((pref) -> { hideManager.setOnPreferenceClickListener((pref) -> {
Utils.runWithPermission(getActivity(), Utils.runWithPermission(getActivity(),
Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE,
() -> new HideManager(getActivity()).exec()); () -> new HideManager().exec());
return true; return true;
}); });
@ -239,7 +239,7 @@ public class SettingsActivity extends Activity implements Topic.Subscriber {
break; break;
case "update_channel": case "update_channel":
mm.updateChannel = Utils.getPrefsInt(prefs, "update_channel"); mm.updateChannel = Utils.getPrefsInt(prefs, "update_channel");
new CheckUpdates(mm, true).exec(); new CheckUpdates(true).exec();
break; break;
} }
mm.loadConfig(); mm.loadConfig();

View File

@ -33,7 +33,7 @@ public class CheckSafetyNet extends ParallelTask<Void, Void, Exception> {
@Override @Override
protected void onPreExecute() { protected void onPreExecute() {
MagiskManager mm = getMagiskManager(); MagiskManager mm = MagiskManager.get();
if (mm.snet_version != CheckSafetyNet.SNET_VER) { if (mm.snet_version != CheckSafetyNet.SNET_VER) {
Shell.sh("rm -rf " + dexPath.getParent()); Shell.sh("rm -rf " + dexPath.getParent());
} }
@ -72,13 +72,13 @@ public class CheckSafetyNet extends ParallelTask<Void, Void, Exception> {
Object helper = helperClazz.getConstructors()[0].newInstance( Object helper = helperClazz.getConstructors()[0].newInstance(
getActivity(), Proxy.newProxyInstance( getActivity(), Proxy.newProxyInstance(
loader, new Class[] { callbackClazz }, (proxy, method, args) -> { loader, new Class[] { callbackClazz }, (proxy, method, args) -> {
getMagiskManager().safetyNetDone.publish(false, args[0]); MagiskManager.get().safetyNetDone.publish(false, args[0]);
return null; return null;
})); }));
helperClazz.getMethod("attest").invoke(helper); helperClazz.getMethod("attest").invoke(helper);
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
getMagiskManager().safetyNetDone.publish(false, -1); MagiskManager.get().safetyNetDone.publish(false, -1);
} }
super.onPostExecute(err); super.onPostExecute(err);
} }

View File

@ -1,7 +1,5 @@
package com.topjohnwu.magisk.asyncs; package com.topjohnwu.magisk.asyncs;
import android.content.Context;
import com.topjohnwu.magisk.BuildConfig; import com.topjohnwu.magisk.BuildConfig;
import com.topjohnwu.magisk.MagiskManager; import com.topjohnwu.magisk.MagiskManager;
import com.topjohnwu.magisk.utils.ShowUI; import com.topjohnwu.magisk.utils.ShowUI;
@ -18,21 +16,19 @@ public class CheckUpdates extends ParallelTask<Void, Void, Void> {
private static final String STABLE_URL = "https://raw.githubusercontent.com/topjohnwu/MagiskManager/update/stable.json"; private static final String STABLE_URL = "https://raw.githubusercontent.com/topjohnwu/MagiskManager/update/stable.json";
private static final String BETA_URL = "https://raw.githubusercontent.com/topjohnwu/MagiskManager/update/beta.json"; private static final String BETA_URL = "https://raw.githubusercontent.com/topjohnwu/MagiskManager/update/beta.json";
private boolean showNotification = false; private boolean showNotification;
public CheckUpdates(Context context) { public CheckUpdates() {
super(context); this(false);
} }
public CheckUpdates(Context context, boolean b) { public CheckUpdates(boolean b) {
super(context);
showNotification = b; showNotification = b;
} }
@Override @Override
protected Void doInBackground(Void... voids) { protected Void doInBackground(Void... voids) {
MagiskManager mm = getMagiskManager(); MagiskManager mm = MagiskManager.get();
if (mm == null) return null;
String jsonStr; String jsonStr;
switch (mm.updateChannel) { switch (mm.updateChannel) {
case STABLE_CHANNEL: case STABLE_CHANNEL:
@ -61,13 +57,12 @@ public class CheckUpdates extends ParallelTask<Void, Void, Void> {
@Override @Override
protected void onPostExecute(Void v) { protected void onPostExecute(Void v) {
MagiskManager mm = getMagiskManager(); MagiskManager mm = MagiskManager.get();
if (mm == null) return;
if (showNotification && mm.updateNotification) { if (showNotification && mm.updateNotification) {
if (BuildConfig.VERSION_CODE < mm.remoteManagerVersionCode) { if (BuildConfig.VERSION_CODE < mm.remoteManagerVersionCode) {
ShowUI.showManagerUpdateNotification(mm); ShowUI.showManagerUpdateNotification();
} else if (mm.magiskVersionCode < mm.remoteMagiskVersionCode) { } else if (mm.magiskVersionCode < mm.remoteMagiskVersionCode) {
ShowUI.showMagiskUpdateNotification(mm); ShowUI.showMagiskUpdateNotification();
} }
} }
mm.updateCheckDone.publish(); mm.updateCheckDone.publish();

View File

@ -21,14 +21,10 @@ public class DownloadBusybox extends ParallelTask<Void, Void, Void> {
private File busybox; private File busybox;
public DownloadBusybox(Context context) {
super(context);
busybox = new File(context.getCacheDir(), "busybox");
}
@Override @Override
protected Void doInBackground(Void... voids) { protected Void doInBackground(Void... voids) {
Context context = getMagiskManager(); Context context = MagiskManager.get();
busybox = new File(context.getCacheDir(), "busybox");
Utils.removeItem(context.getApplicationInfo().dataDir + "/busybox"); Utils.removeItem(context.getApplicationInfo().dataDir + "/busybox");
try { try {
FileOutputStream out = new FileOutputStream(busybox); FileOutputStream out = new FileOutputStream(busybox);

View File

@ -53,8 +53,7 @@ public class FlashZip extends ParallelTask<Void, Void, Integer> {
@Override @Override
protected Integer doInBackground(Void... voids) { protected Integer doInBackground(Void... voids) {
MagiskManager mm = getMagiskManager(); MagiskManager mm = MagiskManager.get();
if (mm == null) return -1;
try { try {
mList.add("- Copying zip to temp directory"); mList.add("- Copying zip to temp directory");
@ -94,8 +93,7 @@ public class FlashZip extends ParallelTask<Void, Void, Integer> {
// -1 = error, manual install; 0 = invalid zip; 1 = success // -1 = error, manual install; 0 = invalid zip; 1 = success
@Override @Override
protected void onPostExecute(Integer result) { protected void onPostExecute(Integer result) {
MagiskManager mm = getMagiskManager(); MagiskManager mm = MagiskManager.get();
if (mm == null) return;
Shell.su_raw( Shell.su_raw(
"rm -rf " + mCachedFile.getParent(), "rm -rf " + mCachedFile.getParent(),
"rm -rf " + MagiskManager.TMP_FOLDER_PATH "rm -rf " + MagiskManager.TMP_FOLDER_PATH
@ -110,7 +108,7 @@ public class FlashZip extends ParallelTask<Void, Void, Integer> {
break; break;
case 1: case 1:
// Success // Success
new LoadModules(mm).exec(); new LoadModules().exec();
break; break;
} }
super.onPostExecute(result); super.onPostExecute(result);

View File

@ -1,6 +1,5 @@
package com.topjohnwu.magisk.asyncs; package com.topjohnwu.magisk.asyncs;
import android.content.Context;
import android.content.pm.PackageManager; import android.content.pm.PackageManager;
import android.os.Environment; import android.os.Environment;
import android.widget.Toast; import android.widget.Toast;
@ -24,10 +23,6 @@ public class HideManager extends ParallelTask<Void, Void, Boolean> {
private static final String ANDROID_MANIFEST = "AndroidManifest.xml"; private static final String ANDROID_MANIFEST = "AndroidManifest.xml";
private static final byte[] UNHIDE_PKG_NAME = "com.topjohnwu.unhide\0".getBytes(); private static final byte[] UNHIDE_PKG_NAME = "com.topjohnwu.unhide\0".getBytes();
public HideManager(Context context) {
super(context);
}
private String genPackageName(String prefix, int length) { private String genPackageName(String prefix, int length) {
StringBuilder builder = new StringBuilder(length); StringBuilder builder = new StringBuilder(length);
builder.append(prefix); builder.append(prefix);
@ -51,14 +46,12 @@ public class HideManager extends ParallelTask<Void, Void, Boolean> {
@Override @Override
protected void onPreExecute() { protected void onPreExecute() {
getMagiskManager().toast(R.string.hide_manager_toast, Toast.LENGTH_SHORT); MagiskManager.toast(R.string.hide_manager_toast, Toast.LENGTH_SHORT);
} }
@Override @Override
protected Boolean doInBackground(Void... voids) { protected Boolean doInBackground(Void... voids) {
MagiskManager mm = getMagiskManager(); MagiskManager mm = MagiskManager.get();
if (mm == null)
return false;
// Generate a new unhide app with random package name // Generate a new unhide app with random package name
File unhideAPK = new File(Environment.getExternalStorageDirectory() + "/MagiskManager", "unhide.apk"); File unhideAPK = new File(Environment.getExternalStorageDirectory() + "/MagiskManager", "unhide.apk");
@ -127,11 +120,8 @@ public class HideManager extends ParallelTask<Void, Void, Boolean> {
@Override @Override
protected void onPostExecute(Boolean b) { protected void onPostExecute(Boolean b) {
MagiskManager mm = getMagiskManager();
if (mm == null)
return;
if (!b) { if (!b) {
mm.toast(R.string.hide_manager_fail_toast, Toast.LENGTH_LONG); MagiskManager.toast(R.string.hide_manager_fail_toast, Toast.LENGTH_LONG);
} }
super.onPostExecute(b); super.onPostExecute(b);
} }

View File

@ -72,10 +72,9 @@ public class InstallMagisk extends ParallelTask<Void, Void, Boolean> {
@Override @Override
protected Boolean doInBackground(Void... voids) { protected Boolean doInBackground(Void... voids) {
MagiskManager mm = getMagiskManager(); MagiskManager mm = MagiskManager.get();
if (mm == null) return false;
File install = new File(Utils.getEncContext(mm).getFilesDir().getParent(), "install"); File install = new File(Utils.getEncContext().getFilesDir().getParent(), "install");
Shell.sh_raw("rm -rf " + install); Shell.sh_raw("rm -rf " + install);
List<String> abis = Arrays.asList(Build.SUPPORTED_ABIS); List<String> abis = Arrays.asList(Build.SUPPORTED_ABIS);

View File

@ -1,7 +1,5 @@
package com.topjohnwu.magisk.asyncs; package com.topjohnwu.magisk.asyncs;
import android.content.Context;
import com.topjohnwu.magisk.MagiskManager; import com.topjohnwu.magisk.MagiskManager;
import com.topjohnwu.magisk.container.Module; import com.topjohnwu.magisk.container.Module;
import com.topjohnwu.magisk.container.ValueSortedMap; import com.topjohnwu.magisk.container.ValueSortedMap;
@ -11,10 +9,6 @@ import java.util.List;
public class LoadModules extends ParallelTask<Void, Void, Void> { public class LoadModules extends ParallelTask<Void, Void, Void> {
public LoadModules(Context context) {
super(context);
}
private List<String> getModList() { private List<String> getModList() {
String command = "ls -d " + MagiskManager.MAGISK_PATH + "/* | grep -v lost+found"; String command = "ls -d " + MagiskManager.MAGISK_PATH + "/* | grep -v lost+found";
return Shell.su(command); return Shell.su(command);
@ -22,8 +16,7 @@ public class LoadModules extends ParallelTask<Void, Void, Void> {
@Override @Override
protected Void doInBackground(Void... voids) { protected Void doInBackground(Void... voids) {
MagiskManager mm = getMagiskManager(); MagiskManager mm = MagiskManager.get();
if (mm == null) return null;
mm.moduleMap = new ValueSortedMap<>(); mm.moduleMap = new ValueSortedMap<>();
for (String path : getModList()) { for (String path : getModList()) {
@ -36,9 +29,7 @@ public class LoadModules extends ParallelTask<Void, Void, Void> {
@Override @Override
protected void onPostExecute(Void v) { protected void onPostExecute(Void v) {
MagiskManager mm = getMagiskManager(); MagiskManager.get().moduleLoadDone.publish();
if (mm == null) return;
mm.moduleLoadDone.publish();
super.onPostExecute(v); super.onPostExecute(v);
} }
} }

View File

@ -4,6 +4,7 @@ import android.app.Activity;
import android.support.v7.app.AlertDialog; import android.support.v7.app.AlertDialog;
import android.webkit.WebView; import android.webkit.WebView;
import com.topjohnwu.magisk.MagiskManager;
import com.topjohnwu.magisk.R; import com.topjohnwu.magisk.R;
import com.topjohnwu.magisk.utils.WebService; import com.topjohnwu.magisk.utils.WebService;
@ -29,7 +30,7 @@ public class MarkDownWindow extends ParallelTask<Void, Void, String> {
Node doc = parser.parse(md); Node doc = parser.parse(md);
return String.format( return String.format(
"<link rel='stylesheet' type='text/css' href='file:///android_asset/%s.css'/> %s", "<link rel='stylesheet' type='text/css' href='file:///android_asset/%s.css'/> %s",
getMagiskManager().isDarkTheme ? "dark" : "light", renderer.render(doc)); MagiskManager.get().isDarkTheme ? "dark" : "light", renderer.render(doc));
} }
@Override @Override

View File

@ -1,7 +1,6 @@
package com.topjohnwu.magisk.asyncs; package com.topjohnwu.magisk.asyncs;
import android.app.Activity; import android.app.Activity;
import android.content.Context;
import android.os.AsyncTask; import android.os.AsyncTask;
import com.topjohnwu.magisk.MagiskManager; import com.topjohnwu.magisk.MagiskManager;
@ -12,18 +11,12 @@ import java.lang.ref.WeakReference;
public abstract class ParallelTask<Params, Progress, Result> extends AsyncTask<Params, Progress, Result> { public abstract class ParallelTask<Params, Progress, Result> extends AsyncTask<Params, Progress, Result> {
private WeakReference<Activity> weakActivity; private WeakReference<Activity> weakActivity;
private WeakReference<MagiskManager> weakMagiskManager;
private Runnable callback = null; private Runnable callback = null;
public ParallelTask() {} public ParallelTask() {}
public ParallelTask(Context context) {
weakMagiskManager = new WeakReference<>(Utils.getMagiskManager(context));
}
public ParallelTask(Activity context) { public ParallelTask(Activity context) {
this((Context) context);
weakActivity = new WeakReference<>(context); weakActivity = new WeakReference<>(context);
} }
@ -31,10 +24,6 @@ public abstract class ParallelTask<Params, Progress, Result> extends AsyncTask<P
return weakActivity.get(); return weakActivity.get();
} }
protected MagiskManager getMagiskManager() {
return weakMagiskManager.get();
}
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public ParallelTask<Params, Progress, Result> exec(Params... params) { public ParallelTask<Params, Progress, Result> exec(Params... params) {
executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, params); executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, params);

View File

@ -10,6 +10,7 @@ import android.support.annotation.NonNull;
import android.widget.Toast; import android.widget.Toast;
import com.topjohnwu.magisk.FlashActivity; import com.topjohnwu.magisk.FlashActivity;
import com.topjohnwu.magisk.MagiskManager;
import com.topjohnwu.magisk.R; import com.topjohnwu.magisk.R;
import com.topjohnwu.magisk.container.InputStreamWrapper; import com.topjohnwu.magisk.container.InputStreamWrapper;
import com.topjohnwu.magisk.utils.Shell; import com.topjohnwu.magisk.utils.Shell;
@ -175,7 +176,7 @@ public class ProcessRepoZip extends ParallelTask<Void, Object, Boolean> {
Utils.showUriSnack(activity, uri); Utils.showUriSnack(activity, uri);
} }
} else { } else {
Utils.getMagiskManager(activity).toast(R.string.process_error, Toast.LENGTH_LONG); MagiskManager.toast(R.string.process_error, Toast.LENGTH_LONG);
} }
super.onPostExecute(result); super.onPostExecute(result);
} }

View File

@ -1,8 +1,8 @@
package com.topjohnwu.magisk.asyncs; package com.topjohnwu.magisk.asyncs;
import android.content.Context;
import android.widget.Toast; import android.widget.Toast;
import com.topjohnwu.magisk.MagiskManager;
import com.topjohnwu.magisk.R; import com.topjohnwu.magisk.R;
import com.topjohnwu.magisk.utils.Shell; import com.topjohnwu.magisk.utils.Shell;
import com.topjohnwu.magisk.utils.Utils; import com.topjohnwu.magisk.utils.Utils;
@ -13,8 +13,7 @@ public class RestoreStockBoot extends ParallelTask<Void, Void, Boolean> {
private String mBoot; private String mBoot;
public RestoreStockBoot(Context context, String boot) { public RestoreStockBoot(String boot) {
super(context);
mBoot = boot; mBoot = boot;
} }
@ -33,9 +32,9 @@ public class RestoreStockBoot extends ParallelTask<Void, Void, Boolean> {
@Override @Override
protected void onPostExecute(Boolean result) { protected void onPostExecute(Boolean result) {
if (result) { if (result) {
getMagiskManager().toast(R.string.restore_done, Toast.LENGTH_SHORT); MagiskManager.toast(R.string.restore_done, Toast.LENGTH_SHORT);
} else { } else {
getMagiskManager().toast(R.string.restore_fail, Toast.LENGTH_LONG); MagiskManager.toast(R.string.restore_fail, Toast.LENGTH_LONG);
} }
} }
} }

View File

@ -1,6 +1,5 @@
package com.topjohnwu.magisk.asyncs; package com.topjohnwu.magisk.asyncs;
import android.content.Context;
import android.content.SharedPreferences; import android.content.SharedPreferences;
import android.os.AsyncTask; import android.os.AsyncTask;
@ -44,13 +43,13 @@ public class UpdateRepos extends ParallelTask<Void, Void, Void> {
private int tasks = 0; private int tasks = 0;
public UpdateRepos(Context context, boolean force) { public UpdateRepos(boolean force) {
super(context); MagiskManager mm = MagiskManager.get();
prefs = getMagiskManager().prefs; prefs = mm.prefs;
repoDB = getMagiskManager().repoDB; repoDB = mm.repoDB;
getMagiskManager().repoLoadDone.hasPublished = false; mm.repoLoadDone.hasPublished = false;
// Legacy data cleanup // Legacy data cleanup
File old = new File(context.getApplicationInfo().dataDir + "/shared_prefs", "RepoMap.xml"); File old = new File(mm.getApplicationInfo().dataDir + "/shared_prefs", "RepoMap.xml");
if (old.exists() || prefs.getString("repomap", null) != null) { if (old.exists() || prefs.getString("repomap", null) != null) {
old.delete(); old.delete();
prefs.edit().remove("version").remove("repomap").remove(ETAG_KEY).apply(); prefs.edit().remove("version").remove("repomap").remove(ETAG_KEY).apply();
@ -211,9 +210,7 @@ public class UpdateRepos extends ParallelTask<Void, Void, Void> {
@Override @Override
protected void onPostExecute(Void v) { protected void onPostExecute(Void v) {
MagiskManager mm = getMagiskManager(); MagiskManager.get().repoLoadDone.publish();
if (mm == null) return;
mm.repoLoadDone.publish();
super.onPostExecute(v); super.onPostExecute(v);
} }
} }

View File

@ -8,6 +8,7 @@ import android.database.Cursor;
import android.net.Uri; import android.net.Uri;
import android.widget.Toast; import android.widget.Toast;
import com.topjohnwu.magisk.MagiskManager;
import com.topjohnwu.magisk.R; import com.topjohnwu.magisk.R;
import com.topjohnwu.magisk.utils.Utils; import com.topjohnwu.magisk.utils.Utils;
@ -34,7 +35,7 @@ public abstract class DownloadReceiver extends BroadcastReceiver {
onDownloadDone(uri); onDownloadDone(uri);
break; break;
default: default:
Utils.getMagiskManager(context).toast(R.string.download_file_error, Toast.LENGTH_LONG); MagiskManager.toast(R.string.download_file_error, Toast.LENGTH_LONG);
break; break;
} }
context.unregisterReceiver(this); context.unregisterReceiver(this);

View File

@ -11,7 +11,7 @@ public class UpdateCheckService extends JobService {
@Override @Override
public boolean onStartJob(JobParameters params) { public boolean onStartJob(JobParameters params) {
Utils.getMagiskManager(this).getMagiskInfo(); Utils.getMagiskManager(this).getMagiskInfo();
new CheckUpdates(this, true) new CheckUpdates(true)
.setCallBack(() -> jobFinished(params, false)).exec(); .setCallBack(() -> jobFinished(params, false)).exec();
return true; return true;
} }

View File

@ -37,7 +37,7 @@ public class SuReceiver extends BroadcastReceiver {
if (mode < 0) return; if (mode < 0) return;
if (mode == NOTIFY_USER_TO_OWNER) { if (mode == NOTIFY_USER_TO_OWNER) {
magiskManager.toast(R.string.multiuser_hint_owner_request, Toast.LENGTH_LONG); MagiskManager.toast(R.string.multiuser_hint_owner_request, Toast.LENGTH_LONG);
return; return;
} }

View File

@ -1,6 +1,5 @@
package com.topjohnwu.magisk.utils; package com.topjohnwu.magisk.utils;
import android.content.Context;
import android.text.TextUtils; import android.text.TextUtils;
import com.topjohnwu.magisk.MagiskManager; import com.topjohnwu.magisk.MagiskManager;
@ -10,7 +9,6 @@ import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.io.InputStreamReader; import java.io.InputStreamReader;
import java.io.OutputStream; import java.io.OutputStream;
import java.lang.ref.WeakReference;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collection; import java.util.Collection;
import java.util.List; import java.util.List;
@ -21,8 +19,6 @@ import java.util.List;
public class Shell { public class Shell {
private static WeakReference<MagiskManager> weakMm;
// -1 = no shell; 0 = non root shell; 1 = root shell // -1 = no shell; 0 = non root shell; 1 = root shell
public static int status; public static int status;
@ -47,12 +43,8 @@ public class Shell {
STDOUT = process.getInputStream(); STDOUT = process.getInputStream();
} }
public static void registerShell(Context context) {
weakMm = new WeakReference<>(Utils.getMagiskManager(context));
}
public static Shell getShell() { public static Shell getShell() {
MagiskManager mm = weakMm.get(); MagiskManager mm = MagiskManager.get();
boolean needNewShell = mm.shell == null; boolean needNewShell = mm.shell == null;
if (!needNewShell) { if (!needNewShell) {

View File

@ -34,7 +34,8 @@ public class ShowUI {
private static final int MAGISK_UPDATE_NOTIFICATION_ID = 1; private static final int MAGISK_UPDATE_NOTIFICATION_ID = 1;
private static final int APK_UPDATE_NOTIFICATION_ID = 2; private static final int APK_UPDATE_NOTIFICATION_ID = 2;
public static void showMagiskUpdateNotification(MagiskManager mm) { public static void showMagiskUpdateNotification() {
MagiskManager mm = MagiskManager.get();
NotificationCompat.Builder builder = new NotificationCompat.Builder(mm, MagiskManager.NOTIFICATION_CHANNEL); NotificationCompat.Builder builder = new NotificationCompat.Builder(mm, MagiskManager.NOTIFICATION_CHANNEL);
builder.setSmallIcon(R.drawable.ic_magisk) builder.setSmallIcon(R.drawable.ic_magisk)
.setContentTitle(mm.getString(R.string.magisk_update_title)) .setContentTitle(mm.getString(R.string.magisk_update_title))
@ -54,7 +55,8 @@ public class ShowUI {
notificationManager.notify(MAGISK_UPDATE_NOTIFICATION_ID, builder.build()); notificationManager.notify(MAGISK_UPDATE_NOTIFICATION_ID, builder.build());
} }
public static void showManagerUpdateNotification(MagiskManager mm) { public static void showManagerUpdateNotification() {
MagiskManager mm = MagiskManager.get();
NotificationCompat.Builder builder = new NotificationCompat.Builder(mm, MagiskManager.NOTIFICATION_CHANNEL); NotificationCompat.Builder builder = new NotificationCompat.Builder(mm, MagiskManager.NOTIFICATION_CHANNEL);
builder.setSmallIcon(R.drawable.ic_magisk) builder.setSmallIcon(R.drawable.ic_magisk)
.setContentTitle(mm.getString(R.string.manager_update_title)) .setContentTitle(mm.getString(R.string.manager_update_title))
@ -73,7 +75,7 @@ public class ShowUI {
} }
public static void showMagiskInstallDialog(MagiskFragment fragment, boolean enc, boolean verity) { public static void showMagiskInstallDialog(MagiskFragment fragment, boolean enc, boolean verity) {
MagiskManager mm = Utils.getMagiskManager(fragment.getActivity()); MagiskManager mm = Utils.getMagiskManager(fragment.getContext());
String filename = Utils.getLegalFilename("Magisk-v" + mm.remoteMagiskVersionString + ".zip"); String filename = Utils.getLegalFilename("Magisk-v" + mm.remoteMagiskVersionString + ".zip");
new AlertDialogBuilder(fragment.getActivity()) new AlertDialogBuilder(fragment.getActivity())
.setTitle(mm.getString(R.string.repo_install_title, mm.getString(R.string.magisk))) .setTitle(mm.getString(R.string.repo_install_title, mm.getString(R.string.magisk)))
@ -101,10 +103,10 @@ public class ShowUI {
switch (idx) { switch (idx) {
case 1: case 1:
if (mm.remoteMagiskVersionCode < 1400) { if (mm.remoteMagiskVersionCode < 1400) {
mm.toast(R.string.no_boot_file_patch_support, Toast.LENGTH_LONG); MagiskManager.toast(R.string.no_boot_file_patch_support, Toast.LENGTH_LONG);
return; return;
} }
mm.toast(R.string.boot_file_patch_msg, Toast.LENGTH_LONG); MagiskManager.toast(R.string.boot_file_patch_msg, Toast.LENGTH_LONG);
Intent intent = new Intent(Intent.ACTION_GET_CONTENT); Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("*/*"); intent.setType("*/*");
fragment.startActivityForResult(intent, SELECT_BOOT_IMG, fragment.startActivityForResult(intent, SELECT_BOOT_IMG,
@ -256,7 +258,7 @@ public class ShowUI {
"cat " + uninstaller + " > /cache/" + UNINSTALLER, "cat " + uninstaller + " > /cache/" + UNINSTALLER,
"cat " + utils + " > /data/magisk/" + Utils.UTIL_FUNCTIONS "cat " + utils + " > /data/magisk/" + Utils.UTIL_FUNCTIONS
); );
mm.toast(R.string.uninstall_toast, Toast.LENGTH_LONG); MagiskManager.toast(R.string.uninstall_toast, Toast.LENGTH_LONG);
Shell.su_raw( Shell.su_raw(
"sleep 5", "sleep 5",
"pm uninstall " + mm.getApplicationInfo().packageName "pm uninstall " + mm.getApplicationInfo().packageName
@ -268,7 +270,7 @@ public class ShowUI {
.setNeutralButton(R.string.restore_stock_boot, (d, i) -> { .setNeutralButton(R.string.restore_stock_boot, (d, i) -> {
String boot = fragment.getSelectedBootImage(); String boot = fragment.getSelectedBootImage();
if (boot == null) return; if (boot == null) return;
new RestoreStockBoot(mm, boot).exec(); new RestoreStockBoot(boot).exec();
}) })
.setNegativeButton(R.string.no_thanks, null) .setNegativeButton(R.string.no_thanks, null)
.show(); .show();

View File

@ -143,41 +143,43 @@ public class Utils {
.setAction(R.string.ok, (v)->{}).show(); .setAction(R.string.ok, (v)->{}).show();
} }
public static boolean checkNetworkStatus(Context context) { public static boolean checkNetworkStatus() {
ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); ConnectivityManager manager = (ConnectivityManager)
MagiskManager.get().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = manager.getActiveNetworkInfo(); NetworkInfo networkInfo = manager.getActiveNetworkInfo();
return networkInfo != null && networkInfo.isConnected(); return networkInfo != null && networkInfo.isConnected();
} }
public static String getLocaleString(Context context, Locale locale, @StringRes int id) { public static String getLocaleString(Locale locale, @StringRes int id) {
Context context = MagiskManager.get();
Configuration config = context.getResources().getConfiguration(); Configuration config = context.getResources().getConfiguration();
config.setLocale(locale); config.setLocale(locale);
Context localizedContext = context.createConfigurationContext(config); Context localizedContext = context.createConfigurationContext(config);
return localizedContext.getString(id); return localizedContext.getString(id);
} }
public static List<Locale> getAvailableLocale(Context context) { public static List<Locale> getAvailableLocale() {
List<Locale> locales = new ArrayList<>(); List<Locale> locales = new ArrayList<>();
HashSet<String> set = new HashSet<>(); HashSet<String> set = new HashSet<>();
Locale locale; Locale locale;
int compareId = R.string.download_file_error; @StringRes int compareId = R.string.download_file_error;
// Add default locale // Add default locale
locales.add(Locale.ENGLISH); locales.add(Locale.ENGLISH);
set.add(getLocaleString(context, Locale.ENGLISH, compareId)); set.add(getLocaleString(Locale.ENGLISH, compareId));
// Add some special locales // Add some special locales
locales.add(Locale.TAIWAN); locales.add(Locale.TAIWAN);
set.add(getLocaleString(context, Locale.TAIWAN, compareId)); set.add(getLocaleString(Locale.TAIWAN, compareId));
locale = new Locale("pt", "BR"); locale = new Locale("pt", "BR");
locales.add(locale); locales.add(locale);
set.add(getLocaleString(context, locale, compareId)); set.add(getLocaleString(locale, compareId));
// Other locales // Other locales
for (String s : context.getAssets().getLocales()) { for (String s : MagiskManager.get().getAssets().getLocales()) {
locale = Locale.forLanguageTag(s); locale = Locale.forLanguageTag(s);
if (set.add(getLocaleString(context, locale, compareId))) { if (set.add(getLocaleString(locale, compareId))) {
locales.add(locale); locales.add(locale);
} }
} }
@ -206,7 +208,8 @@ public class Utils {
== DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_PER_USER; == DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_PER_USER;
} }
public static Context getEncContext(Context context) { public static Context getEncContext() {
Context context = MagiskManager.get();
if (useFDE(context)) if (useFDE(context))
return context.createDeviceProtectedStorageContext(); return context.createDeviceProtectedStorageContext();
else else