I don't know why since I switched to kitkat my app cannot create any file in system (This method was working on android 4.1.2). My app has su permissions, mount system as RW and READ and WRITE_EXTERNAL_STORAGE permissions declared in manifest.
Logcats show me that it allows SU permissions but no errors.
The code that it is not working is this one below.
File file = new File(Environment.getRootDirectory().getPath().toString(), "/etc/init.d/script");
Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.hasta.cocoremanager"
android:versionCode="1"
android:versionName="1.7" >
<uses-sdk
android:minSdkVersion="16"
android:targetSdkVersion="19" />
<uses-permission android:name="android.permission.WRITE_SETTINGS"/>
<uses-permission android:name="android.permission.ACCESS_SUPERUSER" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme">
<activity
android:name="com.hasta.cocoremanager.Main"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
Since 4.4.2 there are new rules for IO on the device storage:
Article
To put it short: Now you can only write in your app's folder.
Ensure that the file has read/write permissions to everyone.
Runtime.getRuntime().exec(new String[] { "su", "-c", "chown 777 /etc/init.d/script" });
Now you will be able to get an instance of that file.
If the file does not exist, first run
Runtime.getRuntime().exec(new String[] { "su", "-c", "echo '#' > /etc/init.d/script" });
EDIT: Without knowing how you want to use the file instance, i'll take a stab at it
File file = null;
try
{
file = new File(Environment.getRootDirectory().getPath().toString(), "/etc/init.d/script");
}
catch (Exception e)
{
// Cannot get file so set permissions.
Runtime.getRuntime().exec(new String[] { "su", "-c", "chown 777 /etc/init.d/script" });
try
{
file = new File(Environment.getRootDirectory().getPath().toString(), "/etc/init.d/script");
}
catch (Exception e)
{
// File does not exits, so create it.
Runtime.getRuntime().exec(new String[] { "su", "-c", "echo '#' > /etc/init.d/script" });
// Now set permissions.
Runtime.getRuntime().exec(new String[] { "su", "-c", "chown 777 /etc/init.d/script" });
try
{
file = new File(Environment.getRootDirectory().getPath().toString(), "/etc/init.d/script");
}
catch (Exception e)
{
// Should never get here.
}
}
// Do stuff with your file.
You can always do all this in your app user area and then do
Runtime.getRuntime().exec(new String[] { "su", "-c", "cp " + Environment.getDataDirectory() + "/script /etc/init.d/script" });
A note on calling su, this syntax also works.
Runtime.getRuntime().exec("su -c cp " + Environment.getDataDirectory() + "/script /etc/init.d/script");
Set menifest permissions that both:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Becasuse also you required the read permission for RW and READ
Related
/**
* Downloading file in background thread
* */
#Override
protected String doInBackground(String... f_url) {
int count;
try {
String root = Environment.getExternalStorageDirectory().toString(); // "/storage/emulated/0"
System.out.println("Downloading");
URL url = new URL(f_url[0]); //http://xxx.168.2.200/tmp/bsp1.txt;
URLConnection conection = url.openConnection();
conection.connect();
// getting file length
int lenghtOfFile = conection.getContentLength();
// input stream to read file - with 8k buffer
InputStream input = new BufferedInputStream(url.openStream(), 8192);
// Output stream to write file
OutputStream output = new FileOutputStream(fileNameDaten);
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
// writing data to file
output.write(data, 0, count);
}
// flushing output
output.flush();
// closing streams
output.close();
input.close();
} catch (Exception e) {
String fel=e.getMessage();
Log.e("Error: ", e.getMessage());
}
return null;
}
/**
* After completing background task
* **/
#Override
protected void onPostExecute(String file_url) {
System.out.println("Downloaded");
}
}
doInBackground is running until "conection.connect();"
After about 3 minutes the app will continue with an exception:
"Failed to connect to /xxx.168.2.200:80"
In principle, I can access the web server's HTML pages with my mobile phone.
My question: What does the error message mean and how can I fix the error?
networkSecurityConfig : not added to manifest, how to formulate ?
app targets android 9, API 28 only partially installed
I will use the app only for local adresses
Follows manifest:enter code here
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="de.wicki.pdftextapplication">
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_INTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_INTERNAL_STORAGE" />
<uses-permission android:name="android.permission.DOWNLOAD_WITHOUT_NOTIFICATION" />
<application
android:usesCleartextTraffic="true"
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>
<activity android:name=".UploadToServer"></activity>
</application>
</manifest>
This question already has answers here:
Android permission doesn't work even if I have declared it
(11 answers)
Storage permission error in Marshmallow
(12 answers)
Closed 2 years ago.
I try to play a music with MediaPlayer.
The problem is I don't succed to acces file even if I ask for permissions in manifest
My Manifest:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.nkm.metaextract" >
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_INTERNAL_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" >
<activity android:name=".MainActivity" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
and the java code:
public class MainActivity extends AppCompatActivity {
//public class MetaExtractActivity extends Activity {
ImageView album_art;
TextView album, artist, genre;
MediaPlayer mp;
MediaMetadataRetriever metaRetriever;
byte[] art;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getInit();
File dir =Environment.getExternalStorageDirectory();
File file=new File(dir + File.separator +"Music/Wholesome.mp3");
if (file.exists()) {
genre.setText(file.toString());
Log.i("DEBUG", "Trouvé "+file.toString());
}else {genre.setText("pas trouvé");
Log.i("DEBUG", "pas trouvé");
}
mp = new MediaPlayer();
try {
mp.setDataSource("/storage/emulated/0/Music/Wholesome.mp3");
Log.i("DEBUG", "ok");
artist.setText("ok");
} catch (IOException e) {
e.printStackTrace();
Log.i("DEBUG", "Erreur "+ e);
artist.setText("pas trouvé");
}
Nota: the file exist and i can read it with store apps
I tried to change de path whit "/storage/emulated/0/Music/Wholesome.mp3" and few other way without change
Where i test if it's a file I obtain:
"I/DEBUG: Trouvé /storage/emulated/0/Music/Wholesome.mp3" but just next
"W/System.err: java.io.FileNotFoundException: /storage/emulated/0/Music/Wholesome.mp3 (Permission denied)"
and where i try to acces I obtain:
"I/DEBUG: Erreur java.io.FileNotFoundException: /storage/emulated/0/Music/Wholesome.mp3 (Permission denied)"
When app start, Android doesn't ask me for acces...and app can't acces file.
is somebody can help ?
Since Android 6.0 you have to ask for the permission in the runtime:
https://developer.android.com/training/permissions/requesting
What you can do for now, is to go to settings of the app, go to permission section, enable those permissions and restart the app. If it doesn't work, I would add runtime permission checks from the link I posted above
Thank you very much Mariusz.
I add
requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 1);
and it wors well...
I am trying to make an app that allows me to ssh and do certain commands.
Using JSch, I wrote an AsyncTask as such that takes care of the process.
The issue is that I cannot access the .pub file for RSA logins due to the error java.io.FileNotFoundException: /storage/emulated/0/MyFolder/id_rsa.pub: open failed: EACCES (Permission denied). On my Nexus 6, "MyFolder" folder exists, along with the .pub file. Permissions are the same as other files in Download.
SomeAsyncTask.java
import android.os.AsyncTask;
import android.os.Environment;
import android.util.Log;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import java.io.File;
public class SomeAsyncTask extends AsyncTask<String, String, String> {
public static final String TAG = "SomeAsyncTask";
#Override
protected String doInBackground(String... params) {
Log.d(TAG, params[0]);
this.submit(params[0]);
return null;
}
private void submit(String command) {
try {
JSch jsch = new JSch();
Session session = jsch.getSession("user", "ip", 22);
File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/MyFolder/", "id_rsa.pub");
jsch.addIdentity(file.toString());
session.connect();
} catch (Exception e) {
Log.d(TAG, e.getMessage());
}
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.whatever.whate">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<meta-data android:name="com.google.android.gms.version" android:value="#integer/google_play_services_version" />
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:theme="#style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
</manifest>
I believe I have all the permissions and the folder/file exists.
What could be causing this?
Permission error when getting file for use with JSch
Always remember when running on an Android Marshmallow device that the permissions systems way of working has changed.
http://developer.android.com/training/permissions/requesting.html
You need to make sure you are taking care of runtime permissions correctly, and if not make sure you allow all the permissions on your device from the settings application.
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.
when i run this piece of code as normal java application in main it runs fine. but when i try to use the same code in onCreate in one of the activity it says file not found exception and prints nothing in logcat. i have tried every possible way but dont know whts the cause of the problem. Also in logcat the msg is like this filenotfound exception: /D:/android/Suyesh.2DV106.Assignment3/southern_cities.txt (no such file or directory) . is it because of the leading forward slash /D:/.. but i didnt put it there and when i try to print the path it doesnt contain that / in front of D. But when i print the absoulte path it contains that /D. Whats the problem here? I have also my manifest file as below.
public class TheCityMap extends Activity{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
String strFile = Environment.getExternalStorageDirectory() +"/android/Suyesh.2DV106.Assignment3/southern_cities.txt";
BufferedReader br = new BufferedReader(new FileReader(strFile));
String strLine = null;
StringTokenizer st = null;
int lineNumber = 0, tokenNumber = 0;
while( (strLine = br.readLine()) != null){
lineNumber++;
st = new StringTokenizer(strLine, ",");
while(st.hasMoreTokens()){
tokenNumber++;
System.out.println("Line # " + lineNumber +", Token # " + tokenNumber+ ", Token : "+ st.nextToken());
}
tokenNumber = 0;
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="assignment3.demos"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="10" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
<application android:icon="#drawable/icon" android:label="#string/app_name">
<activity android:name=".MainListActivity"
android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name="TheCityMap"></activity>
<uses-library android:name="com.google.android.maps"/>
<uses-permission android:name="android.permission.INTERNET" > </uses-permission>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" > </uses-permission>
<uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION" > </uses-permission>
</application>
Android is based on linux so things like "D:" should never work.
If the file is on sd card try this:
String strFile = Environment.getExternalStorageDirectory() + "/android/Suyesh.2DV106.Assignment3/southern_cities.txt";
At the end your path should be something like:
"/mnt/sdcard/android/Suyesh.2DV106.Assignment3/southern_cities.txt"
Have you tried to use:
File file = new File(TheCityMap.class.getResource(/* name */));
BufferedReader reader = new BufferedReader(new FileReader( file ));
or:
new BufferedReader(new InputStreamReader(FlowAp.class.getResourceAsStream("" /* name */)))
if D is your external storage directory (sdcard or flash), use Enviroment.getExternalStorageDirectory()