I have an xls file in my server which needs to be downloaded in my phone using an apps. I'm using Nokia 5 and Android 9 for testing. My compile sdk version is 29. When I clicked download button, it didn't do anything, and after waiting for a while, a "Download Unsuccessful" notification popped up.
This is my MainActivity.java
public class MainActivity extends AppCompatActivity {
private static final int PERMISSION_STORAGE_CODE = 1000;
EditText editUrl;
Button btnDownload;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editUrl = findViewById(R.id.edit_url);
btnDownload = findViewById(R.id.btn_download);
btnDownload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {
String [] permissions = {Manifest.permission.WRITE_EXTERNAL_STORAGE};
requestPermissions(permissions, PERMISSION_STORAGE_CODE);
}
else {
startDownloading();
}
}
else {
startDownloading();
}
}
});
}
private void startDownloading() {
String url = editUrl.getText().toString().trim();
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE);
request.setTitle("Download");
request.setDescription("Downloading file...");
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, ""+System.currentTimeMillis());
DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
manager.enqueue(request);
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch(requestCode) {
case PERMISSION_STORAGE_CODE: {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
startDownloading();
else
Toast.makeText(this, "Permission Denied", Toast.LENGTH_SHORT).show();
}
}
}
}
I added network_security_config.xml (domain is blurred for security reason)
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
<base-config cleartextTrafficPermitted="true" />
<domain-config cleartextTrafficPermitted="true">
<domain includeSubdomains="true">moneytracker.mauini******.com</domain>
</domain-config>
</network-security-config>
and added it in manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.main.downloadtest">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme"
android:networkSecurityConfig="#xml/network_security_config"
android:usesCleartextTraffic="true">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
And lastly, the download url is something like this:
http://moneytracker.mauini******.com/uploads/asd.xls
The file is successfully downloaded when that URL is executed in browser.
Am I missing something? Those are all I can get, searching for days. Please help.
First, on your code request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, ""+System.currentTimeMillis());. After Environment.DIRECTORY_DOWNLOADS param, you should put correct file name on it. coolfilename.xxx. Or, get its Uri value and put the Uri.getLastPathSegment() as the second parameter. Second, try to put request.setMimeType(param).
Related
I'm creating an application, which will show toast messages before and after the call states. I generated and installed my application on my mobile. it was working well after a few days or sometimes a few hours. but after that, it's stopped, in order to run the application I need to open the application again. how can I modify my application to work very well? Thank you
manifest
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.READ_CALL_LOG" />
<uses-permission android:name="android.permission.PROCESS_OUTGOING_CALLS" />
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity"></activity>
<activity android:name=".MainActivity2">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity> <!-- This part is inside the application -->
<receiver
android:name=".CallReceiver"
android:enabled="true">
<intent-filter android:priority="999">
<action android:name="android.intent.action.PHONE_STATE" />
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.NEW_OUTGOING_CALL" />
</intent-filter>
</receiver>
</application>
</manifest>
MainActivity.class
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
checkAndRequestPermissions();
}
private boolean checkAndRequestPermissions() {
int readPhoneState = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE);
int read_call_log = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CALL_LOG);
List listPermissionsNeeded = new ArrayList<>();
if (readPhoneState != PackageManager.PERMISSION_GRANTED) {
listPermissionsNeeded.add(Manifest.permission.READ_PHONE_STATE);
}
if (read_call_log != PackageManager.PERMISSION_GRANTED) {
listPermissionsNeeded.add(Manifest.permission.READ_CALL_LOG);
}
if (read_call_log != PackageManager.PERMISSION_GRANTED) {
listPermissionsNeeded.add(Manifest.permission.PROCESS_OUTGOING_CALLS);
}
if (read_call_log != PackageManager.PERMISSION_GRANTED) {
listPermissionsNeeded.add(Manifest.permission.INTERNET);
}
if (!listPermissionsNeeded.isEmpty()) {
ActivityCompat.requestPermissions(this,
(String[]) listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]),
REQUEST_ID_MULTIPLE_PERMISSIONS);
return false;
}
return true;
}
CallReciver.class
public class CallReceiver extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent) {
try {
runfirstTime(context,intent);
Toast.makeText(context, "1st", Toast.LENGTH_SHORT).show();
} catch (Exception ex) {
try {
}
catch (Exception e)
{
}
}
}
}
New versions of Android does not allow you to do what you are trying to achieve, unless you create foreground service.
Android does not want apps to run in background without explicit knowledge of the user.
So you need to create a foreground service and show a persistent notification in notification panel. Then you can create a BroadcastReceiver from the Foreground Service.
Launch your service as a foreground service using the code below
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
context.startForegroundService(intent);
}
else {
context.startService(intent);
}
And in service onCreate() make something like that:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
startForeground(1, new Notification());
}
Links below will give you a little more insight into Foreground Services.
https://blog.logimonk.com/post/foreground-service-in-android
https://medium.com/#debuggingisfun/android-o-work-around-background-service-limitation-e697b2192bc3
Create your BroadcastReceiver from the service.
I am trying to update my app from outside Google Play, but I have an error, I have looked at everything and I cannot find a solution.
With the following 3 methods I hope to do the AutoUpdate:
private final String FILE_NAME = "app-release.apk";
public void checkStoragePermission(){
if (ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 123);
} else {
updateApp();}
}
private void updateApp() {
Uri uri = FileProvider.getUriForFile(this, getApplicationContext().getPackageName() + ".provider", new File(this.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS).toString() + "/" + FILE_NAME));
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.setFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setDataAndType(uri, "application/vnd.android.package-archive");
startActivity(intent);
}
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case 123: {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
updateApp();
} else {
checkStoragePermission();
}
return;
}
}
}
My Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.jose.updateinapp">
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<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/file_paths" />
</provider>
</application>
</manifest>
And the .xml for FileProvider
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path
name="files_root"
path="Android/data/${applicationId}" />
<external-path
name="external_files"
path="." />
</paths>
The app that i'm attempting to install is the same but with versionCode 2 and versionName 2.0 instead of versionCode 1 and versionName 2.0
When executed this throws an error on the device: error parsing the package
Nothing comes out in the run console. And in the logcat the following errors appear:
E/DatabaseUtils: Writing exception to parcel
java.lang.SecurityException: Permission Denial: reading androidx.core.content.FileProvider uri
content://com.jose.updateinapp.provider/external_files/Android/data/com.jose.updateinapp/files/Download/app-release.apk
from pid=16603, uid=10035 requires the provider be exported, or
grantUriPermission()
Error staging apk from content URI
java.lang.SecurityException: Permission Denial: reading androidx.core.content.FileProvider uri
content://com.jose.updateinapp.provider/external_files/Android/data/com.jose.updateinapp/files/Download/app-release.apk
from pid=16603, uid=10035 requires the provider be exported, or
grantUriPermission()
Any solution? Thank you!
Sorry,something missed in my head.
Try this:
<?xml version="1.0" encoding="utf-8"?>
<paths>
<external-path
name="external"
path="" />
<external-files-path
name="Download"
path="" />
</paths>
uri = FileProvider.getUriForFile(context,
"packgeName.provider",
new File(context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), "xxx.apk"));
intentInstall.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
just try it. it worked in my project..
private void updateApp() {
Uri uri = FileProvider.getUriForFile(this, getApplicationContext().getPackageName() + ".provider", new File(this.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS).toString() + "/" + FILE_NAME));
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
//setFlags change addFlags
intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setDataAndType(uri, "application/vnd.android.package-archive");
startActivity(intent);
}
I want to install new version of my app programmatically. with targetSdkVersion=23 app works fine and this is my code:
public class MainActivity extends AppCompatActivity {
private int PERMISSION_REQUEST_STORAGE = 0;
private DownloadController downloadController;
Button btn_download;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn_download = findViewById(R.id.buttonDownload);
btn_download.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
checkStoragePermission();
}
});
}
public void checkStoragePermission() {
if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
String url= getApplicationContext().getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS).toString() + "/example.apk";
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.setDataAndType(Uri.parse("file://" + url), "application/vnd.android.package-archive");
String selfPackageName = getApplicationContext().getPackageName();
ComponentName componentName = intent.resolveActivity(getApplicationContext().getPackageManager());
String otherPackageName = (componentName != null ? componentName.getPackageName() : "");
if (MainActivity.this == null || !selfPackageName.equals(otherPackageName)) {
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
}
startActivity(intent);
} else {
requestStoragePermission();
}
}
public void requestStoragePermission() {
ActivityCompat.requestPermissions(
MainActivity.this,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
PERMISSION_REQUEST_STORAGE);
}
}
but with targetSdkVersion=29 I heard that I have to use FileProvider. I used this instructure but unfortunately it dosent open my apk to install. this is my res=>xml=>file_provider_paths.xml
<?xml version="1.0" encoding="utf-8"?>
<paths>
<external-path
name="external"
path="." />
<external-files-path
name="external_files"
path="." />
<files-path
name="files"
path="." />
</paths>
my manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.mysms">
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name=".service.OnComplete" >
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
</intent-filter>
</receiver>
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="com.example.myapp"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/file_provider_paths" />
</provider>
</application>
</manifest>
my mainActivity
public class MainActivity extends AppCompatActivity {
private int PERMISSION_REQUEST_STORAGE = 0;
private DownloadController downloadController;
Button btn_download;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn_download = findViewById(R.id.buttonDownload);
btn_download.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
checkStoragePermission();
}
});
}
public void checkStoragePermission() {
if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
File file = new File(getApplicationContext().getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS).toString() + "/example.apk");
Uri uri = FileProvider.getUriForFile(getApplicationContext(), "com.example.myapp", file);
Intent install = new Intent(Intent.ACTION_VIEW);
install.setData(Uri.fromFile(file));
install.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
install.setClassName("com.example.myapp", "com.example.myapp.MainActivity");
install.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
ClipData clipData = new ClipData(new ClipDescription("Meshes", new String[]{ClipDescription.MIMETYPE_TEXT_URILIST}), new ClipData.Item(uri));
install.setClipData(clipData);
startActivity(install);
} else {
requestStoragePermission();
}
}
public void requestStoragePermission() {
ActivityCompat.requestPermissions(
MainActivity.this,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
PERMISSION_REQUEST_STORAGE);
}
}
I get this error
2019-12-17 00:46:38.035 32020-32020/com.example.myapp E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.mysms, PID: 32020
android.os.FileUriExposedException: file:///storage/emulated/0/Android/data/com.example.myapp/files/Download/example.apk exposed beyond app through Intent.getData()
at android.os.StrictMode.onFileUriExposed(StrictMode.java:1799)
at android.net.Uri.checkFileUriExposed(Uri.java:2346)
at android.content.Intent.prepareToLeaveProcess(Intent.java:8933)
at android.content.Intent.prepareToLeaveProcess(Intent.java:8894)
at android.app.Instrumentation.execStartActivity(Instrumentation.java:1517)
at android.app.Activity.startActivityForResult(Activity.java:4224)
at androidx.fragment.app.FragmentActivity.startActivityForResult(FragmentActivity.java:767)
at android.app.Activity.startActivityForResult(Activity.java:4183)
at androidx.fragment.app.FragmentActivity.startActivityForResult(FragmentActivity.java:754)
at android.app.Activity.startActivity(Activity.java:4507)
at android.app.Activity.startActivity(Activity.java:4475)
at com.example.mysms.MainActivity.checkStoragePermission(MainActivity.java:107)
at com.example.mysms.MainActivity$3.onClick(MainActivity.java:76)
at android.view.View.performClick(View.java:5610)
at android.view.View$PerformClick.run(View.java:22265)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
It seems the problem is that you set wrong uri to intent data:
install.setData(Uri.fromFile(file));
You need to set uri which was created with FileProvider:
Uri uri = FileProvider.getUriForFile(getApplicationContext(), "com.example.myapp", file);
install.setData(uri);
The same is done in the instruction you have found:
val contentUri = FileProvider.getUriForFile(
context,
BuildConfig.APPLICATION_ID + PROVIDER_PATH,
File(destination)
)
val install = Intent(Intent.ACTION_VIEW)
install.data = contentUri
please help , when i run the app, the app launch a Fatal Error im learning
just i create a instat with a call but not run, (sorry for my english)
.......................................................................
my manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.android.octa.appprueba3">
<uses-permission android:name="android.permission.CALL_PHONE" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
<category android:name="android.intent.category.APP_CONTACTS" />
</intent-filter>
</activity>
<activity android:name=".SecondActivity"></activity>
</application>
</manifest>
my code:
public class SecondActivity extends AppCompatActivity {
private EditText editPhoneText;
private ImageButton imageCallButton;
private final int PHONE_CALL_CODE = 100;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
editPhoneText = (EditText) findViewById(R.id.editTextPhone);
imageCallButton = (ImageButton) findViewById(R.id.imageCallButton1);
imageCallButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
implicito();
}
});
}
public void implicito(){
Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("Tel: 9999999" ));
startActivity(intent);
}
}
You may want to check whether your device can handle your intent by doing this:
PackageManager packageManager = getPackageManager();
if (intent.resolveActivity(packageManager) != null) {
startActivity(intent);
} else {
Log.d(TAG, "Cannot handle this intent");
}
What's more, if you are placing a call like so, there is NO need to declare the permission in your manifest:
<uses-permission android:name="android.permission.CALL_PHONE" />
Because you are not directly calling someone within your app. You are actually transferring the "duty" to other apps which can handle your intent to call. This doesn't need a permission.
To directly make a call within your app, the intent should be Intent.ACTION_CALL, which needs the permission you declared.
Hope this will help.
There is no activity on your device that handles ACTION_DIAL for a Tel: scheme. Try:
Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:9999999" ));
Case and whitespace are important when assembling a Uri.
Also note that even my revised Intent will not work on all devices, such as on an Android tablet that lacks a dialer.
I have this problem in my application. I want to create a folder in Emulator SD card but it didn't work and I don't know why. I tried mkdir and mkdirs.
I added WRITE_EXTERNAL_STORAGE Permission to the Manifest. I tried with MediaScannerConnection and didn't work. I've searched a lot the web and tried a lot of implementations but no change. What could be the issue?
Here is my code:
public void createDirIfNotExists() {
File folder = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/cdp");
boolean success = true;
if (!folder.exists()) {
success = folder.mkdirs();
}
if (success) {
Log.e("Folder: ", "folder created!!");
} else {
Log.e("Folder Error: ", "folder cannot be created!!");
}
}
My manifest look like this:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.aboussof.myapplication" >
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
</activity>
<activity android:name=".Test">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
And so I try to create the folder:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mProgressDialog = new ProgressDialog(Test.this);
mProgressDialog.setMessage("A message");
mProgressDialog.setIndeterminate(true);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.setCancelable(true);
// execute this when the downloader must be fired
final DownloadTask downloadTask = new DownloadTask(Test.this);
createDirIfNotExists();
downloadTask.execute("http://www.sample-videos.com/video/mp4/720/big_buck_bunny_720p_5mb.mp4");
mProgressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
downloadTask.cancel(true);
}
});
}
Replace
File folder = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/cdp");
with
File folder = new File(Environment.getExternalStorageDirectory() + "/", "cdp");
Have you solved your issue yet?
I use your method with a tiny change at
File folder = new File(Environment.getExternalStorageDirectory(), "cdp");
And the result like the following screenshot:
My AVD configuration like the following:
I have had the same issue - file.mkdirs() returns false on android emulator API 23. And all configs was set according to BNK's answer.
Try to change API to 19 - it works for me. Looks like weird emulator/android version issue.