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!
Related
I have implemented an FTP Client on my app and trying to connect to an Existing FTP Server but don't know why it throws an error.
I am using this library in the build.gradle
implementationfiles('libs/apache-commons-net.jar')
Here is my code for FTP Client connection part
private void configFTPClient(String user, String password)
{
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
FTPClient ftpClient = new FTPClient();
//final String serverFinal=server;
BufferedInputStream buffIn = null;
String fileNameDirectory="BPL_CARDIART";
File file =new File(android.os.Environment.getExternalStorageDirectory().getAbsolutePath(),fileNameDirectory);
String firstRemoteFile =file+"/"+ "Cardiart__LPP1_ECG.pdf";
try {
buffIn = new BufferedInputStream(new FileInputStream(firstRemoteFile));
ftpClient.connect(server,port);
ftpClient.login(user, password);
// ftpClient.changeWorkingDirectory(serverRoad);
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
ftpClient.enterLocalPassiveMode();
ftpClient.storeFile("test.txt", buffIn);
buffIn.close();
ftpClient.logout();
ftpClient.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
}
And my maifest.xml file is code
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="cardiact.bpl.pkg.com.bplcardiactconnect"
>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"
/>
<uses-permission android:name="android.permission.MANAGE_DOCUMENTS"/>
<uses-permission android:name="android.permission.CAMERA"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-feature android:name="android.hardware.usb.host" />
<uses-feature android:name="android.hardware.camera2" android:required="false"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<application
android:allowBackup="false"
android:icon="#mipmap/ic_launcher"
android:fullBackupContent="false"
android:label="#string/app_name"
android:hardwareAccelerated="true"
android:name="application.BaseApplicationClass"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity
android:name=".SplashScreenActivity"
android:label="#string/app_name"
android:theme="#style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".BaseLoginActivityClass"
android:launchMode="singleInstance"
android:configChanges="orientation|keyboardHidden|screenSize"
/>
<meta-data
android:name="preloaded_fonts"
android:resource="#array/preloaded_fonts" />
</application>
</manifest>
As I already checked, connection with my wifi and internet on my phones, its working fine, but still it throws an error
java.net.UnknownHostException: Unable to resolve host "ftp://14.141.84.241/": No address associated with hostname
2018-10-15 11:58:40.669 2407-2407/cardiact.bpl.com.bplcardiactconnect W/System.err: at java.net.Inet6AddressImpl.lookupHostByName(Inet6AddressImpl.java:141)
2018-10-15 11:58:40.669 2407-2407/cardiact.bpl.com.bplcardiactconnect W/System.err: at java.net.Inet6AddressImpl.lookupAllHostAddr(Inet6AddressImpl.java:90)
2018-10-15 11:58:40.670 2407-2407/cardiact.bpl.com.bplcardiactconnect W/System.err: at java.net.InetAddress.getAllByName(InetAddress.java:787)
2018-10-15 11:58:40.670 2407-2407/cardiact.bpl.com.bplcardiactconnect W/System.err: at java.net.Socket.<init>(Socket.java:217)
2018-10-15 11:58:40.670 2407-2407/cardiact.bpl.com.bplcardiactconnect W/System.err: at org.apache.commons.net.DefaultSocketFactory.createSocket(DefaultSocketFactory.java:53)
2018-10-15 11:58:40.670 2407-2407/cardiact.bpl.com.bplcardiactconnect W/System.err: at org.apache.commons.net.SocketClient.connect(SocketClient.java:162)
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);
}
}
});
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
Kindly help me in this problem.. i am working in the hybrid android mobile application.. it works correctly but when i changed the orientation the application gets restarted.... both in portrait and landscape...
This is my manifest file:
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<supports-screens
android:largeScreens="true"
android:normalScreens="true"
android:smallScreens="true"
android:xlargeScreens="true"
android:resizeable="true"
android:anyDensity="true"
/>
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.RECEIVE_SMS" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.RECORD_VIDEO"/>
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.WRITE_CONTACTS" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.BROADCAST_STICKY" />
<application
android:allowBackup="true"
android:icon="#drawable/icon_dropin"
android:label="#string/app_name"
android:theme="#style/AppTheme">
<activity
android:name="com.cogzidel.dropinn.MainActivity"
android:configChanges="orientation|keyboard|keyboardHidden|screenSize"
android:label="#string/app_name"
android:screenOrientation="sensor">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
This is my mainActivity:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.setIntegerProperty("splashscreen",R.drawable.loading_img);
super.init();
if(android.os.Build.VERSION.SDK_INT > android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1) {
fixJellyBeanIssues();
}
super.loadUrl("file:///android_asset/www/index.html",8000);
}
public void onConfigurationChanged(Configuration newConfig)
{
super.onConfigurationChanged(newConfig);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_FULL_SENSOR);
}
#TargetApi(16)
protected void fixJellyBeanIssues() {
System.out.println(super.appView.toString());
try {
super.appView.getSettings().setAllowUniversalAccessFromFileURLs(true);
} catch(NullPointerException e) {
System.out.println(e.toString());
}
}
// catch an error and if try again 1x or quit
#Override
public void onReceivedError( int errorCode, String description, String failingUrl)
{
if(retryCount < 3) {
retryCount++;
System.out.println("Connection failed, trying again. Retry Count: "+retryCount);
super.loadUrl("file:///android_asset/www/listspace.html");
} else {
System.out.println("Sorry, it failed three times so I give up.");
super.loadUrl("file:///android_asset/www/fail.html");
}
return;
}
}
If don't want your application to restart you have to declare that explicidly in the android manifest like this
<activity android:name=".MyActivity"
android:configChanges="orientation"
android:label="#string/app_name">
However this is not recommended and considered as last resort.
Here you can read more how you should handle configuration changes
http://developer.android.com/guide/topics/resources/runtime-changes.html
long uuidHigh = new BigInteger("11bc4f7154ac9edb", 16).longValue();
long uuidLow = new BigInteger("167bf05f9436bc0a", 16).longValue();
UUID uuid = new UUID(uuidHigh, uuidLow);
BluetoothSocket socket = null;
BluetoothAdapter blueAdapter = null;
blueAdapter = BluetoothAdapter.getDefaultAdapter();
BluetoothDevice device = blueAdapter.getRemoteDevice("00:07:AB:6A:96:7D");
try {
socket = device.createRfcommSocketToServiceRecord(uuid); // CRASH!
} catch (IOException e) { e.printStackTrace(); }
Result:
E/AndroidRuntime(14079): java.lang.IllegalStateException: Could not execute method of the activity
Statements just before the "socket =" statement in the same method execute fine. Getting the device seems to work fine with getName() working on it.
The physical device it runs on has API 8.
The bluetooth dev guide cryptically says:
// MY_UUID is the app's UUID string, also used by the server code
tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
But createRfcommSocketToServiceRecord() cannot take a String, it must take a UUID.
Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="intrax.demo.explore"
android:versionCode="1" android:versionName="1.0" >
<uses-sdk android:minSdkVersion="8" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.BLUETOOTH" />
<application android:icon="#drawable/ic_launcher" android:label="#string/app_name" >
<activity
android:name=".BluetoothAct" 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>
</manifest>