add working FileProvider Intent sourcecode

This commit is contained in:
Alexander Mahr 2025-01-05 23:11:30 +01:00
parent 5aa56d9f5c
commit d5afbdb037
9 changed files with 690 additions and 1 deletions

View file

@ -2,10 +2,14 @@
A "FileProvider" is a special type of "ContentProvider"
The goal of this repo, is to create a container that can serve to produce an "empty android Application" (i.e `app.apk` file).
As such the philosophy is to keep the process "simple" as to now make the understanding too difficult.
The Code regarding the FileProvider setup was adopted from
https://github.com/commonsguy/cw-omnibus/blob/master/ContentProvider/Files/app/src/main/java/com/commonsware/android/cp/files/AbstractFileProvider.java
and the copyright notice was retained in the files
## usage
0. clone this repo

44
app/AndroidManifest.xml Normal file
View file

@ -0,0 +1,44 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="app.installapks"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="30"
android:targetSdkVersion="33"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.READ_MEDIA_AUDIO"/>
<uses-permission android:name="android.permission.READ_MEDIA_IMAGES"/>
<uses-permission android:name="android.permission.READ_MEDIA_VIDEO"/>
<uses-permission android:name="android.permission.READ_MEDIA_VISUAL_USER_SELECTED"/>
<uses-permission android:name="android.permission.POST_NOTIFICATIONS"/>
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES"/>
<application android:debuggable="true" android:label="install APKs" android:icon="@drawable/appicon">
<provider
android:name="app.installapks.FileProvider"
android:authorities="app.installapks"
android:exported="true"
/>
<!-- this below is commented out becuase it stupidly requires the use of JETPACK fuckery -->
<!--
<provider
android:name="app.installapks.Locandroidx.core.content.FileProvider"
android:authorities="com.example.myapp.fileprovider"
android:grantUriPermissions="true"
android:exported="false">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/filepaths" />
</provider>
-->
<activity android:name="app.installapks.AppActivity"
android:exported="true"
android:configChanges="orientation|screenSize|keyboardHidden"
android:label="install APKs">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>

BIN
app/assets/foto.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.3 KiB

BIN
app/assets/test.pdf Normal file

Binary file not shown.

View file

@ -0,0 +1,105 @@
/***
Copyright (c) 2014-2015 CommonsWare, LLC
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.
Covered in detail in the book _The Busy Coder's Guide to Android Development_
https://commonsware.com/Android
*/
package app.installapks;
import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.res.AssetFileDescriptor;
import android.database.Cursor;
import android.database.MatrixCursor;
import android.net.Uri;
import android.provider.OpenableColumns;
// via local java file
// copied from https://github.com/MuntashirAkon/cwac-provider/blob/3dccc0ef9cd2eda5fe149b87ff4ef4881c583f8c/provider/src/main/java/com/commonsware/cwac/provider/LegacyCompatCursorWrapper.java
//import com.commonsware.cwac.provider.LegacyCompatCursorWrapper;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLConnection;
abstract class AbstractFileProvider extends ContentProvider {
private final static String[] OPENABLE_PROJECTION= {
OpenableColumns.DISPLAY_NAME, OpenableColumns.SIZE };
@Override
public Cursor query(Uri uri, String[] projection, String selection,
String[] selectionArgs, String sortOrder) {
if (projection == null) {
projection=OPENABLE_PROJECTION;
}
final MatrixCursor cursor=new MatrixCursor(projection, 1);
MatrixCursor.RowBuilder b=cursor.newRow();
for (String col : projection) {
if (OpenableColumns.DISPLAY_NAME.equals(col)) {
b.add(getFileName(uri));
}
else if (OpenableColumns.SIZE.equals(col)) {
b.add(getDataLength(uri));
}
else { // unknown, so just add null
b.add(null);
}
}
return(new LegacyCompatCursorWrapper(cursor));
}
@Override
public String getType(Uri uri) {
return(URLConnection.guessContentTypeFromName(uri.toString()));
}
protected String getFileName(Uri uri) {
return(uri.getLastPathSegment());
}
protected long getDataLength(Uri uri) {
return(AssetFileDescriptor.UNKNOWN_LENGTH);
}
@Override
public Uri insert(Uri uri, ContentValues initialValues) {
throw new RuntimeException("Operation not supported");
}
@Override
public int update(Uri uri, ContentValues values, String where,
String[] whereArgs) {
throw new RuntimeException("Operation not supported");
}
@Override
public int delete(Uri uri, String where, String[] whereArgs) {
throw new RuntimeException("Operation not supported");
}
static void copy(InputStream in, File dst)
throws IOException {
FileOutputStream out=new FileOutputStream(dst);
byte[] buf=new byte[1024];
int len;
while ((len=in.read(buf)) >= 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
}
}

View file

@ -0,0 +1,181 @@
package app.installapks;
import android.provider.Settings ;
import android.content.Intent;
import android.util.Log;
import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
//import android.view.MenuItem;
import android.view.*;
// for WebView,WebMessage,WebMessagePort,
import android.webkit.*;
import android.net.Uri;
import org.json.JSONObject;
import java.io.InputStream;
import java.io.File;
import java.util.Objects;
public class AppActivity extends Activity {
private static final String BASE_URI = "https://alexmahr.de";
// private void installApkProgramatically() {
// try {
// File path = activity.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS);
//
// File file = new File(path, filename);
//
// Uri uri;
//
// if (file.exists()) {
//
// Intent unKnownSourceIntent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES).setData(Uri.parse(String.format("package:%s", activity.getPackageName())));
//
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
//
// if (!activity.getPackageManager().canRequestPackageInstalls()) {
// startActivityForResult(unKnownSourceIntent, Constant.UNKNOWN_RESOURCE_INTENT_REQUEST_CODE);
// } else {
// Uri fileUri = FileProvider.getUriForFile(activity.getBaseContext(), activity.getApplicationContext().getPackageName() + ".provider", file);
// Intent intent = new Intent(Intent.ACTION_VIEW, fileUri);
// intent.putExtra(Intent.EXTRA_NOT_UNKNOWN_SOURCE, true);
// intent.setDataAndType(fileUri, "application/vnd.android" + ".package-archive");
// intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
// intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
// startActivity(intent);
// alertDialog.dismiss();
// }
//
// } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
//
// Intent intent1 = new Intent(Intent.ACTION_INSTALL_PACKAGE);
// uri = FileProvider.getUriForFile(activity.getApplicationContext(), BuildConfig.APPLICATION_ID + ".provider", file);
// activity.grantUriPermission("com.abcd.xyz", uri, Intent.FLAG_GRANT_READ_URI_PERMISSION);
// activity.grantUriPermission("com.abcd.xyz", uri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
// intent1.setDataAndType(uri,
// "application/*");
// intent1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// intent1.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
// intent1.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
// startActivity(intent1);
//
// } else {
// Intent intent = new Intent(Intent.ACTION_VIEW);
//
// uri = Uri.fromFile(file);
//
// intent.setDataAndType(uri,
// "application/vnd.android.package-archive");
// intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// startActivity(intent);
// }
// } else {
//
// Log.i(TAG, " file " + file.getPath() + " does not exist");
// }
// } catch (Exception e) {
//
// Log.i(TAG, "" + e.getMessage());
//
// }
// }
//
public String readFileFromAssets(String filename) {
String filecontents = "";
try {
InputStream stream = getAssets().open(filename);
int filesize = stream.available();
byte[] filebuffer = new byte[filesize];
stream.read(filebuffer);
stream.close();
filecontents = new String(filebuffer);
} catch (Exception e) {
// I <3 java exceptions
}
return filecontents;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// this removes the title bar (a ~1cm big strip at the top of the app showing its name
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
// we create the webview (at least on the android 14 that is a webview that features avif + websockets etc....)
WebView myWebView = new WebView(this);//activityContext);
// MyJavascriptInterface myJavaScriptInterface = new MyJavascriptInterface(this,myWebView);
// we create a webview (there is also setwebviewclient-vs-setwebchromeclient
WebViewClient myWebViewClient= new WebViewClient();
myWebView.setWebViewClient(myWebViewClient);
// to setup settings
WebSettings myWebSettings = myWebView.getSettings();
myWebSettings.setBuiltInZoomControls(true);
myWebSettings.setDisplayZoomControls(false);
myWebSettings.setJavaScriptEnabled(true);
myWebSettings.setDomStorageEnabled(true);
myWebSettings.setDatabaseEnabled(true);
myWebSettings.setDatabasePath("/data/data/" + myWebView.getContext().getPackageName() + "/databases/");
myWebView.addJavascriptInterface(this, "myJavaScriptInterface");
// load the html from assets file
String html = readFileFromAssets("index.html");
myWebView.loadDataWithBaseURL(BASE_URI,html, "text/html", "UTF-8",null);
//myWebView.loadData(encodedHtml, "text/html", "base64");
// alternatively this could be to load a website
//myWebView.loadUrl("https://alexmahr.de/ru");
setContentView(myWebView);
}
// @Override
// public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
// super.onActivityResult(requestCode, resultCode, data);
// switch (requestCode) {
//
// case Constant.UNKNOWN_RESOURCE_INTENT_REQUEST_CODE:
// switch (resultCode) {
// case Activity.RESULT_OK:
// installApkProgramatically();
//
// break;
// case Activity.RESULT_CANCELED:
// //unknown resouce installation cancelled
//
// break;
// }
// break;
// }
@JavascriptInterface
public String startActivity(String fileName) {
File filesDir = getFilesDir();
Log.i("startActivity with Uri",FileProvider.CONTENT_URI
+ fileName);
Intent i = new Intent(Intent.ACTION_VIEW,
Uri.parse(FileProvider.CONTENT_URI
+ fileName));
i.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivity(i);
return filesDir.getAbsolutePath();
}
@JavascriptInterface
public String download(String downloadurl) {
File filesDir = getFilesDir();
Log.i("BAAAAA",FileProvider.CONTENT_URI
+ "foto.jpg");
Intent i = new Intent(Intent.ACTION_VIEW,
Uri.parse(FileProvider.CONTENT_URI
+ "foto.jpg"));
i.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivity(i);
return filesDir.getAbsolutePath();
// this.webview.evaluateJavascript("(setTimeout(()=>{document.body.innerHTML='all gone';},2000)()",null);
// return "this is good";
}
@JavascriptInterface
public String toString() {
// this.webview.evaluateJavascript("(setTimeout(()=>{document.body.innerHTML='all gone';},2000)()",null);
return "this is good";
}
}

View file

@ -0,0 +1,117 @@
/***
Copyright (c) 2008-2014 CommonsWare, LLC
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.
Covered in detail in the book _The Busy Coder's Guide to Android Development_
https://commonsware.com/Android
*/
package app.installapks;
import android.content.res.AssetManager;
import android.net.Uri;
import android.os.ParcelFileDescriptor;
import android.util.Log;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
public class FileProvider extends AbstractFileProvider {
public static final Uri CONTENT_URI=
Uri.parse("content://app.installapks/");
@Override
public boolean onCreate() {
return(true);
}
public File openAssetFile(String path)
throws FileNotFoundException {
File root=getContext().getFilesDir();
File f = new File(root, path).getAbsoluteFile();
if(!f.exists()){
AssetManager assets=getContext().getAssets();
try {
copy(assets.open(path.substring(1)), f);
}
catch (IOException e) {
Log.e("FileProvider", "Exception copying from assets", e);
throw new FileNotFoundException(path);
}
}
return f;
}
@Override
public ParcelFileDescriptor openFile(Uri uri, String mode)
throws FileNotFoundException {
File root=getContext().getFilesDir();
File f = openAssetFile(uri.getPath());
if (!f.getPath().startsWith(root.getPath())) {
throw new
SecurityException("Resolved path jumped beyond root");
}
if (f.exists()) {
return(ParcelFileDescriptor.open(f, parseMode(mode)));
}
throw new FileNotFoundException(uri.getPath());
}
@Override
protected long getDataLength(Uri uri)
{
try {
File f = openAssetFile(uri.getPath());
return(f.length());
} catch (Exception e) {
return 0;
}
}
// following is from ParcelFileDescriptor source code
// Copyright (C) 2006 The Android Open Source Project
// (even though this method was added much after 2006...)
private static int parseMode(String mode) {
final 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("Bad mode '" + mode + "'");
}
return modeBits;
}
}

View file

@ -0,0 +1,219 @@
/***
Copyright (c) 2015-2016 CommonsWare, LLC
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 app.installapks;
import android.database.Cursor;
import android.database.CursorWrapper;
import android.net.Uri;
import java.util.Arrays;
import static android.provider.MediaStore.MediaColumns.DATA;
import static android.provider.MediaStore.MediaColumns.MIME_TYPE;
/**
* Wraps the Cursor returned by an ordinary FileProvider,
* StreamProvider, or other ContentProvider. If the query()
* requests _DATA or MIME_TYPE, adds in some values for
* that column, so the client getting this Cursor is less
* likely to crash. Of course, clients should not be requesting
* either of these columns in the first place...
*/
public class LegacyCompatCursorWrapper extends CursorWrapper {
final private int fakeDataColumn;
final private int fakeMimeTypeColumn;
final private String mimeType;
final private Uri uriForDataColumn;
/**
* Constructor.
*
* @param cursor the Cursor to be wrapped
*/
public LegacyCompatCursorWrapper(Cursor cursor) {
this(cursor, null);
}
/**
* Constructor.
*
* @param cursor the Cursor to be wrapped
* @param mimeType the MIME type of the content represented
* by the Uri that generated this Cursor, should
* we need it
*/
public LegacyCompatCursorWrapper(Cursor cursor, String mimeType) {
this(cursor, mimeType, null);
}
/**
* Constructor.
*
* @param cursor the Cursor to be wrapped
* @param mimeType the MIME type of the content represented
* by the Uri that generated this Cursor, should
* we need it
* @param uriForDataColumn Uri to return for the _DATA column
*/
public LegacyCompatCursorWrapper(Cursor cursor, String mimeType,
Uri uriForDataColumn) {
super(cursor);
this.uriForDataColumn=uriForDataColumn;
if (cursor.getColumnIndex(DATA)>=0) {
fakeDataColumn=-1;
}
else {
fakeDataColumn=cursor.getColumnCount();
}
if (cursor.getColumnIndex(MIME_TYPE)>=0) {
fakeMimeTypeColumn=-1;
}
else if (fakeDataColumn==-1) {
fakeMimeTypeColumn=cursor.getColumnCount();
}
else {
fakeMimeTypeColumn=fakeDataColumn+1;
}
this.mimeType=mimeType;
}
/**
* {@inheritDoc}
*/
@Override
public int getColumnCount() {
int count=super.getColumnCount();
if (!cursorHasDataColumn()) {
count+=1;
}
if (!cursorHasMimeTypeColumn()) {
count+=1;
}
return(count);
}
/**
* {@inheritDoc}
*/
@Override
public int getColumnIndex(String columnName) {
if (!cursorHasDataColumn() && DATA.equalsIgnoreCase(
columnName)) {
return(fakeDataColumn);
}
if (!cursorHasMimeTypeColumn() && MIME_TYPE.equalsIgnoreCase(
columnName)) {
return(fakeMimeTypeColumn);
}
return(super.getColumnIndex(columnName));
}
/**
* {@inheritDoc}
*/
@Override
public String getColumnName(int columnIndex) {
if (columnIndex==fakeDataColumn) {
return(DATA);
}
if (columnIndex==fakeMimeTypeColumn) {
return(MIME_TYPE);
}
return(super.getColumnName(columnIndex));
}
/**
* {@inheritDoc}
*/
@Override
public String[] getColumnNames() {
if (cursorHasDataColumn() && cursorHasMimeTypeColumn()) {
return(super.getColumnNames());
}
String[] orig=super.getColumnNames();
String[] result=Arrays.copyOf(orig, getColumnCount());
if (!cursorHasDataColumn()) {
result[fakeDataColumn]=DATA;
}
if (!cursorHasMimeTypeColumn()) {
result[fakeMimeTypeColumn]=MIME_TYPE;
}
return(result);
}
/**
* {@inheritDoc}
*/
@Override
public String getString(int columnIndex) {
if (!cursorHasDataColumn() && columnIndex==fakeDataColumn) {
if (uriForDataColumn!=null) {
return(uriForDataColumn.toString());
}
return(null);
}
if (!cursorHasMimeTypeColumn() && columnIndex==fakeMimeTypeColumn) {
return(mimeType);
}
return(super.getString(columnIndex));
}
/**
* {@inheritDoc}
*/
@Override
public int getType(int columnIndex) {
if (!cursorHasDataColumn() && columnIndex==fakeDataColumn) {
return(Cursor.FIELD_TYPE_STRING);
}
if (!cursorHasMimeTypeColumn() && columnIndex==fakeMimeTypeColumn) {
return(Cursor.FIELD_TYPE_STRING);
}
return(super.getType(columnIndex));
}
/**
* @return true if the Cursor has a _DATA column, false otherwise
*/
private boolean cursorHasDataColumn() {
return(fakeDataColumn==-1);
}
/**
* @return true if the Cursor has a MIME_TYPE column, false
* otherwise
*/
private boolean cursorHasMimeTypeColumn() {
return(fakeMimeTypeColumn==-1);
}
}

View file

@ -0,0 +1,19 @@
/* AUTO-GENERATED FILE. DO NOT MODIFY.
*
* This class was automatically generated by the
* aapt tool from the resource data it found. It
* should not be modified by hand.
*/
package app.installapks;
public final class R {
public static final class attr {
}
public static final class drawable {
public static final int appicon=0x7f020000;
}
public static final class xml {
public static final int filepaths=0x7f030000;
}
}