FileProvider - IllegalArgumentException: Failed to find configured root share flutter - flutter

I'm trying to share a image with plugin share flutter, but I'm getting the following error:
java.lang.IllegalArgumentException: Failed to find configured root that contains /storage/emulated/0/Android/data/.../cache/share/image-777.jpg
AndroidManifest.xml:
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/provider_path"/>
</provider>
flutter:
final urlImage =
'https://images.tokopedia.net/img/cache/500-square/hDjmkQ/2021/9/13/343063bb-f7c5-468d-9602-9b06ced70bdb.jpg';
final uri = Uri.parse(urlImage);
final response = await http.get(uri);
final bytes = response.bodyBytes;
final temp = await getTemporaryDirectory();
final path = '${temp.path}/image-777.jpg';
File(path).writeAsBytesSync(bytes);
await Share.shareFiles(
[path],
// text: wording + ' ' + url,
// subject: 'Refer your friend',
);
provider_path.xml:
<?xml version="1.0" encoding="utf-8"?>
<paths>
<external-path
name="external"
path="/" />
<external-files-path
name="external_files"
path="/" />
<cache-path
name="cache"
path="/" />
<external-cache-path
name="external_cache"
path="/" />
<files-path
name="files"
path="/" />
</paths>
I was searching whole day about this error and trying to understand FileProvider, but I have no idea what this error message tries to tell me, i already change '.' to '/' in provider_path.xml or '/cache/share' but still not working . If you want more info/code, write me in the comment.

Related

Trying to delete an audio file but giving exception in flutter

I'm trying to delete song file but it is unable to delete and throws an exception of permission denied but permissions are already granted using permission_handler and required storage permissions are added in AndroidManifest.xml as well. I have also checked path is valid and file exist before delete which return true. Would anyone help me to solve this.
Error on file.delete() line.
Unhandled Exception: FileSystemException: Deletion failed, path = '/storage/0E15-2E06/Music/Call Sound Effect.mp3' (OS Error: Permission denied, errno = 13)
AndroidManifest:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
<application
android:label="Example"
android:name="${applicationName}"
android:icon="#mipmap/ic_launcher"
android:usesCleartextTraffic="true"
android:requestLegacyExternalStorage="true" >
Code snippet:
if (await Permission.storage.request().isGranted) {
// Either the permission was already granted before or the user just granted it.
// permission was granted
if (song != null) {
String? path = song.data;
File file = File(path);
bool isExist = await file.exists();
if (isExist) {
await file.delete(recursive: true);
}
}
}
You have to use the permission_handler(https://pub.dev/packages/permission_handler) package and have to mention some permissions in the Androidmanifest.xml file.
<uses-permission android:name="android.permission.WRITE_INTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
Also, you have to ask Permission of storage before doing storage related operation(In your case deletion of audio file).
final _permissionStatus = await Permission.storage.request();
if(_permissionStatus = PermissionStatus.isGranted){
/// Delete audio file
}else{
/// Permission Denied.
}

How to wire up an Share intent in MAUI for Android?

I'm trying to work out how to wire up a Share intent in Android using MAUI.
Am I running into preview bugs, or am I not doing it correctly?
I'm running MAUI Preview 10, with Visual Studio 17.1.0 Preview 1.0.
Version 1
I've added the share intent to the AndroidManifest.xml file:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<uses-sdk android:minSdkVersion="21" android:targetSdkVersion="31" />
<application android:allowBackup="true" android:icon="#mipmap/appicon" android:roundIcon="#mipmap/appicon_round" android:supportsRtl="true">
<activity android:name="SomeLongName.MainActivity" >
<intent-filter>
<action android:name="android.intent.action.SEND" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="text/plain" />
</intent-filter>
</activity>
</application>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
</manifest>
And then by adding a Name property to the MainActivity class:
[Activity(Name = "SomeLongName.MainActivity", Theme = "#style/Maui.SplashTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation | ConfigChanges.UiMode | ConfigChanges.ScreenLayout | ConfigChanges.SmallestScreenSize)]
public class MainActivity : MauiAppCompatActivity
{
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
if (Intent.Type == "text/plain")
{
}
}
}
When I debug the application in MAUI, the app builds correctly and the Output says that the app has deployed. However, in Visual Studio, the debugger fails to run, and there is no evidence of the app on the emulator.
Version 2
In version 2, I've tried to create a separate activity for the Share intent:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<uses-sdk android:minSdkVersion="21" android:targetSdkVersion="31" />
<application android:allowBackup="true" android:icon="#mipmap/appicon" android:roundIcon="#mipmap/appicon_round" android:supportsRtl="true">
<activity android:name="SomeLongName.ShareActivity" >
<intent-filter>
<action android:name="android.intent.action.SEND" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="text/plain" />
</intent-filter>
</activity>
</application>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
</manifest>
[Activity(Name = "SomeLongName.ShareActivity")]
public class ShareActivity : MauiAppCompatActivity
{
protected override void OnCreate(Bundle savedInstanceState)
{
if (Intent.Type == "text/plain" && Intent.Action == "android.intent.action.SEND")
{
//handleSendUrl();
}
base.OnCreate(savedInstanceState);
}
I can now successfully debug the application, but when I try to share to the application, I get an exception on the base.OnCreate call:
Java.Lang.IllegalStateException: 'The specified child already has a parent. You must call removeView() on the child's parent first.'
Seems the issue centres around themes. The solution is in the original question, apply Version 2. With some minor updates. In the MainApplication class add an attribute defining the theme (same as in MainActivity class but could be different).
[Application(Theme = "#style/Maui.SplashTheme")]
public class MainApplication : MauiApplication
{
public MainApplication(IntPtr handle, JniHandleOwnership ownership)
: base(handle, ownership)
{
}
protected override MauiApp CreateMauiApp() => MauiProgram.CreateMauiApp();
}
This both works without error and enables debugging.
Without the MainApplication theme setting, when sharing to the android app (incoming), an error thrown:
Java.Lang.IllegalArgumentException: 'The style on this component requires your app theme to be Theme.MaterialComponents (or a descendant).'
In my secondary activity, the Activity attribute sets the Theme, but is ignored and error still shown, hence the Application level needed. Not sure why.
[Activity(Theme = "#android:style/Theme.MaterialComponents.Light", Name = "com.somename.receiveurlactivity", MainLauncher = false, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation | ConfigChanges.UiMode | ConfigChanges.ScreenLayout | ConfigChanges.SmallestScreenSize)]
public class ReceiveUrlActivity : MauiAppCompatActivity
{
//.... etc

AndroidAlarmManagerPlus not starting automatically after reboot

I've set permissions in the AndroidManifest.xml file
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<uses-permission android:name="android.permission.WAKE_LOCK"/>
I've also added the following lines in the AndroidManifest.xml as specified in the docs
<service
android:name="dev.fluttercommunity.plus.androidalarmmanager.AlarmService"
android:permission="android.permission.BIND_JOB_SERVICE"
android:exported="false"/>
<receiver
android:name="dev.fluttercommunity.plus.androidalarmmanager.AlarmBroadcastReceiver"
android:exported="false"/>
<receiver
android:name="dev.fluttercommunity.plus.androidalarmmanager.RebootBroadcastReceiver"
android:enabled="false">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"></action>
</intent-filter>
</receiver>
In my main.dart file, I've the following lines of codes...
import 'package:android_alarm_manager_plus/android_alarm_manager_plus.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await AndroidAlarmManager.initialize();
runApp(MyApp());
await AndroidAlarmManager.periodic(Duration(minutes: 1), 0, syncData);
}
void syncData() async {
print("synching data");
String? uploadedUrl = await S3.uploadToS3();
print(uploadedUrl);
}
What should I add for this to work automatically on reboot? TIA :)
From Android 8.0 You can't use most of the implicit broadcast ,
So your application service will not start on
ACTION_LOCKED_BOOT_COMPLETED or ACTION_BOOT_COMPLETED
for more details
you can use WorkManager instead to sync data to server
here is a good example

Flutter Image File share Permission Denial

When i am try to share my directory image via share plug in ! Image is not going to share ! Asking me permission what is that ??? Can any one give me solution on it
FlatButton(
onPressed: () async {
Directory dir = await getApplicationDocumentsDirectory();
File testFile = new File("${dir.path}/image.png");
FlutterShareFile.shareImage(dir.path, "image.png", ShareFileType.image);
},
)
I am getting this type of warning :
E/DatabaseUtils( 8123): java.lang.SecurityException: Permission Denial: reading androidx.core.content.FileProvider uri content://com.photogranth.watermark.contentprovider/images/image.png from pid=6574, uid=1000 requires the provider be exported, or grantUriPermission()
E/DatabaseUtils( 8123): at android.content.ContentProvider.enforceReadPermissionInner(ContentProvider.java:742)
E/DatabaseUtils( 8123): at android.content.ContentProvider$Transport.enforceReadPermission(ContentProvider.java:615)
E/DatabaseUtils( 8123): at android.content.ContentProvider$Transport.enforceFilePermission(ContentProvider.java:606)
E/DatabaseUtils( 8123): at android.content.ContentProvider$Transport.openTypedAssetFile(ContentProvider.java:520)
E/DatabaseUtils( 8123): at android.content.ContentProviderNative.onTransact(ContentProviderNative.java:307)
E/DatabaseUtils( 8123): at android.os.Binder.execTransactInternal(Binder.java:1021)
E/DatabaseUtils( 8123): at android.os.Binder.execTransact(Binder.java:994)
Did you add this to your AndroidManifest.xml file?
<application>
...
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}.provider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/provider_paths"/>
</provider>
</application>

SSRS 2008 Execution Service LoadReport Error

I'm using SSRS 2008 (NOT R2)
I have a report deployed to a dev server, I'm trying to render the report as a pdf by calling the execution service.
The error I am getting is
This operation is not supported on a report server that runs in native mode. ---> Microsoft.ReportingServices.Diagnostics.Utilities.OperationNotSupportedNativeModeException: This operation is not supported on a report server that runs in native mode.
Two things I notice: one is that web service wsdl shows LoadReport having two parameters - report path and history id, but when I generate a service reference for the ReportExecution2005.asmx, the LoadReport method has 5 parameters: trusteduserheader, reportPath, historyid, serviceinfoheader, and executionheader
I have tried adding the service reference with and without ?wsdl at the end of the url but the result is the same
Here's the code I'm using:
ReportExecutionServiceSoapClient rs = new ReportExecutionServiceSoapClient("ReportExecutionServiceSoap", "http://xxx:80/ReportServer/ReportExecution2005.asmx");
rs.ClientCredentials.Windows.ClientCredential = new NetworkCredential("aaa", "aaa", "aaa");
rs.ClientCredentials.Windows.AllowedImpersonationLevel = TokenImpersonationLevel.Impersonation;
// Render arguments
byte[] result = null;
string reportPath = "/Invoices/InvoiceStandard";
string format = "PDF";
string historyID = null;
string devInfo = "";
// Prepare report parameter.
ParameterValue[] parameters = new ParameterValue[3];
parameters[0] = new ParameterValue();
parameters[0].Name = "PartyID";
parameters[0].Value = "19758";
parameters[1] = new ParameterValue();
parameters[1].Name = "Contract";
parameters[1].Value = "17703"; // June
parameters[2] = new ParameterValue();
parameters[2].Name = "FinancialPeriod";
parameters[2].Value = "MAR-2012";
string encoding="";
string mimeType="";
string extension="";
Warning[] warnings = null;
string[] streamIDs = null;
ExecutionInfo execInfo = new ExecutionInfo();
TrustedUserHeader trusteduserHeader = new TrustedUserHeader();
ExecutionHeader execHeader = new ExecutionHeader();
ServerInfoHeader serviceInfo = new ServerInfoHeader();
execHeader = rs.LoadReport(trusteduserHeader, reportPath, historyID, out serviceInfo, out execInfo);
rs.SetExecutionParameters(execHeader, trusteduserHeader, parameters, "en-us", out execInfo);
try
{
rs.Render(execHeader,
trusteduserHeader,
format,
devInfo,
out result,
out extension,
out encoding,
out mimeType,
out warnings,
out streamIDs);
}
Here's my web.config
<?xml version="1.0"?>
<configuration>
<connectionStrings>
<add name="ApplicationServices"
connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnetdb.mdf;User Instance=true"
providerName="System.Data.SqlClient" />
</connectionStrings>
<system.web>
<compilation debug="true" targetFramework="4.0" />
<authentication mode="Forms">
<forms loginUrl="~/Account/Login.aspx" timeout="2880" />
</authentication>
<membership>
<providers>
<clear/>
<add name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider" connectionStringName="ApplicationServices"
enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false"
maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10"
applicationName="/" />
</providers>
</membership>
<profile>
<providers>
<clear/>
<add name="AspNetSqlProfileProvider" type="System.Web.Profile.SqlProfileProvider" connectionStringName="ApplicationServices" applicationName="/"/>
</providers>
</profile>
<roleManager enabled="false">
<providers>
<clear/>
<add name="AspNetSqlRoleProvider" type="System.Web.Security.SqlRoleProvider" connectionStringName="ApplicationServices" applicationName="/" />
<add name="AspNetWindowsTokenRoleProvider" type="System.Web.Security.WindowsTokenRoleProvider" applicationName="/" />
</providers>
</roleManager>
</system.web>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
</system.webServer>
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="ReportExecutionServiceSoap" closeTimeout="00:01:00"
openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"
allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"
maxBufferSize="65536" maxBufferPoolSize="524288" maxReceivedMessageSize="65536"
messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered"
useDefaultWebProxy="true">
<readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
maxBytesPerRead="4096" maxNameTableCharCount="16384" />
<security mode="TransportCredentialOnly">
<transport clientCredentialType="Windows"/>
<message clientCredentialType="UserName" algorithmSuite="Default" />
</security>
</binding>
</basicHttpBinding>
</bindings>
<client>
<endpoint address="http://xxx:80/ReportServer/ReportExecution2005.asmx"
binding="basicHttpBinding" bindingConfiguration="ReportExecutionServiceSoap"
contract="SSRS.ReportExecutionServiceSoap" name="ReportExecutionServiceSoap" />
</client>
</system.serviceModel>
</configuration>
I had the same problem with SSRS 2008 R2, but I did not want to resort to calling the report viewer control.
Above, Rick Hodder was using the following statement:
TrustedUserHeader trusteduserHeader = new TrustedUserHeader();
This statement will cause the OperationNotSupportedNativeModeException error he encountered if the SSRS installation is not configured with a certificate for SSL connections. Check the SSRS Logs for an error entry that contains:
ERROR: TrustedHeader Not Supported in Native Mode.
If this is the case, you need to either configure the server to work with SSL, or use null for the trusted header.
TrustedUserHeader trusteduserHeader = null;
Is this report loaded from some front end or is it loaded from DLL? To me it looks like you are using ASP.net Application. In this case you could use reportViewer object to pull the report for you all the heavy lifting can be done by the ReportViewer and you can then just save the file as PDF
using something like this
reportViewer.ServerReport.ReportServerUrl = new Uri(Config.ReportServerURL);
reportViewer.ServerReport.ReportPath = String.Format("{0}/{1}", Config.ReportServerEnvironment, reportName);
reportViewer.ServerReport.ReportServerCredentials = new ReportsCredentials(Config.ReportServerUser, Config.ReportServerPassword, Config.ReportServerDomain);
reportViewer.GetDocumentStream(SSRSFormatType.Pdf, documentName);
Here reportViewer is the reference to ReportViewer object on the screen.