I'm unable to create directory in android 10. It's working on devices till android Oreo.
I tried two ways for creating folders.
Using File.mkdir():
File f = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Pastebin");
if (!f.isFile()) {
if (!(f.isDirectory())) {
success = f.mkdir();
}
Here, the variable success is always false which means the directory isn't created.
Using Files.createDirectory():
File f = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Pastebin");
if (!f.isFile()) {
if (!(f.isDirectory())) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
try {
Files.createDirectory(Paths.get(f.getAbsolutePath()));
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), R.string.unable_to_download, Toast.LENGTH_LONG).show();
}
} else {
f.mkdir();
}
}
which causes this exception:
pzy64.pastebinpro W/System.err: java.nio.file.AccessDeniedException: /storage/emulated/0/Pastebin
pzy64.pastebinpro W/System.err: at sun.nio.fs.UnixFileSystemProvider.createDirectory(UnixFileSystemProvider.java:391)
pzy64.pastebinpro W/System.err: at java.nio.file.Files.createDirectory(Files.java:674)
I've implemented the run-time permissions and
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
are all set.
As was first disclosed back in March 2019, you no longer have access by default to arbitrary locations on external storage or removable storage on Android 10+. This includes Environment.getExternalStorageDirectory() and other methods on Environment (e.g., getExternalStoragePublicDirectory().
For Android 10 and 11, you can add android:requestLegacyExternalStorage="true" to your <application> element in the manifest. This opts you into the legacy storage model, and your existing external storage code will work.
Otherwise, your choices are:
Use methods on Context, such as getExternalFilesDir(), to get at directories on external storage into which your app can write. You do not need any permissions to use those directories on Android 4.4+. However, the data that you store there gets removed when your app is uninstalled.
Use the Storage Access Framework, such as ACTION_OPEN_DOCUMENT and ACTION_CREATE_DOCUMENT.
If your content is media, you can use MediaStore to place the media in standard media locations.
For Android 10, you can add
android:requestLegacyExternalStorage="true"
to your element in the manifest. This opts you into the legacy storage model, and your existing external storage code will work. This fix will not work on Android R and higher though, so this is only a short-term fix.
There are more restrictions in Android API 30
you can only write in your app-specific files
File dir_ = new File(context.getFilesDir(), "YOUR_DIR");
dir_.mkdirs();
or in the external storage of your app Android/data
File dir_ = new File(myContext.getExternalFilesDir("FolderName"),"YOUR_DIR");
UPDATE
this answer provided another solution https://stackoverflow.com/a/65744517/8195076
UPDATE
another way is to grant this permission in manifest
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
like this answer https://stackoverflow.com/a/66968986/8195076
This works for me and I think it's functional on Android 10>
ContentResolver resolver = getContentResolver();
ContentValues contentValues = new ContentValues();
contentValues.put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_PICTURES + "/Folder Example");
String path = String.valueOf(resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues));
File folder = new File(path);
boolean isCreada = folder.exists();
if(!isCreada) {
folder.mkdirs();
}
You can use public directory to save files in Android 11 like this:
dir = new File(Environment.getExternalStoragePublicDirectory(DIRECTORY_DOCUMENTS).getPath()
+ "/foldername");
if (!dir.exists()) {
dir.mkdir();
Toast.makeText(getApplicationContext(), "not exist", Toast.LENGTH_SHORT).show();
}
Since Q beta 4 it's possible to opt-out of that feature by:
targeting api 28 (or lower)
using requestLegacyExternalStorage manifest attribute:
<manifest ... >
<!-- This attribute is "false" by default on apps targeting Android Q. -->
<application android:requestLegacyExternalStorage="true" ... >
...
</application>
</manifest>
only use
android:requestLegacyExternalStorage="true"
in manifests
Related
Opening Whatsapp with intent is not working in android OS 11 but working fine up to android (OS) 10 devices, It displays the message "Whatsapp app not installed in your phone" on the android 11 device. Does anyone have a solution for this?
String contact = "+91 9999999999"; // use country code with your phone number
String url = "https://api.whatsapp.com/send?phone=" + contact;
try {
PackageManager pm = context.getPackageManager();
pm.getPackageInfo("com.whatsapp", PackageManager.GET_ACTIVITIES);
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
context.startActivity(i);
} catch (PackageManager.NameNotFoundException e) {
Toast.makeText(mContext, "Whatsapp app not installed in your phone",Toast.LENGTH_LONG).show();
e.printStackTrace();
}
There are new changes in android 11 of package visibility.
You need to add a new section queries under you app's <manifest> tag with desired package name:
<manifest package="com.example.app">
<queries>
<package android:name="com.whatsapp" />
</queries>
...
</manifest>
Instead of using wildcards, it's more explicit to add both package names:
<manifest package="com.example.app">
<queries>
<package android:name="com.whatsapp"/>
<package android:name="com.whatsapp.w4b"/>
</queries>
...
</manifest>
"com.whatsapp"
can also be the culprit.
i was also boggled with this message.
the issue was "whatsApp business app" which has package name:
"com.whatsapp.w4b"
used following code to find out which one is installed:
String appPackage="";
if (isAppInstalled(ctx, "com.whatsapp.w4b")) {
appPackage = "com.whatsapp.w4b";
//do ...
} else if (isAppInstalled(ctx, "com.whatsapp")) {
appPackage = "com.whatsapp";
//do ...
} else {
Toast.makeText(ctx, "whatsApp is not installed", Toast.LENGTH_LONG).show();
}
private boolean isAppInstalled(Context ctx, String packageName) {
PackageManager pm = ctx.getPackageManager();
boolean app_installed;
try {
pm.getPackageInfo(packageName, PackageManager.GET_ACTIVITIES);
app_installed = true;
} catch (PackageManager.NameNotFoundException e) {
app_installed = false;
}
return app_installed;
}
Rather than adding each Package names in , you can add:
**<uses-permission android:name="android.permission.QUERY_ALL_PACKAGES" tools:ignore="QueryAllPackagesPermission" />**
to your AndroidManifest.xml file in your project.
I was also bothering with the same, this permission allowed me to troubleshoot my issue/error.
To open Whatsapp or Whatsapp Business on button click use the below code.
To open whatsapp
Intent intent1 = getPackageManager().getLaunchIntentForPackage("com.whatsapp");
startActivity(intent1);
To open Business whatsapp
Intent intent2 = getPackageManager().getLaunchIntentForPackage("com.whatsapp.w4b");
startActivity(intent2);
When I try to execute newly created azure function with CosmosDBTrigger, I get the above exception for the function with cosmosdb trigger
Investigative information
Environment:
Visual Studio 2017 15.3.5
Packages referenced:
Marvin.JsonPatch.Dynamic Version="1.1.0"
Microsoft.Azure.DocumentDB Version="1.17.0"
Microsoft.Azure.WebJobs Version="2.1.0-beta4"
Microsoft.Azure.WebJobs.Extensions.DocumentDB Version="1.1.0-beta4"
Microsoft.Azure.WebJobs.ServiceBus Version="2.0.0"
Microsoft.NET.Sdk.Functions Version="1.0.5"
Newtonsoft.Json Version="10.0.3"
System.Configuration.ConfigurationManager Version="4.4.0"
Steps to reproduce the issue
Provide the steps required to reproduce the problem:
Create a new Azure Function Project from Visual Studio
Add a function (i didn't find any option for CosmosDB Binding so i created using HttpTrigger)
once the .cs file is created, replace the file with the code that i have put below.
Build
Hit F5
Here is the code sample
public static class AddEventInEventStore
{
[FunctionName("AddEventInEventStore")]
public static void Run([CosmosDBTrigger("db", "Items",
ConnectionStringSetting = "AzureWebJobsDocumentDBConnectionString",
LeaseCollectionName = "leases", LeaseDatabaseName = "db"
)]
IReadOnlyList<Document> changeList, TraceWriter log)
{
if (changeList != null && changeList.Count > 0)
{
log.Verbose("Documents modified " + changeList.Count);
foreach (var change in changeList)
{
log.Verbose("First document Id " + change.Id);
}
}
}
}
Update your Azure Functions and Web Jobs Tools (Tools -> Extensions and Updates).
I can see you are on 1.0.0 version (console title), while 1.0.4 is already available.
I am trying to create VSIX package to extend functionality of TFS 2012 source control right click context menu when clicking on branch.
I don't want to use Add-in. this has to be package which other developers can directly install.
The customized menu items need to appear in the source control explorer contextual menu after they install the extension. I am not able to get any sample for this requirement or not able to get proper documentation source. One of sample I found is "TFS community branch tool", which is kind of similar functionality I am looking for, but I am not able to get the source code of it.
Appreciate your help.
I assume that you are familiar with the .vsct file, command/menu/groups Guids/Id stuff (all this is documented in MSDN). So, the question would be which is the Guid/Id of the group inside the context menu of Source Control Explorer.
Guessing that you may want your command below the "Get Latest Version" menu entry of the context menu of a file, the code would be:
<Commands package="guidVSMyPackagePkg">
<Buttons>
<Button guid="guidVSMyPackageCmdSet" id="cmdidMyCommand" priority="0x0100" type="Button">
<Parent guid="guidSourceControlExplorerMenuGroup" id="SourceControlExplorerMenuGroupId"/>
<Strings>
<ButtonText>My Command</ButtonText>
</Strings>
</Button>
</Buttons>
</Commands>
<Symbols>
<GuidSymbol name="guidVSMyPackagePkg" value="{...}" />
<GuidSymbol name="guidVSMyPackageCmdSet" value="{...}">
<IDSymbol name="cmdidMyCommand" value="0x0100" />
</GuidSymbol>
<GuidSymbol name="guidSourceControlExplorerMenuGroup" value="{ffe1131c-8ea1-4d05-9728-34ad4611bda9}">
<IDSymbol name="SourceControlExplorerMenuGroupId" value="0x1111" />
</GuidSymbol>
</Symbols>
Building upon Carlos Quintero's answer:
If you need to put the command in any other location in the Source Control Explorers context menu, you need the right Id. Using EnableVSIPLogging you can only find information for commands and their parent menus, but not the groups.
In order to find Group Ids (or any other ID for that matter) used in the Source Control Explorer you can follow these steps (for VS2015):
Decompile Microsoft.VisualStudio.TeamFoundation.VersionControl.dll (using JetBrains dotPeek for instance).
Open Resources\HatPackage.resources.
Look up 1000.ctmenu and copy the Base64 data.
Convert the data from Base64 to bytes.
Save the bytes in a file as TfsMenu.cto (the extension needs to be .cto and it needs to be in a location with write rights for the next step to work).
Run "C:\Program Files (x86)\Microsoft Visual Studio 14.0\VSSDK\VisualStudioIntegration\Tools\Bin\vsct.exe" TfsMenu.cto TfsMenu.vsct to decompile the file.
Now you have the original .vsct file that was used to make the TFS plugin. In here you can look up all IDs.
To get you started finding the menuitems in TfsMenu.vsct, you can enable EnableVSIPLogging:
Add HKEY_CURRENT_USER\SOFTWARE\Microsoft\VisualStudio\14.0\General\EnableVSIPLogging as DWORD32 with value 1.
Now, in Visual Studio, when Holding Ctrl+Shift while hovering menus or clicking menu items in the Source Control Explorer, a messagebox pops up with information about that item, including the GUID and ID of that menu/menuitem
#Erik I was so happy to run across your explanation for extracting the vsct as I trying very hard to figure out how to do that very thing. Just to expound upon your answer I converted it into code. Sharing here in case anyone is interested.
static void Main(string[] args)
{
/*
Extract menus from extensions
http://stackoverflow.com/questions/29831181/creating-vsix-package-for-tfs-source-control-explorer-context-menu-extension
*/
try
{
string vsctPath = ConfigurationManager.AppSettings["VSCTPath"];
if (!File.Exists(vsctPath))
{
WriteConsole("The path to the vsct.exe could not be found. Please edit the app.config to set the right executable path.", ConsoleColor.Yellow);
return;
}
//TODO: Convert to a command line argument
string dllPath = #"C:\Program Files (x86)\Microsoft SQL Server\130\Tools\Binn\ManagementStudio\Extensions\Application\Microsoft.SqlServer.Management.SqlStudio.Explorer.dll";
var assembly = Assembly.LoadFrom(dllPath);
if (assembly == null)
{
WriteConsole("Could not load assembly.", ConsoleColor.Yellow);
return;
}
var resourceName = assembly.GetManifestResourceNames().FirstOrDefault(n => Regex.IsMatch(n, #"VSPackage\.resources", RegexOptions.IgnoreCase));
if (String.IsNullOrWhiteSpace(resourceName))
{
WriteConsole("Could find VSPackage.resources in assembly.", ConsoleColor.Yellow);
return;
}
var resourceManager = new ResourceManager(Path.GetFileNameWithoutExtension(resourceName), assembly);
if (resourceManager == null)
{
WriteConsole("Could find load the resource " + resourceName + ".", ConsoleColor.Yellow);
return;
}
var menus = resourceManager.GetObject("Menus.ctmenu") as byte[];
if (menus == null)
{
WriteConsole("Could find Menus.ctmenu resource in VSPackage.resources.", ConsoleColor.Yellow);
return;
}
string dir = Path.Combine(Path.GetTempPath(), "PackageMenus");
string fileName = Path.GetFileNameWithoutExtension(dllPath) + ".cto";
Directory.CreateDirectory(dir);
Directory.SetCurrentDirectory(dir);
File.WriteAllBytes(Path.Combine(dir, fileName), menus);
string processArgs = String.Format(#"{0} {1}.vsct", fileName, fileName);
var pi = new ProcessStartInfo(vsctPath, processArgs);
pi.UseShellExecute = false;
pi.RedirectStandardError = true;
pi.RedirectStandardOutput = true;
var ret = Process.Start(pi);
var output = ret.StandardOutput.ReadToEnd();
var errors = ret.StandardError.ReadToEnd();
Console.WriteLine(output);
if (!string.IsNullOrWhiteSpace(errors))
{
Console.Write("Errors: ");
WriteConsole(errors, ConsoleColor.Red);
}
else
{
Console.WriteLine("New files written to: " + dir);
}
}
catch(Exception ex)
{
WriteConsole(ex.ToString(), ConsoleColor.Red);
}
finally
{
Console.WriteLine("\r\nPress any key to continue.");
Console.ReadKey(true);
}
}
private static void WriteConsole(string message, ConsoleColor color = ConsoleColor.White)
{
Console.ForegroundColor = color;
Console.WriteLine(message);
Console.ResetColor();
}
I am currently using the Google AdMob Xamarin component (version 6.12.0 - see https://components.xamarin.com/view/googleadmob) to display DFP interstitials and banner ads (displayed at different points within a tableview) on an iOS app. When I am debugging in Visual Studio 2013 I get the following output:
<Google:HTML> You are currently using version 6.12.0 of the SDK, which doesn't
officially support iOS 8. Please consider updating your SDK to the most recent
sdk version, 6.12.2, to get iOS 8 support, including a fix for smart banner
rendering in landscape mode. The latest SDK can be downloaded from
http://goo.gl/iGzfsP. A full list of release notes is available at
https://developers.google.com/mobile-ads-sdk/docs/admob/ios/rel-notes.
According to the Xamarin component's page, 6.12.0 does actually support iOS 8. Should I ignore the warning that I am getting? If not, how do I go about using 6.12.2 when the newest version of the component is only 6.12.0? Is it OK to stay with 6.12.0 or will it cause issues?
I have noticed that the banner ads aren't really displaying in the correct location on iOS8, they are slightly to the right and down from where they should be. Is this because of the SDK or some other change in iOS8 regarding how cells are displayed?
Below is how I display the banner ad:
public void InitialiseBanner(AdMobView property)
{
_bannerViewDelegate = new AdMobBannerViewDelegate();
_bannerView = new DFPBannerView();
float x = (CurrentWidth/2) - (AdvertWidth/2);
_bannerView.RootViewController = this;
_bannerView.BackgroundColor = UIColor.White;
_bannerView.Delegate = _bannerViewDelegate;
_bannerView.Frame = new RectangleF(x, 5, AdvertWidth, 50);
View.Frame = new RectangleF(0, 0, CurrentWidth, 50);
View.AddSubview(_bannerView);
_bannerView.AdUnitID = "/**UNITIDREMOVED**/" + property.AdAlias;
GADRequest request = GADRequest.Request;
.
.
.
_bannerView.LoadRequest(request);
View.BringSubviewToFront(_bannerView);
if (DeviceHelper.IsIos8OrGreater && RespondsToSelector(new Selector("separatorInset")))
{
_bannerView.LayoutMargins = UIEdgeInsets.Zero;
}
}
As for a normal banner, try loading your AdView Like this:
(This is my working example)
As a class level declaration, type this:
GADBannerView adView;
bool viewOnScreen = false;
// Get you own AdmobId from: http://www.google.com/ads/admob/
const string AdmobId = "<your admob id>";
Then in your viewDidLoad you can specify position of your banner and load it:
adView = new GADBannerView (size: GADAdSizeCons.Banner, origin: new PointF (0, UIScreen.MainScreen.Bounds.Height-100)) {
AdUnitID = AdmobId,
RootViewController = this
};
adView.DidReceiveAd += (sender, args) => {
if (!viewOnScreen) View.AddSubview (adView);
viewOnScreen = true;
};
adView.LoadRequest (GADRequest.Request);
I get the same error as well, but it doesn't actually matter. I also thought first that this was the issue but my setup was a bit wrong, i think that is the same for your code. In my example i just added my AdView to the MainView, but using custom cells you should be able to implement it in your UITable View. Also, have a look at the example provided in the components section. As for displaying DFP interstitials: There has to be something wrong with the setup as well, but i can't see it in the code you provided.
After upgrading some of our external websites running on SharePoint 2007 to 2010, we ran a link checker to find problems. We noticed the log showed requests for a file called spsdisco.aspx. Indeed, when examining the source of our web pages, SharePoint is adding the following link element to the page HEAD:
<link href="_vti_bin/spsdisco.aspx" rel="alternate" type="text/xml" />
This is a web service discovery file listing out the names and locations of all of SharePoint's web service endpoints. Even worse, this file is starting to show up in search indexes. At best it is embarrassing; at worst it's a potential vulnerability (these are external websites). Because it's a virtual file, it shows up under every site and subsite, so a manual approach to "hiding" each one is difficult and clumsy.
I can't seem to find any actual documentation about it -- a few references on updating it to include a custom web service, but that's about it. How might we approach a reliable, top-down approach to disabling access to these pages? I think we can find a way to suppress the LINK element in the page, but that's just obscuring the problem.
Is there a location in SharePoint (Site or Central Admin) to turn it off? Would you just add some request filtering to IIS to disallow access to SPSdisco.aspx and the ASMX files?
Update: On Kev's suggestion, I've cross-posted to sharepoint.stackexchange.com.
Update 2: See, I hadn't abandoned this question. We finally had time to get some MS guidance and build a deployable SharePoint solution to address the issue.
As a quick fix I would add a request filtering rule to deny access to SPSDisco.aspx.
But you might want to ask on the new SharePoint Stack Exchange site about a more robust fix:
https://sharepoint.stackexchange.com/
Here is the solution that we arrived at. It was in part based on recommendations by our Microsoft representative, so you might consider this an unofficial, "official" approach.
First, we need keep SharePoint from advertising the disco file to the world (i.e. Google). Simply remove the following line in your master pages:
<SharePoint:SoapDiscoveryLink runat="server"/>
This will suppress the <link href="/_vti_bin/spsdisco.aspx" rel="alternate" type="text/xml"> reference in the HEAD of your pages.
Next, we want to make sure that unauthorized users don't have access to the web services described by the disco file, or anything in _vti_bin for that matter. If your site only runs internal to your firewall (an intranet, for example), then this isn't as important. But if you've got anonymous endpoints that can be accessed externally, you want them locked down.
This is an excellent application for an HttpModule. We'll build one that intercepts any request containing _vti_bin in the path, and if the current user is unauthorized will return a 404 NOT FOUND status code. I chose to return a 404 rather than a 401 UNAUTHORIZED because I don't just want to lock those paths down, I want to hide the fact that anything even exists at those paths.
Our HttpModule looks like this:
using System;
using System.Web;
namespace Custom.SharePoint.HttpModule.SpSecureVtiBin {
public class SpSecureVtiBinModule : IHttpModule {
#region IHttpModule Members
public void Dispose() { }
public void Init( HttpApplication context ) {
context.AuthorizeRequest += new EventHandler( context_AuthorizeRequest );
}
protected virtual void context_AuthorizeRequest( object sender, EventArgs e ) {
HttpApplication app = (HttpApplication)sender;
string requestedPath = app.Request.Path;
if ( requestedPath.ToLowerInvariant().Contains( "_vti_bin" ) ) {
if ( !app.Request.IsAuthenticated ) {
app.Response.StatusCode = 404;
app.Response.StatusDescription = "Not Found";
app.Response.Write( "404 NOT FOUND" );
app.Response.End();
}
}
}
#endregion
}
}
Simple enough. To use the HttpModule, it needs to be registered in the site's web.config file with an entry under \configuration\system.webServer\modules:
<add name="SpSecureVtiBinModule" type="Custom.SharePoint.HttpModule.SpSecureVtiBin.SpSecureVtiBinModule, Custom.SharePoint.HttpModule.SpSecureVtiBin, Version=1.0.0.0, Culture=neutral, PublicKeyToken=[your_public_key_token]" />
Of course, we don't want to modify a SharePoint application's web.config file manually. We'll create an SPFeatureReceiver to do the job:
using System.Collections.ObjectModel;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
namespace Custom.SharePoint.HttpModule.SpSecureVtiBin {
public class ModuleFeatureReceiver : SPFeatureReceiver {
private static string _owner = "SpSecureVtiBinModule";
public override void FeatureActivated( SPFeatureReceiverProperties properties ) {
SPWebApplication app = (SPWebApplication)properties.Feature.Parent;
app.WebConfigModifications.Add( GetModificationForSystemWebServer() );
app.WebService.ApplyWebConfigModifications();
app.Update();
}
public override void FeatureDeactivating( SPFeatureReceiverProperties properties ) {
SPWebApplication app = (SPWebApplication)properties.Feature.Parent;
Collection<SPWebConfigModification> mods = app.WebConfigModifications;
int modCount = mods.Count;
bool modRemoved = false;
for ( int i = modCount - 1; i >= 0; i-- ) {
SPWebConfigModification mod = mods[i];
if ( mod.Owner.Equals( _owner ) || mod.Owner.Equals( "CHK.SharePoint.HttpModule.SpSecureVtiBin.SpSecureVtiBinModule" ) ) {
app.WebConfigModifications.Remove( mod );
modRemoved = true;
}
}
if ( modRemoved ) {
app.WebService.ApplyWebConfigModifications();
app.Update();
}
}
private SPWebConfigModification GetModificationForSystemWebServer() {
return new SPWebConfigModification {
Name = "add[#name='SpSecureVtiBinModule']",
Owner = _owner,
Path = "configuration/system.webServer/modules",
Value = #"<add name=""SpSecureVtiBinModule"" type=""Custom.SharePoint.HttpModule.SpSecureVtiBin.SpSecureVtiBinModule, Custom.SharePoint.HttpModule.SpSecureVtiBin, Version=1.0.0.0, Culture=neutral, PublicKeyToken=[your_public_key_token]"" />",
Sequence = 0
};
}
}
}
Now all that's left is to package up the HttpModule. You'll need to define a Feature in the package and reference the SPFeatureReceiver class. This will cause the web.config entry to be added when the Feature is activated, and the entry to be removed when the Feature is deactivated. Target the Feature for a WebApplication and the assembly deployment target to GlobalAssemblyCache.