From 69b8836b50e46b4e2095ee1067c2d2706424d8fb Mon Sep 17 00:00:00 2001 From: AbdurazaaqMohammed Date: Thu, 29 Aug 2024 22:27:52 -0400 Subject: [PATCH] 1.6.6.2 Add option to install APK after successfully merging and signing Sort installed app list alphabetically Show icon of apps in the app list --- app/build.gradle.kts | 2 +- app/src/main/AndroidManifest.xml | 10 + .../support/v4/content/FileProvider.java | 773 ++++++++++++++++++ .../AntiSplit/main/AppInfo.java | 15 + .../AntiSplit/main/AppListArrayAdapter.java | 104 +++ .../AntiSplit/main/CustomArrayAdapter.java | 64 +- .../AntiSplit/main/DeviceSpecsUtil.java | 8 +- .../AntiSplit/main/IconsHelper.java | 34 + .../AntiSplit/main/MainActivity.java | 79 +- .../AntiSplit/main/SignUtil.java | 15 +- .../com/aefyr/pseudoapksigner/IOUtils.java | 4 +- .../java/com/j256/simplezip/ZipFileInput.java | 25 +- .../java/com/reandroid/apk/ApkBundle.java | 2 +- .../com/reandroid/apkeditor/merge/Merger.java | 16 +- .../java/com/reandroid/archive/Archive.java | 5 +- .../com/reandroid/archive/InputSource.java | 6 +- .../archive/block/ApkSignatureBlock.java | 9 +- .../com/reandroid/arsc/chunk/TableBlock.java | 7 +- .../reandroid/arsc/chunk/UnknownChunk.java | 7 +- .../arsc/chunk/xml/ResXmlDocument.java | 7 +- .../java/com/reandroid/json/JSONItem.java | 6 +- app/src/main/res/layout/activity_main.xml | 29 +- app/src/main/res/layout/list_item.xml | 22 + app/src/main/res/values/strings.xml | 2 + app/src/main/res/xml/paths.xml | 9 + 25 files changed, 1109 insertions(+), 151 deletions(-) create mode 100644 app/src/main/java/android/support/v4/content/FileProvider.java create mode 100644 app/src/main/java/com/abdurazaaqmohammed/AntiSplit/main/AppInfo.java create mode 100644 app/src/main/java/com/abdurazaaqmohammed/AntiSplit/main/AppListArrayAdapter.java create mode 100644 app/src/main/java/com/abdurazaaqmohammed/AntiSplit/main/IconsHelper.java create mode 100644 app/src/main/res/layout/list_item.xml create mode 100644 app/src/main/res/xml/paths.xml diff --git a/app/build.gradle.kts b/app/build.gradle.kts index 67ba15f0..e064ca5a 100644 --- a/app/build.gradle.kts +++ b/app/build.gradle.kts @@ -11,7 +11,7 @@ android { minSdk = 4 targetSdk = 35 versionCode = 30 - versionName = "1.6.6.1" + versionName = "1.6.6.2" multiDexEnabled = true } diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index 930b0437..19c424f2 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -5,6 +5,7 @@ + @@ -40,5 +41,14 @@ + + + \ No newline at end of file diff --git a/app/src/main/java/android/support/v4/content/FileProvider.java b/app/src/main/java/android/support/v4/content/FileProvider.java new file mode 100644 index 00000000..2e95ab8f --- /dev/null +++ b/app/src/main/java/android/support/v4/content/FileProvider.java @@ -0,0 +1,773 @@ +/* + * Copyright (C) 2013 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package android.support.v4.content; + +import static org.xmlpull.v1.XmlPullParser.END_DOCUMENT; +import static org.xmlpull.v1.XmlPullParser.START_TAG; + +import android.content.ContentProvider; +import android.content.ContentValues; +import android.content.Context; +import android.content.Intent; +import android.content.pm.PackageManager; +import android.content.pm.ProviderInfo; +import android.content.res.XmlResourceParser; +import android.database.Cursor; +import android.database.MatrixCursor; +import android.net.Uri; +import android.os.Environment; +import android.os.ParcelFileDescriptor; +import android.provider.OpenableColumns; +import android.text.TextUtils; +import android.webkit.MimeTypeMap; + +import org.xmlpull.v1.XmlPullParserException; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + +/** + * FileProvider is a special subclass of {@link ContentProvider} that facilitates secure sharing + * of files associated with an app by creating a content:// {@link Uri} for a file + * instead of a file:/// {@link Uri}. + *

+ * A content URI allows you to grant read and write access using + * temporary access permissions. When you create an {@link Intent} containing + * a content URI, in order to send the content URI + * to a client app, you can also call {@link Intent#setFlags(int) Intent.setFlags()} to add + * permissions. These permissions are available to the client app for as long as the stack for + * a receiving {@link android.app.Activity} is active. For an {@link Intent} going to a + * {@link android.app.Service}, the permissions are available as long as the + * {@link android.app.Service} is running. + *

+ * In comparison, to control access to a file:/// {@link Uri} you have to modify the + * file system permissions of the underlying file. The permissions you provide become available to + * any app, and remain in effect until you change them. This level of access is + * fundamentally insecure. + *

+ * The increased level of file access security offered by a content URI + * makes FileProvider a key part of Android's security infrastructure. + *

+ * This overview of FileProvider includes the following topics: + *

+ *
    + *
  1. Defining a FileProvider
  2. + *
  3. Specifying Available Files
  4. + *
  5. Retrieving the Content URI for a File
  6. + *
  7. Granting Temporary Permissions to a URI
  8. + *
  9. Serving a Content URI to Another App
  10. + *
+ *

Defining a FileProvider

+ *

+ * Since the default functionality of FileProvider includes content URI generation for files, you + * don't need to define a subclass in code. Instead, you can include a FileProvider in your app + * by specifying it entirely in XML. To specify the FileProvider component itself, add a + * <provider> + * element to your app manifest. Set the android:name attribute to + * android.support.v4.content.FileProvider. Set the android:authorities + * attribute to a URI authority based on a domain you control; for example, if you control the + * domain mydomain.com you should use the authority + * com.mydomain.fileprovider. Set the android:exported attribute to + * false; the FileProvider does not need to be public. Set the + * android:grantUriPermissions attribute to true, to allow you + * to grant temporary access to files. For example: + *

+ *<manifest>
+ *    ...
+ *    <application>
+ *        ...
+ *        <provider
+ *            android:name="android.support.v4.content.FileProvider"
+ *            android:authorities="com.mydomain.fileprovider"
+ *            android:exported="false"
+ *            android:grantUriPermissions="true">
+ *            ...
+ *        </provider>
+ *        ...
+ *    </application>
+ *</manifest>
+ *

+ * If you want to override any of the default behavior of FileProvider methods, extend + * the FileProvider class and use the fully-qualified class name in the android:name + * attribute of the <provider> element. + *

Specifying Available Files

+ * A FileProvider can only generate a content URI for files in directories that you specify + * beforehand. To specify a directory, specify the its storage area and path in XML, using child + * elements of the <paths> element. + * For example, the following paths element tells FileProvider that you intend to + * request content URIs for the images/ subdirectory of your private file area. + *
+ *<paths xmlns:android="http://schemas.android.com/apk/res/android">
+ *    <files-path name="my_images" path="images/"/>
+ *    ...
+ *</paths>
+ *
+ *

+ * The <paths> element must contain one or more of the following child elements: + *

+ *
+ *
+ *
+ *<files-path name="name" path="path" />
+ *
+ *
+ *
+ * Represents files in the files/ subdirectory of your app's internal storage + * area. This subdirectory is the same as the value returned by {@link Context#getFilesDir() + * Context.getFilesDir()}. + *
+ *
+ *<external-path name="name" path="path" />
+ *
+ *
+ *
+ * Represents files in the root of your app's external storage area. The path + * {@link Context#getExternalFilesDir(String) Context.getExternalFilesDir()} returns the + * files/ subdirectory of this this root. + *
+ *
+ *
+ *<cache-path name="name" path="path" />
+ *
+ *
+ *
+ * Represents files in the cache subdirectory of your app's internal storage area. The root path + * of this subdirectory is the same as the value returned by {@link Context#getCacheDir() + * getCacheDir()}. + *
+ *
+ *

+ * These child elements all use the same attributes: + *

+ *
+ *
+ * name="name" + *
+ *
+ * A URI path segment. To enforce security, this value hides the name of the subdirectory + * you're sharing. The subdirectory name for this value is contained in the + * path attribute. + *
+ *
+ * path="path" + *
+ *
+ * The subdirectory you're sharing. While the name attribute is a URI path + * segment, the path value is an actual subdirectory name. Notice that the + * value refers to a subdirectory, not an individual file or files. You can't + * share a single file by its file name, nor can you specify a subset of files using + * wildcards. + *
+ *
+ *

+ * You must specify a child element of <paths> for each directory that contains + * files for which you want content URIs. For example, these XML elements specify two directories: + *

+ *<paths xmlns:android="http://schemas.android.com/apk/res/android">
+ *    <files-path name="my_images" path="images/"/>
+ *    <files-path name="my_docs" path="docs/"/>
+ *</paths>
+ *
+ *

+ * Put the <paths> element and its children in an XML file in your project. + * For example, you can add them to a new file called res/xml/file_paths.xml. + * To link this file to the FileProvider, add a + * <meta-data> element + * as a child of the <provider> element that defines the FileProvider. Set the + * <meta-data> element's "android:name" attribute to + * android.support.FILE_PROVIDER_PATHS. Set the element's "android:resource" attribute + * to @xml/file_paths (notice that you don't specify the .xml + * extension). For example: + *

+ *<provider
+ *    android:name="android.support.v4.content.FileProvider"
+ *    android:authorities="com.mydomain.fileprovider"
+ *    android:exported="false"
+ *    android:grantUriPermissions="true">
+ *    <meta-data
+ *        android:name="android.support.FILE_PROVIDER_PATHS"
+ *        android:resource="@xml/file_paths" />
+ *</provider>
+ *
+ *

Generating the Content URI for a File

+ *

+ * To share a file with another app using a content URI, your app has to generate the content URI. + * To generate the content URI, create a new {@link File} for the file, then pass the {@link File} + * to {@link #getUriForFile(Context, String, File) getUriForFile()}. You can send the content URI + * returned by {@link #getUriForFile(Context, String, File) getUriForFile()} to another app in an + * {@link android.content.Intent}. The client app that receives the content URI can open the file + * and access its contents by calling + * {@link android.content.ContentResolver#openFileDescriptor(Uri, String) + * ContentResolver.openFileDescriptor} to get a {@link ParcelFileDescriptor}. + *

+ * For example, suppose your app is offering files to other apps with a FileProvider that has the + * authority com.mydomain.fileprovider. To get a content URI for the file + * default_image.jpg in the images/ subdirectory of your internal storage + * add the following code: + *

+ *File imagePath = new File(Context.getFilesDir(), "images");
+ *File newFile = new File(imagePath, "default_image.jpg");
+ *Uri contentUri = getUriForFile(getContext(), "com.mydomain.fileprovider", newFile);
+ *
+ * As a result of the previous snippet, + * {@link #getUriForFile(Context, String, File) getUriForFile()} returns the content URI + * content://com.mydomain.fileprovider/my_images/default_image.jpg. + *

Granting Temporary Permissions to a URI

+ * To grant an access permission to a content URI returned from + * {@link #getUriForFile(Context, String, File) getUriForFile()}, do one of the following: + *
    + *
  • + * Call the method + * {@link Context#grantUriPermission(String, Uri, int) + * Context.grantUriPermission(package, Uri, mode_flags)} for the content:// + * {@link Uri}, using the desired mode flags. This grants temporary access permission for the + * content URI to the specified package, according to the value of the + * the mode_flags parameter, which you can set to + * {@link Intent#FLAG_GRANT_READ_URI_PERMISSION}, {@link Intent#FLAG_GRANT_WRITE_URI_PERMISSION} + * or both. The permission remains in effect until you revoke it by calling + * {@link Context#revokeUriPermission(Uri, int) revokeUriPermission()} or until the device + * reboots. + *
  • + *
  • + * Put the content URI in an {@link Intent} by calling {@link Intent#setData(Uri) setData()}. + *
  • + *
  • + * Next, call the method {@link Intent#setFlags(int) Intent.setFlags()} with either + * {@link Intent#FLAG_GRANT_READ_URI_PERMISSION} or + * {@link Intent#FLAG_GRANT_WRITE_URI_PERMISSION} or both. + *
  • + *
  • + * Finally, send the {@link Intent} to + * another app. Most often, you do this by calling + * {@link android.app.Activity#setResult(int, android.content.Intent) setResult()}. + *

    + * Permissions granted in an {@link Intent} remain in effect while the stack of the receiving + * {@link android.app.Activity} is active. When the stack finishes, the permissions are + * automatically removed. Permissions granted to one {@link android.app.Activity} in a client + * app are automatically extended to other components of that app. + *

    + *
  • + *
+ *

Serving a Content URI to Another App

+ *

+ * There are a variety of ways to serve the content URI for a file to a client app. One common way + * is for the client app to start your app by calling + * {@link android.app.Activity#startActivityForResult(Intent, int, Bundle) startActivityResult()}, + * which sends an {@link Intent} to your app to start an {@link android.app.Activity} in your app. + * In response, your app can immediately return a content URI to the client app or present a user + * interface that allows the user to pick a file. In the latter case, once the user picks the file + * your app can return its content URI. In both cases, your app returns the content URI in an + * {@link Intent} sent via {@link android.app.Activity#setResult(int, Intent) setResult()}. + *

+ *

+ * You can also put the content URI in a {@link android.content.ClipData} object and then add the + * object to an {@link Intent} you send to a client app. To do this, call + * {@link Intent#setClipData(ClipData) Intent.setClipData()}. When you use this approach, you can + * add multiple {@link android.content.ClipData} objects to the {@link Intent}, each with its own + * content URI. When you call {@link Intent#setFlags(int) Intent.setFlags()} on the {@link Intent} + * to set temporary access permissions, the same permissions are applied to all of the content + * URIs. + *

+ *

+ * Note: The {@link Intent#setClipData(ClipData) Intent.setClipData()} method is + * only available in platform version 16 (Android 4.1) and later. If you want to maintain + * compatibility with previous versions, you should send one content URI at a time in the + * {@link Intent}. Set the action to {@link Intent#ACTION_SEND} and put the URI in data by calling + * {@link Intent#setData setData()}. + *

+ *

More Information

+ *

+ * To learn more about FileProvider, see the Android training class + * Sharing Files Securely with URIs. + *

+ */ +public class FileProvider extends ContentProvider { + private static final String[] COLUMNS = { + OpenableColumns.DISPLAY_NAME, OpenableColumns.SIZE }; + + private static final String + META_DATA_FILE_PROVIDER_PATHS = "android.support.FILE_PROVIDER_PATHS"; + + private static final String TAG_ROOT_PATH = "root-path"; + private static final String TAG_FILES_PATH = "files-path"; + private static final String TAG_CACHE_PATH = "cache-path"; + private static final String TAG_EXTERNAL = "external-path"; + + private static final String ATTR_NAME = "name"; + private static final String ATTR_PATH = "path"; + + private static final File DEVICE_ROOT = new File("/"); + + // @GuardedBy("sCache") + private static HashMap sCache = new HashMap(); + + private PathStrategy mStrategy; + + /** + * The default FileProvider implementation does not need to be initialized. If you want to + * override this method, you must provide your own subclass of FileProvider. + */ + @Override + public boolean onCreate() { + return true; + } + + /** + * After the FileProvider is instantiated, this method is called to provide the system with + * information about the provider. + * + * @param context A {@link Context} for the current component. + * @param info A {@link ProviderInfo} for the new provider. + */ + @Override + public void attachInfo(Context context, ProviderInfo info) { + super.attachInfo(context, info); + + // Sanity check our security + if (info.exported) { + throw new SecurityException("Provider must not be exported"); + } + if (!info.grantUriPermissions) { + throw new SecurityException("Provider must grant uri permissions"); + } + + mStrategy = getPathStrategy(context, info.authority); + } + + /** + * Return a content URI for a given {@link File}. Specific temporary + * permissions for the content URI can be set with + * {@link Context#grantUriPermission(String, Uri, int)}, or added + * to an {@link Intent} by calling {@link Intent#setData(Uri) setData()} and then + * {@link Intent#setFlags(int) setFlags()}; in both cases, the applicable flags are + * {@link Intent#FLAG_GRANT_READ_URI_PERMISSION} and + * {@link Intent#FLAG_GRANT_WRITE_URI_PERMISSION}. A FileProvider can only return a + * content {@link Uri} for file paths defined in their <paths> + * meta-data element. See the Class Overview for more information. + * + * @param context A {@link Context} for the current component. + * @param authority The authority of a {@link FileProvider} defined in a + * {@code <provider>} element in your app's manifest. + * @param file A {@link File} pointing to the filename for which you want a + * content {@link Uri}. + * @return A content URI for the file. + * @throws IllegalArgumentException When the given {@link File} is outside + * the paths supported by the provider. + */ + public static Uri getUriForFile(Context context, String authority, File file) { + final PathStrategy strategy = getPathStrategy(context, authority); + return strategy.getUriForFile(file); + } + + /** + * Use a content URI returned by + * {@link #getUriForFile(Context, String, File) getUriForFile()} to get information about a file + * managed by the FileProvider. + * FileProvider reports the column names defined in {@link android.provider.OpenableColumns}: + *
    + *
  • {@link android.provider.OpenableColumns#DISPLAY_NAME}
  • + *
  • {@link android.provider.OpenableColumns#SIZE}
  • + *
+ * For more information, see + * {@link ContentProvider#query(Uri, String[], String, String[], String) + * ContentProvider.query()}. + * + * @param uri A content URI returned by {@link #getUriForFile}. + * @param projection The list of columns to put into the {@link Cursor}. If null all columns are + * included. + * @param selection Selection criteria to apply. If null then all data that matches the content + * URI is returned. + * @param selectionArgs An array of {@link java.lang.String}, containing arguments to bind to + * the selection parameter. The query method scans selection from left to + * right and iterates through selectionArgs, replacing the current "?" character in + * selection with the value at the current position in selectionArgs. The + * values are bound to selection as {@link java.lang.String} values. + * @param sortOrder A {@link java.lang.String} containing the column name(s) on which to sort + * the resulting {@link Cursor}. + * @return A {@link Cursor} containing the results of the query. + * + */ + @Override + public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, + String sortOrder) { + // ContentProvider has already checked granted permissions + final File file = mStrategy.getFileForUri(uri); + + if (projection == null) { + projection = COLUMNS; + } + + String[] cols = new String[projection.length]; + Object[] values = new Object[projection.length]; + int i = 0; + for (String col : projection) { + if (OpenableColumns.DISPLAY_NAME.equals(col)) { + cols[i] = OpenableColumns.DISPLAY_NAME; + values[i++] = file.getName(); + } else if (OpenableColumns.SIZE.equals(col)) { + cols[i] = OpenableColumns.SIZE; + values[i++] = file.length(); + } + } + + cols = copyOf(cols, i); + values = copyOf(values, i); + + final MatrixCursor cursor = new MatrixCursor(cols, 1); + cursor.addRow(values); + return cursor; + } + + /** + * Returns the MIME type of a content URI returned by + * {@link #getUriForFile(Context, String, File) getUriForFile()}. + * + * @param uri A content URI returned by + * {@link #getUriForFile(Context, String, File) getUriForFile()}. + * @return If the associated file has an extension, the MIME type associated with that + * extension; otherwise application/octet-stream. + */ + @Override + public String getType(Uri uri) { + // ContentProvider has already checked granted permissions + final File file = mStrategy.getFileForUri(uri); + + final int lastDot = file.getName().lastIndexOf('.'); + if (lastDot >= 0) { + final String extension = file.getName().substring(lastDot + 1); + final String mime = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension); + if (mime != null) { + return mime; + } + } + + return "application/octet-stream"; + } + + /** + * By default, this method throws an {@link java.lang.UnsupportedOperationException}. You must + * subclass FileProvider if you want to provide different functionality. + */ + @Override + public Uri insert(Uri uri, ContentValues values) { + throw new UnsupportedOperationException("No external inserts"); + } + + /** + * By default, this method throws an {@link java.lang.UnsupportedOperationException}. You must + * subclass FileProvider if you want to provide different functionality. + */ + @Override + public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) { + throw new UnsupportedOperationException("No external updates"); + } + + /** + * Deletes the file associated with the specified content URI, as + * returned by {@link #getUriForFile(Context, String, File) getUriForFile()}. Notice that this + * method does not throw an {@link java.io.IOException}; you must check its return value. + * + * @param uri A content URI for a file, as returned by + * {@link #getUriForFile(Context, String, File) getUriForFile()}. + * @param selection Ignored. Set to {@code null}. + * @param selectionArgs Ignored. Set to {@code null}. + * @return 1 if the delete succeeds; otherwise, 0. + */ + @Override + public int delete(Uri uri, String selection, String[] selectionArgs) { + // ContentProvider has already checked granted permissions + final File file = mStrategy.getFileForUri(uri); + return file.delete() ? 1 : 0; + } + + /** + * By default, FileProvider automatically returns the + * {@link ParcelFileDescriptor} for a file associated with a content:// + * {@link Uri}. To get the {@link ParcelFileDescriptor}, call + * {@link android.content.ContentResolver#openFileDescriptor(Uri, String) + * ContentResolver.openFileDescriptor}. + * + * To override this method, you must provide your own subclass of FileProvider. + * + * @param uri A content URI associated with a file, as returned by + * {@link #getUriForFile(Context, String, File) getUriForFile()}. + * @param mode Access mode for the file. May be "r" for read-only access, "rw" for read and + * write access, or "rwt" for read and write access that truncates any existing file. + * @return A new {@link ParcelFileDescriptor} with which you can access the file. + */ + @Override + public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException { + // ContentProvider has already checked granted permissions + final File file = mStrategy.getFileForUri(uri); + final int fileMode = modeToMode(mode); + return ParcelFileDescriptor.open(file, fileMode); + } + + /** + * Return {@link PathStrategy} for given authority, either by parsing or + * returning from cache. + */ + private static PathStrategy getPathStrategy(Context context, String authority) { + PathStrategy strat; + synchronized (sCache) { + strat = sCache.get(authority); + if (strat == null) { + try { + strat = parsePathStrategy(context, authority); + } catch (IOException e) { + throw new IllegalArgumentException( + "Failed to parse " + META_DATA_FILE_PROVIDER_PATHS + " meta-data", e); + } catch (XmlPullParserException e) { + throw new IllegalArgumentException( + "Failed to parse " + META_DATA_FILE_PROVIDER_PATHS + " meta-data", e); + } + sCache.put(authority, strat); + } + } + return strat; + } + + /** + * Parse and return {@link PathStrategy} for given authority as defined in + * {@link #META_DATA_FILE_PROVIDER_PATHS} {@code <meta-data>}. + * + * @see #getPathStrategy(Context, String) + */ + private static PathStrategy parsePathStrategy(Context context, String authority) + throws IOException, XmlPullParserException { + final SimplePathStrategy strat = new SimplePathStrategy(authority); + + final ProviderInfo info = context.getPackageManager() + .resolveContentProvider(authority, PackageManager.GET_META_DATA); + final XmlResourceParser in = info.loadXmlMetaData( + context.getPackageManager(), META_DATA_FILE_PROVIDER_PATHS); + if (in == null) { + throw new IllegalArgumentException( + "Missing " + META_DATA_FILE_PROVIDER_PATHS + " meta-data"); + } + + int type; + while ((type = in.next()) != END_DOCUMENT) { + if (type == START_TAG) { + final String tag = in.getName(); + + final String name = in.getAttributeValue(null, ATTR_NAME); + String path = in.getAttributeValue(null, ATTR_PATH); + + File target = null; + if (TAG_ROOT_PATH.equals(tag)) { + target = buildPath(DEVICE_ROOT, path); + } else if (TAG_FILES_PATH.equals(tag)) { + target = buildPath(context.getFilesDir(), path); + } else if (TAG_CACHE_PATH.equals(tag)) { + target = buildPath(context.getCacheDir(), path); + } else if (TAG_EXTERNAL.equals(tag)) { + target = buildPath(Environment.getExternalStorageDirectory(), path); + } + + if (target != null) { + strat.addRoot(name, target); + } + } + } + + return strat; + } + + /** + * Strategy for mapping between {@link File} and {@link Uri}. + *

+ * Strategies must be symmetric so that mapping a {@link File} to a + * {@link Uri} and then back to a {@link File} points at the original + * target. + *

+ * Strategies must remain consistent across app launches, and not rely on + * dynamic state. This ensures that any generated {@link Uri} can still be + * resolved if your process is killed and later restarted. + * + * @see SimplePathStrategy + */ + interface PathStrategy { + /** + * Return a {@link Uri} that represents the given {@link File}. + */ + public Uri getUriForFile(File file); + + /** + * Return a {@link File} that represents the given {@link Uri}. + */ + public File getFileForUri(Uri uri); + } + + /** + * Strategy that provides access to files living under a narrow whitelist of + * filesystem roots. It will throw {@link SecurityException} if callers try + * accessing files outside the configured roots. + *

+ * For example, if configured with + * {@code addRoot("myfiles", context.getFilesDir())}, then + * {@code context.getFileStreamPath("foo.txt")} would map to + * {@code content://myauthority/myfiles/foo.txt}. + */ + static class SimplePathStrategy implements PathStrategy { + private final String mAuthority; + private final HashMap mRoots = new HashMap(); + + public SimplePathStrategy(String authority) { + mAuthority = authority; + } + + /** + * Add a mapping from a name to a filesystem root. The provider only offers + * access to files that live under configured roots. + */ + public void addRoot(String name, File root) { + if (TextUtils.isEmpty(name)) { + throw new IllegalArgumentException("Name must not be empty"); + } + + try { + // Resolve to canonical path to keep path checking fast + root = root.getCanonicalFile(); + } catch (IOException e) { + throw new IllegalArgumentException( + "Failed to resolve canonical path for " + root, e); + } + + mRoots.put(name, root); + } + + @Override + public Uri getUriForFile(File file) { + String path; + try { + path = file.getCanonicalPath(); + } catch (IOException e) { + throw new IllegalArgumentException("Failed to resolve canonical path for " + file); + } + + // Find the most-specific root path + Map.Entry mostSpecific = null; + for (Map.Entry root : mRoots.entrySet()) { + final String rootPath = root.getValue().getPath(); + if (path.startsWith(rootPath) && (mostSpecific == null + || rootPath.length() > mostSpecific.getValue().getPath().length())) { + mostSpecific = root; + } + } + + if (mostSpecific == null) { + throw new IllegalArgumentException( + "Failed to find configured root that contains " + path); + } + + // Start at first char of path under root + final String rootPath = mostSpecific.getValue().getPath(); + if (rootPath.endsWith("/")) { + path = path.substring(rootPath.length()); + } else { + path = path.substring(rootPath.length() + 1); + } + + // Encode the tag and path separately + path = Uri.encode(mostSpecific.getKey()) + '/' + Uri.encode(path, "/"); + return new Uri.Builder().scheme("content") + .authority(mAuthority).encodedPath(path).build(); + } + + @Override + public File getFileForUri(Uri uri) { + String path = uri.getEncodedPath(); + + final int splitIndex = path.indexOf('/', 1); + final String tag = Uri.decode(path.substring(1, splitIndex)); + path = Uri.decode(path.substring(splitIndex + 1)); + + final File root = mRoots.get(tag); + if (root == null) { + throw new IllegalArgumentException("Unable to find configured root for " + uri); + } + + File file = new File(root, path); + try { + file = file.getCanonicalFile(); + } catch (IOException e) { + throw new IllegalArgumentException("Failed to resolve canonical path for " + file); + } + + if (!file.getPath().startsWith(root.getPath())) { + throw new SecurityException("Resolved path jumped beyond configured root"); + } + + return file; + } + } + + /** + * Copied from ContentResolver.java + */ + private static int modeToMode(String mode) { + int modeBits; + if ("r".equals(mode)) { + modeBits = ParcelFileDescriptor.MODE_READ_ONLY; + } else if ("w".equals(mode) || "wt".equals(mode)) { + modeBits = ParcelFileDescriptor.MODE_WRITE_ONLY + | ParcelFileDescriptor.MODE_CREATE + | ParcelFileDescriptor.MODE_TRUNCATE; + } else if ("wa".equals(mode)) { + modeBits = ParcelFileDescriptor.MODE_WRITE_ONLY + | ParcelFileDescriptor.MODE_CREATE + | ParcelFileDescriptor.MODE_APPEND; + } else if ("rw".equals(mode)) { + modeBits = ParcelFileDescriptor.MODE_READ_WRITE + | ParcelFileDescriptor.MODE_CREATE; + } else if ("rwt".equals(mode)) { + modeBits = ParcelFileDescriptor.MODE_READ_WRITE + | ParcelFileDescriptor.MODE_CREATE + | ParcelFileDescriptor.MODE_TRUNCATE; + } else { + throw new IllegalArgumentException("Invalid mode: " + mode); + } + return modeBits; + } + + private static File buildPath(File base, String... segments) { + File cur = base; + for (String segment : segments) { + if (segment != null) { + cur = new File(cur, segment); + } + } + return cur; + } + + private static String[] copyOf(String[] original, int newLength) { + final String[] result = new String[newLength]; + System.arraycopy(original, 0, result, 0, newLength); + return result; + } + + private static Object[] copyOf(Object[] original, int newLength) { + final Object[] result = new Object[newLength]; + System.arraycopy(original, 0, result, 0, newLength); + return result; + } +} \ No newline at end of file diff --git a/app/src/main/java/com/abdurazaaqmohammed/AntiSplit/main/AppInfo.java b/app/src/main/java/com/abdurazaaqmohammed/AntiSplit/main/AppInfo.java new file mode 100644 index 00000000..35da9552 --- /dev/null +++ b/app/src/main/java/com/abdurazaaqmohammed/AntiSplit/main/AppInfo.java @@ -0,0 +1,15 @@ +package com.abdurazaaqmohammed.AntiSplit.main; + +import android.graphics.drawable.Drawable; + +public class AppInfo { + String name; + String packageName; + Drawable icon; + + public AppInfo(String name, Drawable icon, String packageName) { + this.name = name; + this.icon = icon; + this.packageName = packageName; + } +} diff --git a/app/src/main/java/com/abdurazaaqmohammed/AntiSplit/main/AppListArrayAdapter.java b/app/src/main/java/com/abdurazaaqmohammed/AntiSplit/main/AppListArrayAdapter.java new file mode 100644 index 00000000..3a216f53 --- /dev/null +++ b/app/src/main/java/com/abdurazaaqmohammed/AntiSplit/main/AppListArrayAdapter.java @@ -0,0 +1,104 @@ +package com.abdurazaaqmohammed.AntiSplit.main; + +import android.content.Context; +import android.view.LayoutInflater; +import android.view.View; +import android.view.ViewGroup; +import android.widget.ArrayAdapter; +import android.widget.Filter; +import android.widget.Filterable; +import android.widget.ImageView; +import android.widget.TextView; + +import com.abdurazaaqmohammed.AntiSplit.R; + +import java.util.ArrayList; +import java.util.List; + +public class AppListArrayAdapter extends ArrayAdapter implements Filterable { + private final Context context; + private final List originalAppInfoList; + public List filteredAppInfoList; + private final int textColor; + private final boolean showIcon; + private AppInfoFilter filter; + + public AppListArrayAdapter(Context context, List appInfoList, int textColor, boolean showIcon) { + super(context, R.layout.list_item, appInfoList); + this.context = context; + this.originalAppInfoList = new ArrayList<>(appInfoList); + this.filteredAppInfoList = new ArrayList<>(appInfoList); + this.textColor = textColor; + this.showIcon = showIcon; + } + + @Override + public int getCount() { + return filteredAppInfoList.size(); + } + + @Override + public AppInfo getItem(int position) { + return filteredAppInfoList.get(position); + } + + @Override + public View getView(int position, View convertView, ViewGroup parent) { + if (convertView == null) { + convertView = LayoutInflater.from(context).inflate(R.layout.list_item, parent, false); + } + + TextView textView = convertView.findViewById(R.id.text_view); + ImageView iconView = convertView.findViewById(R.id.icon_view); + + AppInfo appInfo = getItem(position); + textView.setText(appInfo.name); + textView.setTextColor(textColor); + + if (showIcon) { + iconView.setImageDrawable(appInfo.icon); + iconView.setVisibility(View.VISIBLE); + } else { + iconView.setVisibility(View.GONE); + } + + return convertView; + } + + @Override + public Filter getFilter() { + if (filter == null) { + filter = new AppInfoFilter(); + } + return filter; + } + + private class AppInfoFilter extends Filter { + @Override + protected FilterResults performFiltering(CharSequence constraint) { + FilterResults results = new FilterResults(); + if (constraint == null || constraint.length() == 0) { + results.values = new ArrayList<>(originalAppInfoList); + results.count = originalAppInfoList.size(); + } else { + List filteredItems = new ArrayList<>(); + String filterPattern = constraint.toString().toLowerCase().trim(); + for (AppInfo appInfo : originalAppInfoList) { + if (appInfo.name.toLowerCase().contains(filterPattern)) { + filteredItems.add(appInfo); + } + } + results.values = filteredItems; + results.count = filteredItems.size(); + } + return results; + } + + @Override + protected void publishResults(CharSequence constraint, FilterResults results) { + filteredAppInfoList.clear(); + filteredAppInfoList.addAll((List) results.values); + notifyDataSetChanged(); + } + } +} \ No newline at end of file diff --git a/app/src/main/java/com/abdurazaaqmohammed/AntiSplit/main/CustomArrayAdapter.java b/app/src/main/java/com/abdurazaaqmohammed/AntiSplit/main/CustomArrayAdapter.java index 7641f9c9..5ff8de1f 100644 --- a/app/src/main/java/com/abdurazaaqmohammed/AntiSplit/main/CustomArrayAdapter.java +++ b/app/src/main/java/com/abdurazaaqmohammed/AntiSplit/main/CustomArrayAdapter.java @@ -6,13 +6,10 @@ import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; -import android.widget.Filter; import android.widget.TextView; import com.abdurazaaqmohammed.AntiSplit.R; -import java.util.ArrayList; -import java.util.List; import java.util.Objects; /** @noinspection NullableProblems*/ @@ -22,8 +19,6 @@ public class CustomArrayAdapter extends ArrayAdapter { private final int textColor; private final boolean lang; private String langCode; - private final List filteredList; - private CustomFilter filter; public CustomArrayAdapter(Context context, String[] values, int textColor, boolean lang) { super(context, android.R.layout.simple_list_item_multiple_choice, values); @@ -31,7 +26,6 @@ public CustomArrayAdapter(Context context, String[] values, int textColor, boole this.values = values; this.textColor = textColor; this.lang = lang; - this.filteredList = new ArrayList<>(); if (lang) { String[] langCodes = MainActivity.rss.getStringArray(R.array.langs); for (int i = 0; i < langCodes.length; i++) { @@ -41,17 +35,6 @@ public CustomArrayAdapter(Context context, String[] values, int textColor, boole } } } - this.filteredList.addAll(List.of(values)); // Initialize filteredList with original values - } - - @Override - public int getCount() { - return filteredList.size(); - } - - @Override - public String getItem(int position) { - return filteredList.get(position); } @Override @@ -59,51 +42,10 @@ public View getView(int position, View convertView, ViewGroup parent) { if (convertView == null) { convertView = LayoutInflater.from(context).inflate(lang ? android.R.layout.simple_list_item_1 : android.R.layout.simple_list_item_multiple_choice, parent, false); } - TextView textView = convertView.findViewById(android.R.id.text1); - String curr = getItem(position); // Use the filtered list item - textView.setText(lang && Objects.equals(curr, langCode) ? Html.fromHtml("" + curr + "") : curr); + String curr = values[position]; + textView.setText(lang ? Html.fromHtml(Objects.equals(curr, langCode) ? ("" + curr + "") : curr) : curr); textView.setTextColor(textColor); - return convertView; } - - @Override - public Filter getFilter() { - if (filter == null) { - filter = new CustomFilter(); - } - return filter; - } - - private class CustomFilter extends Filter { - @Override - protected FilterResults performFiltering(CharSequence constraint) { - FilterResults results = new FilterResults(); - if (constraint == null || constraint.length() == 0) { - results.values = List.of(values); - results.count = values.length; - } else { - List filteredItems = new ArrayList<>(); - String filterPattern = constraint.toString().toLowerCase().trim(); - - for (String item : values) { - if (item.toLowerCase().contains(filterPattern)) { - filteredItems.add(item); - } - } - - results.values = filteredItems; - results.count = filteredItems.size(); - } - return results; - } - - @Override - protected void publishResults(CharSequence constraint, FilterResults results) { - filteredList.clear(); - filteredList.addAll((List) results.values); - notifyDataSetChanged(); - } - } -} +} \ No newline at end of file diff --git a/app/src/main/java/com/abdurazaaqmohammed/AntiSplit/main/DeviceSpecsUtil.java b/app/src/main/java/com/abdurazaaqmohammed/AntiSplit/main/DeviceSpecsUtil.java index 3111fe99..4cc83768 100644 --- a/app/src/main/java/com/abdurazaaqmohammed/AntiSplit/main/DeviceSpecsUtil.java +++ b/app/src/main/java/com/abdurazaaqmohammed/AntiSplit/main/DeviceSpecsUtil.java @@ -13,6 +13,7 @@ import java.io.File; import java.io.IOException; +import java.io.InputStream; import java.util.ArrayList; import java.util.Enumeration; import java.util.List; @@ -36,7 +37,8 @@ public DeviceSpecsUtil(Context context) { public List getListOfSplits(Uri splitAPKUri) throws IOException { List splits = new ArrayList<>(); - try (ZipFileInput zis = new ZipFileInput(FileUtils.getInputStream(splitAPKUri, context))) { + try (InputStream is = FileUtils.getInputStream(splitAPKUri, context); + ZipFileInput zis = new ZipFileInput(is)) { ZipFileHeader header; while ((header = zis.readFileHeader()) != null) { final String name = header.getFileName(); @@ -47,7 +49,9 @@ public List getListOfSplits(Uri splitAPKUri) throws IOException { if(splits.size() < 2) { File file = new File(FileUtils.getPath(splitAPKUri, context)); boolean couldNotRead = !file.canRead(); - if(couldNotRead) FileUtils.copyFile(FileUtils.getInputStream(splitAPKUri, context), file = new File(context.getCacheDir(), file.getName())); + try(InputStream is = FileUtils.getInputStream(splitAPKUri, context)) { + if(couldNotRead) FileUtils.copyFile(is, file = new File(context.getCacheDir(), file.getName())); + } Enumeration entries = (zipFile = new ZipFile(file)).getEntries(); // Do not close this ZipFile it could be used later in merger while (entries.hasMoreElements()) { diff --git a/app/src/main/java/com/abdurazaaqmohammed/AntiSplit/main/IconsHelper.java b/app/src/main/java/com/abdurazaaqmohammed/AntiSplit/main/IconsHelper.java new file mode 100644 index 00000000..10abb315 --- /dev/null +++ b/app/src/main/java/com/abdurazaaqmohammed/AntiSplit/main/IconsHelper.java @@ -0,0 +1,34 @@ +package com.abdurazaaqmohammed.AntiSplit.main; +import static com.aefyr.pseudoapksigner.Base64.DEFAULT; +import static com.aefyr.pseudoapksigner.Base64.encodeToString; + +import android.graphics.Bitmap; +import android.graphics.Canvas; +import android.graphics.drawable.BitmapDrawable; +import android.graphics.drawable.Drawable; + +import java.io.ByteArrayOutputStream; + +public class IconsHelper { + static Bitmap drawableToBitmap(Drawable drawable) { + if (drawable instanceof BitmapDrawable) { + return ((BitmapDrawable) drawable).getBitmap(); + } + Bitmap bitmap = Bitmap.createBitmap( + drawable.getIntrinsicWidth(), + drawable.getIntrinsicHeight(), + Bitmap.Config.ARGB_8888 + ); + Canvas canvas = new Canvas(bitmap); + drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight()); + drawable.draw(canvas); + return bitmap; + } + + static String bitmapToBase64(Bitmap bitmap) { + ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); + bitmap.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream); + byte[] byteArray = byteArrayOutputStream.toByteArray(); + return encodeToString(byteArray, DEFAULT); + } +} diff --git a/app/src/main/java/com/abdurazaaqmohammed/AntiSplit/main/MainActivity.java b/app/src/main/java/com/abdurazaaqmohammed/AntiSplit/main/MainActivity.java index d60bb8f6..22dfa365 100644 --- a/app/src/main/java/com/abdurazaaqmohammed/AntiSplit/main/MainActivity.java +++ b/app/src/main/java/com/abdurazaaqmohammed/AntiSplit/main/MainActivity.java @@ -3,6 +3,7 @@ import static android.provider.Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION; import static com.abdurazaaqmohammed.AntiSplit.main.LegacyUtils.supportsActionBar; import static com.abdurazaaqmohammed.AntiSplit.main.LegacyUtils.supportsArraysCopyOfAndDownloadManager; +import static com.abdurazaaqmohammed.AntiSplit.main.LegacyUtils.supportsFileChannel; import static com.reandroid.apkeditor.merge.LogUtil.logEnabled; import com.github.angads25.filepicker.model.DialogConfigs; @@ -16,7 +17,6 @@ import android.app.AlertDialog; import android.app.DownloadManager; import android.content.ClipData; -import android.content.ClipboardManager; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; @@ -38,6 +38,7 @@ import android.os.Handler; import android.os.Looper; import android.provider.OpenableColumns; +import android.support.v4.content.FileProvider; import android.text.Editable; import android.text.Html; import android.text.TextUtils; @@ -76,6 +77,8 @@ import java.net.URL; import java.nio.channels.ClosedByInterruptException; import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; import java.util.List; import java.util.Locale; import java.util.Objects; @@ -294,7 +297,7 @@ protected void onCreate(Bundle savedInstanceState) { styleAlertDialog(new AlertDialog.Builder(this).setSingleChoiceItems(display, curr, (dialog, which) -> { updateLang(LocaleHelper.setLocale(MainActivity.this, lang = langs[which]).getResources(), l); dialog.dismiss(); - }).create(), display, true); + }).create(), display, true, null); }); l.findViewById(R.id.changeBgColor).setOnClickListener(v3 -> showColorPickerDialog(false, bgColor, l)); @@ -305,7 +308,7 @@ protected void onCreate(Bundle savedInstanceState) { title.setTextSize(25); styleAlertDialog( new AlertDialog.Builder(this).setCustomTitle(title).setView(l) - .setPositiveButton(rss.getString(R.string.close), (dialog, which) -> dialog.dismiss()).create(), null, false); + .setPositiveButton(rss.getString(R.string.close), (dialog, which) -> dialog.dismiss()).create(), null, false, null); }); decodeButton.setOnClickListener(v -> { @@ -373,7 +376,7 @@ protected void onCreate(Bundle savedInstanceState) { } } - public void styleAlertDialog(AlertDialog ad, String[] display, boolean isLang) { + public void styleAlertDialog(AlertDialog ad, String[] display, boolean isLang, ArrayAdapter aagh) { GradientDrawable border = new GradientDrawable(); border.setColor(bgColor); // Background color border.setStroke(5, textColor); // Border width and color @@ -382,7 +385,7 @@ public void styleAlertDialog(AlertDialog ad, String[] display, boolean isLang) { runOnUiThread(() -> { ad.show(); ListView lv; - if(display != null && (lv = ad.getListView()) != null) lv.setAdapter(new CustomArrayAdapter(this, display, textColor, isLang)); + if((aagh != null || display != null) && (lv = ad.getListView()) != null) lv.setAdapter(aagh == null ? new CustomArrayAdapter(this, display, textColor, isLang) : aagh); Window w = ad.getWindow(); Button positiveButton = ad.getButton(AlertDialog.BUTTON_POSITIVE); @@ -534,36 +537,31 @@ private void selectAppsListener(View v) { PackageManager pm = getPackageManager(); List packageInfoList = pm.getInstalledPackages(0); - List appsList = new ArrayList<>(); - List pkgNamesList = new ArrayList<>(); + List appInfoList = new ArrayList<>(); for (PackageInfo packageInfo : packageInfoList) { try { - ApplicationInfo ai = pm.getApplicationInfo(packageInfo.packageName, 0); + String packageName = packageInfo.packageName; + ApplicationInfo ai = pm.getApplicationInfo(packageName, 0); if (ai.splitSourceDirs != null) { - appsList.add((String) pm.getApplicationLabel(ai)); - pkgNamesList.add(packageInfo.packageName); + appInfoList.add(new AppInfo((String) pm.getApplicationLabel(ai), pm.getApplicationIcon(ai), packageName)); } } catch (PackageManager.NameNotFoundException ignored) {} } - String[] apps = appsList.toArray(new String[0]); - String[] pkgNames = pkgNamesList.toArray(new String[0]); + Collections.sort(appInfoList, Comparator.comparing(p -> p.name)); LinearLayout dialogView = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.dialog_search, null); ListView listView = dialogView.findViewById(R.id.list_view); - final ArrayAdapter adapter = new CustomArrayAdapter(this, apps, textColor, true); + final AppListArrayAdapter adapter = new AppListArrayAdapter(this, appInfoList, textColor, true); listView.setAdapter(adapter); listView.setOnItemClickListener((parent, view, position, id) -> { ad.dismiss(); boolean realAskValue = ask; ask = true; - // try { - //apkExtractor.extractApk(apps[position]); - for(int i = 0; i < apps.length; i++) if(Objects.equals(apps[i], adapter.getItem(position))) pkgName = pkgNames[i]; + pkgName = adapter.filteredAppInfoList.get(position).packageName; selectDirToSaveAPKOrSaveNow(); - // } catch (PackageManager.NameNotFoundException | IOException e) { showError(e); } ask = realAskValue; }); @@ -586,7 +584,7 @@ public void afterTextChanged(Editable s) { } }); ad.setView(dialogView); - styleAlertDialog(ad, apps, false); + styleAlertDialog(ad, null, false, adapter); } private static class ProcessTask extends AsyncTask { @@ -676,7 +674,7 @@ protected Void doInBackground(Uri... uris) { Merger.run( activity.urisAreSplitApks ? activity.splitAPKUri : null, cacheDir, - uris[0], + (uris[0]), activity, splits, signApk); @@ -781,7 +779,7 @@ private void process(Uri outputUri) { cancelButton.setColorFilter(new LightingColorFilter(0xFF000000, textColor)); ViewSwitcher vs = findViewById(R.id.viewSwitcher); vs.setVisibility(View.VISIBLE); - if(Objects.equals(vs.getCurrentView(), findViewById(R.id.copyLog))) vs.showNext(); + if(Objects.equals(vs.getCurrentView(), findViewById(R.id.finishedButtons))) vs.showNext(); cancelButton.setOnClickListener(v -> { Intent intent; @@ -849,10 +847,10 @@ protected void onPostExecute(String[] result) { try { currentVer = ((Context) activity).getPackageManager().getPackageInfo(((Context) activity).getPackageName(), 0).versionName; } catch (Exception e) { - currentVer = "1.6.6"; + currentVer = null; } boolean newVer = false; - char[] curr = TextUtils.isEmpty(currentVer) ? new char[] {1, 6, 6} : currentVer.replace(".", "").toCharArray(); + char[] curr = TextUtils.isEmpty(currentVer) ? new char[] {1, 6, 6, 1} : currentVer.replace(".", "").toCharArray(); char[] latest = latestVersion.replace(".", "").toCharArray(); for(int i = 0; i < curr.length; i++) { if(latest[i] > curr[i]) { @@ -885,7 +883,7 @@ protected void onPostExecute(String[] result) { }); if(supportsArraysCopyOfAndDownloadManager) builder.setNeutralButton("Go to GitHub Release", (dialog, which) -> activity.startActivity(new Intent(Intent.ACTION_VIEW).setData(Uri.parse("https://github.com/AbdurazaaqMohammed/AntiSplit-M/releases/latest")))); activity.styleAlertDialog(builder.setNegativeButton(rss.getString(R.string.cancel), null).create(), - null, false); + null, false, null); } else if (toast) activity.runOnUiThread(() -> Toast.makeText(activity, rss.getString(R.string.no_update_found), Toast.LENGTH_SHORT).show()); } catch (Exception ignored) { if (toast) activity.runOnUiThread(() -> Toast.makeText(activity, "Failed to check for update", Toast.LENGTH_SHORT).show()); @@ -998,29 +996,42 @@ public void showApkSelectionDialog() { splitsToUse = splits; selectDirToSaveAPKOrSaveNow(); } - }).setNegativeButton("Cancel", null).create(), apkNames, false); + }).setNegativeButton("Cancel", null).create(), apkNames, false, null); } catch (IOException e) { showError(e); } } + private void showSuccess() { - if(!errorOccurred) { + ViewSwitcher vs = findViewById(R.id.viewSwitcher); + vs.setVisibility(View.VISIBLE); + if(Objects.equals(vs.getCurrentView(), findViewById(R.id.cancelButton))) vs.showNext(); + ImageView copyLogButton = findViewById(R.id.copyLog); + LightingColorFilter cf = new LightingColorFilter(0xFF000000, textColor); + copyLogButton.setColorFilter(cf); + copyLogButton.setOnClickListener(v -> copyText(new StringBuilder().append(((TextView) findViewById(R.id.logField)).getText()).append('\n').append(((TextView) findViewById(R.id.errorField)).getText()))); + ImageView installButton = findViewById(R.id.installButton); + if(errorOccurred) installButton.setVisibility(View.GONE); + else { final String success = rss.getString(R.string.success_saved); LogUtil.logMessage(success); runOnUiThread(() -> Toast.makeText(this, success, Toast.LENGTH_SHORT).show()); + File output; + if(signApk && (output = Merger.signedApk) != null && output.exists() && output.length() > 999) { + installButton.setColorFilter(cf); + installButton.setVisibility(View.VISIBLE); + installButton.setOnClickListener(v -> //if (supportsFileChannel && !getPackageManager().canRequestPackageInstalls()) startActivityForResult(new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES).setData(Uri.parse(String.format("package:%s", getPackageName()))), 1234); + startActivity(new Intent(Build.VERSION.SDK_INT > 13 ? Intent.ACTION_INSTALL_PACKAGE : Intent.ACTION_VIEW) + .addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION) + .addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP) + .setData(FileProvider.getUriForFile(this, "com.abdurazaaqmohammed.AntiSplit.provider", output)))); + } else installButton.setVisibility(View.GONE); } - - ViewSwitcher vs = findViewById(R.id.viewSwitcher); - vs.setVisibility(View.VISIBLE); - if(Objects.equals(vs.getCurrentView(), findViewById(R.id.cancelButton))) vs.showNext(); - ImageView b = findViewById(R.id.copyLog); - b.setColorFilter(new LightingColorFilter(0xFF000000, textColor)); - b.setOnClickListener(v -> copyText(new StringBuilder().append(((TextView) findViewById(R.id.logField)).getText()).append('\n').append(((TextView) findViewById(R.id.errorField)).getText()))); } private void copyText(CharSequence text) { - if(supportsActionBar) ((ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE)).setPrimaryClip(ClipData.newPlainText("log", text)); + if(supportsActionBar) ((android.content.ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE)).setPrimaryClip(ClipData.newPlainText("log", text)); else ((android.text.ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE)).setText(text); Toast.makeText(this, rss.getString(R.string.copied_log), Toast.LENGTH_SHORT).show(); } @@ -1051,7 +1062,7 @@ private void showError(Exception e) { sv.setBackgroundColor(bgColor); msg.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, (int) (rss.getDisplayMetrics().heightPixels * 0.6))); sv.addView(msg); - styleAlertDialog(b.setCustomTitle(title).setView(sv).create(), null, false); + styleAlertDialog(b.setCustomTitle(title).setView(sv).create(), null, false, null); /*TextView errorBox = findViewById(R.id.errorField); errorBox.setVisibility(View.VISIBLE); errorBox.setText(stackTrace); diff --git a/app/src/main/java/com/abdurazaaqmohammed/AntiSplit/main/SignUtil.java b/app/src/main/java/com/abdurazaaqmohammed/AntiSplit/main/SignUtil.java index 4616a981..9d4debd1 100644 --- a/app/src/main/java/com/abdurazaaqmohammed/AntiSplit/main/SignUtil.java +++ b/app/src/main/java/com/abdurazaaqmohammed/AntiSplit/main/SignUtil.java @@ -16,6 +16,7 @@ import java.io.File; import java.io.IOException; import java.io.InputStream; +import java.io.OutputStream; import java.security.InvalidKeyException; import java.security.KeyStore; import java.security.KeyStoreException; @@ -63,7 +64,7 @@ public static void signPseudoApkSigner(File temp, Context context, Uri out, Exce if(Build.VERSION.SDK_INT < 30) { // When I tried signing with apksig in AVD with sdk 10 java.security is throwing some error saying something not found // Apparently 11 is the last version that supports v1 signing alone. - try (InputStream fis = FileUtils.getInputStream(temp)) { + try (InputStream is = FileUtils.getInputStream(temp)) { final String FILE_NAME_PAST = "testkey.past"; final String FILE_NAME_PRIVATE_KEY = "testkey.pk8"; File signingEnvironment = new File(context.getFilesDir(), "signing"); @@ -76,15 +77,21 @@ public static void signPseudoApkSigner(File temp, Context context, Uri out, Exce IOUtils.copyFileFromAssets(context, FILE_NAME_PRIVATE_KEY, privateKeyFile); } - PseudoApkSigner.sign(fis, FileUtils.getOutputStream(out, context), pastFile, privateKeyFile); + try(OutputStream os = FileUtils.getOutputStream(out, context)) { + PseudoApkSigner.sign(is, os, pastFile, privateKeyFile); + } } catch (Exception e2) { LogUtil.logMessage(msg); - FileUtils.copyFile(temp, FileUtils.getOutputStream(out, context)); + try(OutputStream os = FileUtils.getOutputStream(out, context)) { + FileUtils.copyFile(temp, os); + } throw(new RuntimeException(msg, e)); // for showError } } else { LogUtil.logMessage(msg); - FileUtils.copyFile(temp, FileUtils.getOutputStream(out, context)); + try(OutputStream os = FileUtils.getOutputStream(out, context)) { + FileUtils.copyFile(temp, os); + } throw(new RuntimeException(msg, e)); // for showError } } diff --git a/app/src/main/java/com/aefyr/pseudoapksigner/IOUtils.java b/app/src/main/java/com/aefyr/pseudoapksigner/IOUtils.java index 2bbebb6a..ceca1a6c 100644 --- a/app/src/main/java/com/aefyr/pseudoapksigner/IOUtils.java +++ b/app/src/main/java/com/aefyr/pseudoapksigner/IOUtils.java @@ -13,8 +13,8 @@ public class IOUtils { public static void copyFileFromAssets(Context context, String assetFileName, File destination) throws IOException { - try (InputStream inputStream = context.getAssets().open(assetFileName)) { - OutputStream outputStream = FileUtils.getOutputStream(destination); + try (InputStream inputStream = context.getAssets().open(assetFileName); + OutputStream outputStream = FileUtils.getOutputStream(destination)) { byte[] buf = new byte[1024 * 1024]; int len; while ((len = inputStream.read(buf)) > 0) outputStream.write(buf, 0, len); diff --git a/app/src/main/java/com/j256/simplezip/ZipFileInput.java b/app/src/main/java/com/j256/simplezip/ZipFileInput.java index b690dae8..6bd2aa7c 100644 --- a/app/src/main/java/com/j256/simplezip/ZipFileInput.java +++ b/app/src/main/java/com/j256/simplezip/ZipFileInput.java @@ -131,12 +131,15 @@ public long readFileDataToFile(String outputPath) throws IOException { * @return THe number of bytes written into the output-stream. */ public long readFileDataToFile(File outputFile) throws IOException { - long numBytes = readFileData(FileUtils.getOutputStream(outputFile)); - if (outputFileMap == null) { - outputFileMap = new HashMap<>(); + try(OutputStream os = FileUtils.getOutputStream(outputFile)) { + long numBytes = readFileData(os); + if (outputFileMap == null) { + outputFileMap = new HashMap<>(); + } + outputFileMap.put(currentFileHeader.getFileName(), outputFile); + return numBytes; } - outputFileMap.put(currentFileHeader.getFileName(), outputFile); - return numBytes; + } /** @@ -227,12 +230,14 @@ public long readRawFileDataToFile(String outputPath) throws IOException { * @return THe number of bytes written into the output-stream. */ public long readRawFileDataToFile(File outputFile) throws IOException { - long numBytes = readRawFileData(FileUtils.getOutputStream(outputFile)); - if (outputFileMap == null) { - outputFileMap = new HashMap<>(); + try(OutputStream os = FileUtils.getOutputStream(outputFile)) { + long numBytes = readRawFileData(os); + if (outputFileMap == null) { + outputFileMap = new HashMap<>(); + } + outputFileMap.put(currentFileHeader.getFileName(), outputFile); + return numBytes; } - outputFileMap.put(currentFileHeader.getFileName(), outputFile); - return numBytes; } /** diff --git a/app/src/main/java/com/reandroid/apk/ApkBundle.java b/app/src/main/java/com/reandroid/apk/ApkBundle.java index 062242d6..0a9b25d2 100644 --- a/app/src/main/java/com/reandroid/apk/ApkBundle.java +++ b/app/src/main/java/com/reandroid/apk/ApkBundle.java @@ -233,7 +233,7 @@ public void loadApkDirectory(File dir, boolean recursive, Context context) throw if(Build.VERSION.SDK_INT > 15) act.finishAffinity(); else act.finish(); latch.countDown(); - }).create(), null, false)); + }).create(), null, false, null)); latch.await(); } load(apkList); diff --git a/app/src/main/java/com/reandroid/apkeditor/merge/Merger.java b/app/src/main/java/com/reandroid/apkeditor/merge/Merger.java index 294067d5..bb047471 100644 --- a/app/src/main/java/com/reandroid/apkeditor/merge/Merger.java +++ b/app/src/main/java/com/reandroid/apkeditor/merge/Merger.java @@ -65,7 +65,8 @@ public interface LogListener { private static void extractAndLoad(Uri in, File cacheDir, Context context, List splits, ApkBundle bundle) throws IOException, MismatchedSplitsException, InterruptedException { logMessage(in.getPath()); boolean checkSplits = splits != null && !splits.isEmpty(); - try (ZipFileInput zis = new ZipFileInput(FileUtils.getInputStream(in, context))) { + try (InputStream is = FileUtils.getInputStream(in, context); + ZipFileInput zis = new ZipFileInput(is)) { ZipFileHeader header; while ((header = zis.readFileHeader()) != null) { String name = header.getFileName(); @@ -95,8 +96,9 @@ private static void extractAndLoad(Uri in, File cacheDir, Context context, List< if (DeviceSpecsUtil.zipFile == null) { File input = new File(FileUtils.getPath(in, context)); boolean couldNotRead = !input.canRead(); - if (couldNotRead) - FileUtils.copyFile(FileUtils.getInputStream(in, context), input = new File(cacheDir, input.getName())); + if (couldNotRead) try(InputStream is = FileUtils.getInputStream(in, context)) { + FileUtils.copyFile(is, input = new File(cacheDir, input.getName())); + } ZipFile zf = new ZipFile(input); extractZipFile(zf, checkSplits, splits, cacheDir); if (couldNotRead) input.delete(); @@ -214,10 +216,12 @@ public static void run(ApkBundle bundle, File cacheDir, Uri out, Context context mergedModule.writeApk(temp = new File(cacheDir, "temp.apk")); logMessage(MainActivity.rss.getString(R.string.signing)); boolean noPerm = MainActivity.doesNotHaveStoragePerm(context); - File stupid = new File(noPerm ? (cacheDir + File.separator + "stupid.apk") : FileUtils.getPath(out, context)); + File stupid = signedApk = new File(noPerm ? (cacheDir + File.separator + "stupid.apk") : FileUtils.getPath(out, context)); try { SignUtil.signDebugKey(context, temp, stupid); - if (noPerm) FileUtils.copyFile(stupid, FileUtils.getOutputStream(out, context)); + if (noPerm) try(OutputStream os = FileUtils.getOutputStream(out, context)) { + FileUtils.copyFile(stupid, os); + } } catch (Exception e) { SignUtil.signPseudoApkSigner(temp, context, out, e); } @@ -257,6 +261,8 @@ public static void run(ApkBundle bundle, File cacheDir, Uri out, Context context } } + public static File signedApk; + public static void run(Uri in, File cacheDir, Uri out, Context context, List splits, boolean signApk) throws Exception { logMessage(com.abdurazaaqmohammed.AntiSplit.main.MainActivity.rss.getString(R.string.searching)); try (ApkBundle bundle = new ApkBundle()) { diff --git a/app/src/main/java/com/reandroid/archive/Archive.java b/app/src/main/java/com/reandroid/archive/Archive.java index 1675c528..3888488f 100644 --- a/app/src/main/java/com/reandroid/archive/Archive.java +++ b/app/src/main/java/com/reandroid/archive/Archive.java @@ -83,8 +83,9 @@ public void extract(File file, ArchiveEntry archiveEntry) throws IOException { //applyAttributes(archiveEntry, file); } private void extractCompressed(File file, ArchiveEntry archiveEntry) throws IOException { - OutputStream outputStream = FileUtils.getOutputStream(file); - IOUtil.writeAll(openInputStream(archiveEntry), outputStream); + try(OutputStream outputStream = FileUtils.getOutputStream(file)) { + IOUtil.writeAll(openInputStream(archiveEntry), outputStream); + } } private void applyAttributes(ArchiveEntry archiveEntry, File file) { CentralEntryHeader ceh = archiveEntry.getCentralEntryHeader(); diff --git a/app/src/main/java/com/reandroid/archive/InputSource.java b/app/src/main/java/com/reandroid/archive/InputSource.java index a5da3858..464e66de 100644 --- a/app/src/main/java/com/reandroid/archive/InputSource.java +++ b/app/src/main/java/com/reandroid/archive/InputSource.java @@ -95,9 +95,9 @@ public void write(File file) throws IOException { if(!dir.exists()){ dir.mkdirs(); } - OutputStream outputStream = FileUtils.getOutputStream(file); - write(outputStream); - outputStream.close(); + try(OutputStream outputStream = FileUtils.getOutputStream(file)) { + write(outputStream); + } } public long write(OutputStream outputStream) throws IOException { InputStream inputStream = openStream(); diff --git a/app/src/main/java/com/reandroid/archive/block/ApkSignatureBlock.java b/app/src/main/java/com/reandroid/archive/block/ApkSignatureBlock.java index 5a13e5b3..3e953c7f 100644 --- a/app/src/main/java/com/reandroid/archive/block/ApkSignatureBlock.java +++ b/app/src/main/java/com/reandroid/archive/block/ApkSignatureBlock.java @@ -119,11 +119,10 @@ public List writeSplitRawToDirectory(File dir) throws IOException{ if(dir1 != null && !dir1.exists()){ dir1.mkdirs(); } - OutputStream outputStream = FileUtils.getOutputStream(file1); - signatureInfo.writeBytes(outputStream); - outputStream.close(); - File file = file1; - writtenFiles.add(file); + try(OutputStream outputStream = FileUtils.getOutputStream(file1)){ + signatureInfo.writeBytes(outputStream); + } + writtenFiles.add(file1); } return writtenFiles; } diff --git a/app/src/main/java/com/reandroid/arsc/chunk/TableBlock.java b/app/src/main/java/com/reandroid/arsc/chunk/TableBlock.java index ead90d0b..0fffd4d9 100644 --- a/app/src/main/java/com/reandroid/arsc/chunk/TableBlock.java +++ b/app/src/main/java/com/reandroid/arsc/chunk/TableBlock.java @@ -509,10 +509,9 @@ public final int writeBytes(File file) throws IOException{ if(dir!=null && !dir.exists()){ dir.mkdirs(); } - OutputStream outputStream = FileUtils.getOutputStream(file); - int length = super.writeBytes(outputStream); - outputStream.close(); - return length; + try(OutputStream outputStream = FileUtils.getOutputStream(file)) { + return super.writeBytes(outputStream); + } } public int resolveStagedAlias(int stagedResId, int def){ StagedAliasEntry stagedAliasEntry = getStagedAlias(stagedResId); diff --git a/app/src/main/java/com/reandroid/arsc/chunk/UnknownChunk.java b/app/src/main/java/com/reandroid/arsc/chunk/UnknownChunk.java index 224064cc..5ddeb8c5 100644 --- a/app/src/main/java/com/reandroid/arsc/chunk/UnknownChunk.java +++ b/app/src/main/java/com/reandroid/arsc/chunk/UnknownChunk.java @@ -86,10 +86,9 @@ public final int writeBytes(File file) throws IOException{ throw new IOException("Can not create directory: "+dir); } } - OutputStream outputStream= FileUtils.getOutputStream(file); - int length = super.writeBytes(outputStream); - outputStream.close(); - return length; + try (OutputStream outputStream= FileUtils.getOutputStream(file)) { + return super.writeBytes(outputStream); + } } @Override public String toString(){ diff --git a/app/src/main/java/com/reandroid/arsc/chunk/xml/ResXmlDocument.java b/app/src/main/java/com/reandroid/arsc/chunk/xml/ResXmlDocument.java index 4dc8e4ea..6f39ce0f 100644 --- a/app/src/main/java/com/reandroid/arsc/chunk/xml/ResXmlDocument.java +++ b/app/src/main/java/com/reandroid/arsc/chunk/xml/ResXmlDocument.java @@ -449,10 +449,9 @@ public final int writeBytes(File file) throws IOException{ if(dir!=null && !dir.exists()){ dir.mkdirs(); } - OutputStream outputStream= FileUtils.getOutputStream(file); - int length = super.writeBytes(outputStream); - outputStream.close(); - return length; + try(OutputStream outputStream= FileUtils.getOutputStream(file)) { + return super.writeBytes(outputStream); + } } public void mergeWithName(ResourceMergeOption mergeOption, ResXmlDocument document) { if(document == this){ diff --git a/app/src/main/java/com/reandroid/json/JSONItem.java b/app/src/main/java/com/reandroid/json/JSONItem.java index 6f78f53c..77935e87 100644 --- a/app/src/main/java/com/reandroid/json/JSONItem.java +++ b/app/src/main/java/com/reandroid/json/JSONItem.java @@ -40,9 +40,9 @@ public void write(File file, int indentFactor) throws IOException{ if(dir != null && !dir.exists()){ dir.mkdirs(); } - OutputStream outputStream= FileUtils.getOutputStream(file); - write(outputStream, indentFactor); - outputStream.close(); + try(OutputStream outputStream= FileUtils.getOutputStream(file)) { + write(outputStream, indentFactor); + } } public void write(OutputStream outputStream) throws IOException { write(outputStream, INDENT_FACTOR); diff --git a/app/src/main/res/layout/activity_main.xml b/app/src/main/res/layout/activity_main.xml index becd98d4..e2686ff2 100644 --- a/app/src/main/res/layout/activity_main.xml +++ b/app/src/main/res/layout/activity_main.xml @@ -13,7 +13,7 @@ - - + android:orientation="horizontal" + android:gravity="center"> + + + + + + diff --git a/app/src/main/res/layout/list_item.xml b/app/src/main/res/layout/list_item.xml new file mode 100644 index 00000000..ada119d6 --- /dev/null +++ b/app/src/main/res/layout/list_item.xml @@ -0,0 +1,22 @@ + + + + + + + + \ No newline at end of file diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 27654b7a..4358f965 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -73,4 +73,6 @@ Pause button Copied log Select from Installed Apps + App icon + Install diff --git a/app/src/main/res/xml/paths.xml b/app/src/main/res/xml/paths.xml new file mode 100644 index 00000000..4d6eec73 --- /dev/null +++ b/app/src/main/res/xml/paths.xml @@ -0,0 +1,9 @@ + + + + + + + \ No newline at end of file