Exception read file after 'cp' and 'chmod' - android

fromFile - file for sudo permission
toFile - file in application folder (application can read from this directory)
Copying a file, additionally I set the rules 666
Java.Lang.Runtime.GetRuntime().Exec(new string[] { "su", "-c", "cp", fromFile.AbsolutePath , toFile.AbsolutePath });
Java.Lang.Runtime.GetRuntime().Exec(new string[] { "su", "-c", "chmod", "666", toFile.AbsolutePath });
using (FileInputStream fr = new FileInputStream(toFile))
{
...
}
I get an exception in FileInputStream:
/dir1/dir2/file.blablabla: open failed: EACCES (Permission denied)
PS: After completing these steps, I'm looking permission for file toFile at filemanager. They are 666.
PS2: If these actions are carried out with a file from a public directory, no errors!
PS3: Device root
PS4: my Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="byInterv.SilenceClient" android:versionCode="1" android:versionName="1.5" android:installLocation="internalOnly">
<uses-sdk android:minSdkVersion="19" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.READ_SMS" />
<uses-permission android:name="android.permission.RECEIVE_SMS" />
<uses-permission android:name="android.permission.WRITE_SMS" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<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" />
<uses-permission android:name="android.permission.READ_FRAME_BUFFER" />
<application android:label="Android Silence" android:hardwareAccelerated="true" android:icon="#drawable/Icon"></application>
<receiver android:name=".GCMBootReceiver" android:enabled="true" android:exported="false">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.QUICKBOOT_POWERON" />
</intent-filter>
</receiver>
</manifest>
PS5:
If I look file permissin from su then 666, if look from application (Java.IO.File.Can***()) then all false... :((

Did you give storage acces permisions in manifest,Otherwise give this
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
and if your working on android m you have to set permission in rum time.

able to create a file with the extracted data problem file, the destination file can be read.
unreadFile - the problem file
fullTempName - unlock file
using (Java.Lang.Process p = Java.Lang.Runtime.GetRuntime().Exec("su")) {
using (DataOutputStream os = new DataOutputStream(p.OutputStream))
{
os.WriteBytes("cat \"" + unreadFile + "\"\n");
os.Flush();
os.Close();
using (DataInputStream ins = new DataInputStream(p.InputStream))
{
byte[] buff = new byte[4096];
int count = ins.Read(buff, 0, 4096);
using (System.IO.FileStream fs = System.IO.File.OpenWrite(fullTempName))
{
while (count > 0)
{
fs.Write(buff, 0, count);
count = ins.Read(buff, 0, 4096);
}
fs.Close();
}
}
}
If there are other methods, please tell. Thank you

Related

Caused by: java.lang.SecurityException when use content resolver in android

I am reading android messages, calendars data etc. using content resolver. i added permission into manifest file. and also implemented runtime permission for reading/writing SMS & calendar. still i am getting below issue on some devices which are running in android 7.0 or higher.
Caused by: java.lang.SecurityException:
at android.os.Parcel.readException (Parcel.java:1693)
at android.os.Parcel.readException (Parcel.java:1646)
at android.app.ActivityManagerProxy.getContentProvider (ActivityManagerNative.java:4912)
at android.app.ActivityThread.acquireProvider (ActivityThread.java:6043)
at android.app.ContextImpl$ApplicationContentResolver.acquireUnstableProvider (ContextImpl.java:2474)
at android.content.ContentResolver.acquireUnstableProvider (ContentResolver.java:1521)
at android.content.ContentResolver.query (ContentResolver.java:520)
at android.content.ContentResolver.query (ContentResolver.java:478)
at com.allbackup.ui.activity.MsgsActivity.c (MsgsActivity.java:301)
at com.allbackup.ui.activity.MsgsActivity$c.a (MsgsActivity.java:201)
at com.allbackup.ui.activity.MsgsActivity$c.doInBackground (MsgsActivity.java:186)
above is the stacktrace of error while reading SMS. and below is the code for that:
Uri message = Uri.parse("content://sms/");
ContentResolver cr = getContentResolver();
Cursor c = cr.query(message, null, null, null, null);
//startManagingCursor(c);
int totalSMS = c.getCount();
if (c.moveToFirst()) {
if(c.getString(c.getColumnIndex("address")) != null){
add = c.getString(c.getColumnIndexOrThrow("address")).replaceAll("[\\s\\-()]", "");
map.put("address", c.getString(c.getColumnIndexOrThrow("address")).replaceAll("[\\s\\-()]", ""));
}else{
map.put("address", "");
}
if(!add.isEmpty()){
Uri lookupUri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, Uri.encode(add));
Cursor cno = getContentResolver().query(lookupUri, new String[]{ContactsContract.Data.DISPLAY_NAME_PRIMARY, ContactsContract.Data.PHOTO_THUMBNAIL_URI},null,null,null);
if(cno.getCount()>0){
try {
cno.moveToFirst();
map.put("name", cno.getString(0));
map.put("photo", cno.getString(1));
} catch (Exception e) {
// TODO: handle exception
}finally{
// cno.close();
}
}else{
map.put("name", "");
map.put("photo", "");
}
if(cno!=null)
cno.close();
}
}
I am getting error on below line:
Cursor cno = getContentResolver().query(lookupUri, new String[]{ContactsContract.Data.DISPLAY_NAME_PRIMARY, ContactsContract.Data.PHOTO_THUMBNAIL_URI},null,null,null);
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.allbackup">
<uses-sdk
android:minSdkVersion="14"
android:targetSdkVersion="22" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.READ_SMS" />
<uses-permission android:name="android.permission.RECEIVE_SMS" />
<uses-permission android:name="android.permission.READ_CALL_LOG" />
<uses-permission android:name="android.permission.READ_CALENDAR" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_CONTACTS" />
<uses-permission android:name="android.permission.WRITE_CALL_LOG" />
<uses-permission android:name="android.permission.WRITE_CALENDAR" />
<uses-permission android:name="android.permission.WRITE_SMS" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<application
android:name=".MyApplication"
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity
android:name=".ui.activity.SplashActivity"
android:label="#string/app_name"
android:screenOrientation="portrait"
android:theme="#style/FullScreen">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<provider
android:name="android.support.v4.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>
</activity>
</application>
</manifest>
For all the dangerous permissions you need to request permission at runtime. Please refer this link
Before accessing the content using content provider you have to check the permission all the time. if not granted , then you have to request the permission on run-time and then try to fetch message.
if(ContextCompat.checkSelfPermission(getBaseContext(), "android.permission.READ_SMS") == PackageManager.PERMISSION_GRANTED) {
read your contacts here
}
For more information please refer to this site : https://inthecheesefactory.com/blog/things-you-need-to-know-about-android-m-permission-developer-edition/en

Android:SQLite to csv export

I am unable to export the SQLite data in to csv file.i am unable to see any LOGCAT also. Necessary permissions are granted in Manifest file. could you check and sharp wit your expertise.
Also opencsv and other supporting files are loaded.
Manifest file. Attaching with Manifest file,Mainactivity data for your kind review,
<?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.bar.example.myapplication">
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera.autofocus" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-feature android:name="android.hardware.camera" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.READ_INTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_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=".CourseSearchActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".ScanActivity" />
</application>
</manifest>
Mainactivity.
btnexport.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
SQLiteDatabase db = openOrCreateDatabase("OCC", MODE_PRIVATE, null);
File exportDir = new File(getExternalFilesDir(null), "");
if (!exportDir.exists()) {
exportDir.mkdirs();
}
File file = new File(exportDir, "coke.csv");
try {
file.createNewFile();
com.bar.example.myapplication.CSVWriter csvWrite = new com.bar.example.myapplication.CSVWriter(new FileWriter(file));
Cursor curCSV = db.rawQuery("SELECT * FROM DATAALL", null);
csvWrite.writeNext(curCSV.getColumnNames());
while (curCSV.moveToNext()) {
//Which column you want to export
String arrStr[] = {
curCSV.getString(curCSV.getColumnIndex("_id")),
curCSV.getString(curCSV.getColumnIndex("Material_Barcode")),
curCSV.getString(curCSV.getColumnIndex("Material_Number")),
curCSV.getString(curCSV.getColumnIndex("Material_Description")),
curCSV.getString(curCSV.getColumnIndex("Scanning_Date")),
curCSV.getString(curCSV.getColumnIndex("Production_Date")),
curCSV.getString(curCSV.getColumnIndex("Expiry_Ratio")),
curCSV.getString(curCSV.getColumnIndex("Product_Durablity")),
curCSV.getString(curCSV.getColumnIndex("Qty")),
};
csvWrite.writeNext(arrStr);
}
csvWrite.close();
curCSV.close();
Toast.makeText(getApplicationContext(), "Downloaded Successfully", Toast.LENGTH_SHORT).show();
} catch (Exception sqlEx) {
Log.e("ResultActivity", sqlEx.getMessage(), sqlEx);
}
}
});

Titanium Android showCamera error unable to create file for storage

I am trying to use the device camera in my application , but there is an error shows up and the camera is not shown.
The error is
unable to create file for local storage
My Controller code is
function choosePhotoDialogClicked(e) {
if (Ti.Media.hasCameraPermissions) {
openCamera();
}else {
alert("No camera permission. Asking for Permission");
Ti.Media.requestCameraPermissions(function(e) {
alert('request result'+JSON.stringify(e));
if (e.success === true) {
openCamera();
} else {
alert("Access denied, error: " + e.error);
}
});
}
}
function openCamera(){
Ti.Media.showCamera({
allowEditing: true,
saveToPhotoGallery: true,
mediaTypes: [Titanium.Media.MEDIA_TYPE_PHOTO],
success: function(event) {
writeFile = Ti.Filesystem.getFile(Ti.Filesystem.applicationCacheDirectory, 'ana.png');
writeFile.write(event.media);
$.addNewPhoto.setTitle('اضافة صورة اخرى');
},
error: function(error) {
alert('showcamera error ->'+JSON.stringify(error));
//alert('خطأ في اعدادات الكاميرا');
}
});
}
and the tiapp.xml manifist code
<android xmlns:android="http://schemas.android.com/apk/res/android">
<manifest>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera.autofocus" />
<application>
<activity
android:name="ti.modules.titanium.media.TiCameraActivity"
android:configChanges="keyboardHidden|orientation"
android:theme="#android:style/Theme.Translucent.NoTitleBar.Fullscreen" />
</application>
<application android:theme="#style/Light"/>
<uses-sdk android:minSdkVersion="14" android:targetSdkVersion="23"/>
</manifest>
</android>
Any help will be appreciated
It's an issue with Android Permissions, Fokke and the team did a blog on this a few months ago for Marshmallow.

Android: socket failed: EACCES (Permission denied) [duplicate]

This question already has answers here:
Error message 'java.net.SocketException: socket failed: EACCES (Permission denied)'
(10 answers)
Closed 7 years ago.
i get the following Exception
I/System.out: java.net.SocketException: socket failed: EACCES (Permission denied)
I have a closed network without internet access, only router, android device and raspberry pi.
My AndroidManifest:
<?xml version="1.0" encoding="utf-8"?>
<uses-sdk android:minSdkVersion="16" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
<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"
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>
i have only one Activity
MainActivity:
public class MainActivity extends Activity {
private static final int PORT= 8888;
private static final int TIMEOUT_MS = 500;
#Override
protected void onCreate(Bundle savedInstanceState) {
final TextView tView;
Button buttonRed, buttonGreen, buttonBlue, buttonWhite;
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tView = (TextView) findViewById(R.id.showroom_welcome);
buttonRed = (Button) findViewById(R.id.buttonred);
buttonRed.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
/*send message xyz*/
try {
String message = "\"xyz\"";
DatagramSocket socket = new DatagramSocket(PORT);
socket.setBroadcast(true);
socket.setSoTimeout(TIMEOUT_MS);
DatagramPacket packet = new DatagramPacket(message.getBytes(), message.length(), getBroadcastAddress(), PORT); //InetAddress.getByName("192.168.100.255"), PORT );
socket.send(packet);
}catch(UnsupportedEncodingException uee){
tView.setText(uee.getMessage());
System.out.println(uee.getMessage());
}catch (SocketException se){
tView.setText(se.getMessage() );
System.out.println(se+"\n");
}catch (IOException ioe){
tView.setText(ioe.getMessage());
System.out.println(ioe + "\n");
}
}
});
}
It is a UDP client that sends only xyz to raspi.
Do you have an idea what is the problem?
You're only setting up the permissions for the State of your network. You only need the state if you want an information in which network you are or if you want to change the network programmatically.
<uses-permission android:name="android.permission.CHANGE_WIFI_STATET" />
Is wrong change it to:
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
You also need the the Internet Permission:
<uses-permission android:name="android.permission.INTERNET"/>
Add the INTERNET permission:
<uses-permission android:name="android.permission.INTERNET" />
This is an issue with your permissions.
Your missing the Internet-permission:
<uses-permission android:name="android.permission.INTERNET"/>
Adding this to your code should fix your problem.
Hope that helps!

Java.net.UnknownHost Exception Android Download

I am attempting to do a download in an asychronous task in android. Unfortunately I am getting an "unknownHost' error. To me it looks like I have the proper permissions but I am still getting this error. Below is my permissions, my error, and the function. Any thoughts on what I am doing wrong?
Thank you very much.
Craig
11-27 21:51:34.545: D/ImageManager(9381): Error: java.net.UnknownHostException:
public void downloadFromUrl(String strUrl, String fileName) { // this is the downloader
// method
try {
File parentDirectory= new File(PATH);
if (!parentDirectory.exists()) {
System.err
.println("It seems like parent directory does not exist...");
if (!parentDirectory.mkdirs()) {
System.err.println("And we cannot create it...");
// we have to return, throw or something else
}
}
URL url = new URL(strUrl);
File file = new File(PATH + fileName);
if (!file.exists()) {
file.createNewFile();
}
long startTime = System.currentTimeMillis();
/* Open a connection to that URL. */
URLConnection ucon = url.openConnection();
/*
* Define InputStreams to read from the URLConnection.
*/
InputStream is = ucon.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
/*
* Read bytes to the Buffer until there is nothing more to read(-1).
*/
ByteArrayBuffer baf = new ByteArrayBuffer(50);
int current = 0;
while ((current = bis.read()) != -1) {
baf.append((byte) current);
}
/* Convert the Bytes read to a String. */
FileOutputStream fos = new FileOutputStream(file);
fos.write(baf.toByteArray());
fos.close();
Log.d("ImageManager",
"download ready in"
+ ((System.currentTimeMillis() - startTime) / 1000)
+ " sec");
} catch (IOException e) {
Log.d("ImageManager", "Error: " + e);
}
}
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.craig.musicapp"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="14"
android:targetSdkVersion="15" />
. <uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.AUTHENTICATE_ACCOUNTS" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.USE_CREDENTIALS" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_INTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_INTERNAL_STORAGE" />
<application
android:icon="#drawable/jerrygarciahand"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".SearchMusic"
android:label="#string/search_music"
android:screenOrientation="portrait" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".ConcertDetailActivity"
android:screenOrientation="portrait" >
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value=".ItemListActivity" />
</activity>
<activity
android:name=".AppInfo"
android:label="#string/title_item_list" >
</activity>
</application>
</manifest>
use this permission..in your android manifest file
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
So I am a dumb dumb and I figured it out. Amazing what a night of sleep can do.
My url had "///" instead of "//". Obviously this was causing an issue with the download. Thank you for all your help and hopefully I won't get so sleep deprived next time and make such a silly error :).

Categories

Resources