I have seen several questions regarding SocketException when using Android, but none of them cover the BindException that I get even with the INTERNET permission specified in my manifest.
Here is part of my manifest:
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"></uses-permission>
<uses-permission android:name="android.permission.READ_OWNER_DATA"></uses-permission>
<uses-permission android:name="android.permission.READ_PHONE_STATE"></uses-permission>
<uses-permission android:name="android.permission.ACCOUNT_MANAGER"></uses-permission>
<uses-permission android:name="android.permission.AUTHENTICATE_ACCOUNTS"></uses-permission>
Here is the relevant portion of my LogCat output:
04-22 14:49:06.117: DEBUG/MyLibrary(4844): Address to bind: 192.168.1.14 port: 843
04-22 14:49:06.197: WARN/System.err(4844): java.net.BindException: Permission denied (maybe missing INTERNET permission)
04-22 14:49:06.207: WARN/System.err(4844): at org.apache.harmony.luni.platform.OSNetworkSystem.socketBindImpl(Native Method)
04-22 14:49:06.207: WARN/System.err(4844): at org.apache.harmony.luni.platform.OSNetworkSystem.bind(OSNetworkSystem.java:107)
04-22 14:49:06.217: WARN/System.err(4844): at org.apache.harmony.luni.net.PlainSocketImpl.bind(PlainSocketImpl.java:184)
04-22 14:49:06.217: WARN/System.err(4844): at java.net.ServerSocket.bind(ServerSocket.java:414)
04-22 14:49:06.227: WARN/System.err(4844): at org.apache.harmony.nio.internal.ServerSocketChannelImpl$ServerSocketAdapter.bind(ServerSocketChannelImpl.java:213)
04-22 14:49:06.227: WARN/System.err(4844): at java.net.ServerSocket.bind(ServerSocket.java:367)
04-22 14:49:06.237: WARN/System.err(4844): at org.apache.harmony.nio.internal.ServerSocketChannelImpl$ServerSocketAdapter.bind(ServerSocketChannelImpl.java:283)
04-22 14:49:06.237: WARN/System.err(4844): at mylibrary.net.PolicyConnection$PolicyServerWorker.(PolicyConnection.java:201)
I Really hope this is a simple problem and not something complicated by the fact that the binding is occurring within a worker thread on a port less than 1024.
Update
Looks as if this is a privileged port issue, anyone know how to bind to ports lower than 1024 in Android?
SelectorProvider provider = SelectorProvider.provider();
try {
ServerSocketChannel channel = provider.openServerSocketChannel();
policySocket = channel.socket();
Log.d("MyLibrary", "Address to bind: " + device.getAddress().getAddress() + " port: 843");
InetSocketAddress addr = new InetSocketAddress(InetAddress.getByName(device.getAddress().getAddress()), 843);
policySocket.bind(addr);
policySocket.setReuseAddress(true);
policySocket.setReceiveBufferSize(256);
} catch (Exception e) {
e.printStackTrace();
}
anyone know how to bind to ports lower
than 1024 in Android?
Either root your phone, modify the firmware, or don't bind to ports lower than 1024. That's a Linux thing more than an Android thing.
Try add permission android.permission.INTERNET
it worked for me
Related
I have a weird crash in Lollipopand below. I get a security Exception when trying to download a file from the server, but in devices running Marshmallow and above the app does not crash. Logcat:
Caused by: java.lang.SecurityException: need WRITE_EXTERNAL_STORAGE permission to use DESTINATION_FILE_URI: uid 10229 does not have android.permission.WRITE_EXTERNAL_STORAGE.
In App's grandle I use
targetSdkVersion 22
Will change after our first push on Google Console to target the latest sdk version, but for now this will remain to 22, so no need for run time permissions.
Furthermore, in App's Manifest we declare app's permission.
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.DOWNLOAD_WITHOUT_NOTIFICATION" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Also, the code that uses the DownloadManagerinside an AsynckTask :
try {
String dirPath = String.format("%5$s/%1$s/Resources/%2$s/%3$s/%4$s/", userID, resource.getiD(), filePackage.getiD(), language, dir.getCanonicalPath());
File makeDirs = new File(dirPath);
makeDirs.mkdirs();
} catch (Exception ex) {
ex.printStackTrace();
}
this.downloadManager = (DownloadManager) getApplicationContext().getSystemService(DOWNLOAD_SERVICE);
DownloadManager.Request request = new DownloadManager.Request(url);
request.setDestinationInExternalFilesDir(getApplicationContext(), null, filePath);
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_HIDDEN);
request.setVisibleInDownloadsUi(false);
downloadID = downloadManager.enqueue(request);
Again, this crash is observed only in Galaxy A5 with OS version 5.0.2, in an emulator running Samsung Galaxy S6 with Lollipop and in emulator running Kitkat 4.4.4 HTC One.
The full stack trace :
java.lang.RuntimeException: Unable to start activity ComponentInfo{...players.PDFViewer}: java.lang.SecurityException: need WRITE_EXTERNAL_STORAGE permission to use DESTINATION_FILE_URI: uid 10229 does not have android.permission.WRITE_EXTERNAL_STORAGE.
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2808)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2873)
at android.app.ActivityThread.access$900(ActivityThread.java:181)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1482)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:6145)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1399)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)
Caused by: java.lang.SecurityException: need WRITE_EXTERNAL_STORAGE permission to use DESTINATION_FILE_URI: uid 10229 does not have android.permission.WRITE_EXTERNAL_STORAGE.
at android.os.Parcel.readException(Parcel.java:1540)
at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:185)
at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:137)
at android.content.ContentProviderProxy.insert(ContentProviderNative.java:475)
at android.content.ContentResolver.insert(ContentResolver.java:1260)
at android.app.DownloadManager.enqueue(DownloadManager.java:1336)
at de.imsystems.crmmobile.players.PDFViewer.onCreate(PDFViewer.java:104)
at android.app.Activity.performCreate(Activity.java:6374)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2752)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2873)
at android.app.ActivityThread.access$900(ActivityThread.java:181)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1482)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:6145)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1399)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)
If you have any thoughts, please share them, thanks in advance.
Eventually this post WRITE_EXTERNAL_STORAGE not working on lollipop even though it's set in the manifest helped me. What I did was to alter permissions in AndroidManifest.xml file like this:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" android:maxSdkVersion="26" tools:replace="android:maxSdkVersion"/>
This way the app doesn't crashes!
I want to create a packet and send to over network(2nd layer of network) in android application I use android studio.I download jnetpcap-1.3.0 file , this file include some file such as jnetPcap.jar , I add this jar file to my android project,Is it right or not?
at this step I can call some classes in the jar file(jnetpcap.jar) but when I want run this android application I have an error and I don't know how I can solve this problem.
I asign some permission to android appliaton, such as permission is :
<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" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE"/>
<uses-permission zndroid:name="android.permission.CHANGE_WIFI_MULTICAST_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
My code is:
int size=100;
Ethernet wEth;
byte[] sourceMac={};
byte[] destMac={};
Ip4 wIp4;
byte[] bytes={};
byte[] dIP={};
byte[] sIP={};
try {
Process p = Runtime.getRuntime().exec("su");
JPacket wPacket = new JMemoryPacket(size);
wPacket.order(ByteOrder.BIG_ENDIAN);
wPacket.setUShort(12, 0x0800);
wPacket.scan(JProtocol.ETHERNET_ID);
wEth = wPacket.getHeader(new Ethernet());
wEth.source(sourceMac);
wEth.destination(destMac);
wEth.checksum(wEth.calculateChecksum());
int headersize = 14;
wPacket.setUByte(14, 0x40 | 0x05);
wPacket.scan(JProtocol.ETHERNET_ID);
wIp4 = wPacket.getHeader(new Ip4());
wIp4.length(500 - wEth.size());
wIp4.source(dIP);
wIp4.destination(sIP);
wIp4.ttl(32);
wIp4.flags(0);
wIp4.offset(0);
wIp4.checksum(wIp4.calculateChecksum());
headersize += 20;
}catch (Exception ex)
{
ex.printStackTrace();
}
and I have this error that shows on logcat on androis studio :
1. 11-15 14:03:42.084 2996-2996/com.example.saeed.monoq E/Trace: error
opening trace file: No such file or directory (2) 11-15 14:03:42.814
2996-2996/com.example.saeed.monoq E/dalvikvm: Could not find class
'android.util.ArrayMap', referenced from method
com.android.tools.fd.runtime.MonkeyPatcher.monkeyPatchExistingResources
11-15 14:03:42.844 2996-2996/com.example.saeed.monoq E/dalvikvm:
Could not find class 'android.util.ArrayMap', referenced from method
com.android.tools.fd.runtime.MonkeyPatcher.pruneResourceCache 11-15
14:03:44.884 2996-2996/com.example.saeed.monoq E/AndroidRuntime:
FATAL EXCEPTION: main
java.lang.ExceptionInInitializerError
at
com.example.saeed.monoq.MainActivity.onCreate(MainActivity.java:69)
at android.app.Activity.performCreate(Activity.java:5008)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:107 at
how can I solve this problem?
Check your Gradle files to see if you have included all required dependencies. For packet manipulation, you may want to check on mvn repo details.
java.lang.RuntimeException: setAudioSource failed.
11-07 20:30:16.294 12438-12438/com.main.sample W/System.err: at android.media.MediaRecorder.setAudioSource(Native Method)
11-07 20:30:16.294 12438-12438/com.main.sample W/System.err: at com.main.sample.Activity.EventsaddActivity.initializeMediaRecord
In the first step you need to add these permissions:
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
set target sdk to 22 or use request permission and set target to 23 or above.
and check your path again
MediaRecorder.setAudioSource(new File("YOUR_PATH"));
I'm having the following error on a few of my users:
Caused by: java.lang.SecurityException: Permission denied (missing INTERNET permission?)
at java.net.InetAddress.lookupHostByName(InetAddress.java:418)
at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
at java.net.InetAddress.getAllByName(InetAddress.java:214)
at com.android.okhttp.internal.Dns$1.getAllByName(Dns.java:28)
at com.android.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:216)
at com.android.okhttp.internal.http.RouteSelector.next(RouteSelector.java:122)
at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:292)
at com.android.okhttp.internal.http.HttpEngine.sendSocketRequest(HttpEngine.java:255)
at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:206)
at com.android.okhttp.internal.http.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:345)
at com.android.okhttp.internal.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:89)
at com.android.okhttp.internal.http.HttpURLConnectionImpl.getOutputStream(HttpURLConnectionImpl.java:197)
at com.android.okhttp.internal.http.HttpsURLConnectionImpl.getOutputStream(HttpsURLConnectionImpl.java:254)
at [my communication HttpUrlConnection request]
... 12 more
Caused by: libcore.io.GaiException: getaddrinfo failed: EAI_NODATA (No address associated with hostname)
at libcore.io.Posix.getaddrinfo(Native Method)
at libcore.io.ForwardingOs.getaddrinfo(ForwardingOs.java:61)
at java.net.InetAddress.lookupHostByName(InetAddress.java:405)
... 25 more
Caused by: libcore.io.ErrnoException: getaddrinfo failed: EACCES (Permission denied)
... 28 more
The app requires internet to do it's most basic function, I don't think a user have removed the permission using root or something like that.
Additionally, this error was sent to me with my own error reporting tool. I have made the upload with the registered error and at that moment the permission was available.
There is no restriction on device model of android version that has the error.
Example of a part of the manifest:
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
[...]
Any clue is appreciated,
Thanks in advance.
This will help you.
Write the following in your onCreate method
int PERMISSION_ALL = 1;
String[] PERMISSIONS = {Manifest.permission.READ_CONTACTS, Manifest.permission.WRITE_CONTACTS, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_SMS, Manifest.permission.CAMERA};
if (!hasPermissions(this, PERMISSIONS)) {
ActivityCompat.requestPermissions(this, PERMISSIONS, PERMISSION_ALL);
}
And get this method
public static boolean hasPermissions(Context context, String... permissions)
{
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && context != null && permissions != null)
{
for (String permission : permissions)
{
if (ActivityCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED)
{
return false;
}
}
}
return true;
}
The application will ask for only those permission which the application needs, that too only once. If it works upvote and do let me know. It worked for me
HttpUrlConnection request also requires android.permission.ACCESS_NETWORK_STATE. Do you also have this permission listed in the manifest?
Please post your manifest file so we can see that android.permission.ACCESS_NETWORK_STATE, and android.permission.INTERNET are both listed without any spelling, capitalization, syntax errors.
The issue can also happen if a user has rooted their Android device and tinkered with the permissions. How do you know the user has not rooted the device? Can you reproduce the problem on any of your own devices?
See more detail on this issue here: SecurityException: Permission denied (missing INTERNET permission?)
I would like to give the user the choice to copy files onto the Android device data directory as well as the external area.
Can you tell me what I need to add to the manifest that will allow my app to copy the files to the internal area?
I was planning on storing the files in /data/data/your.app.package.name/myFiles. In the code, File.DirInternal translates to that location.
If I use File.DirRootExternal, it goes to /mnt/sdcard which does not crash the app.
That's why I thought the manifest was causing the issue.
It crashes on this line if I use File.DirInternal:
mpTheMediaPlayer.Load(File.DirInternal, "114.mp3")
This is the code that's crashing:
' Http sub routines.
'-------------------
Sub JobDone(Job As String)
Select Job
Case "Job1"
If HttpUtils.IsSuccess(mp3Url) Then
Dim blnFolderMade As Boolean
mp3 = HttpUtils.GetInputStream(mp3Url)
timer1.Enabled = True
Dim out As OutputStream
out = File.OpenOutput(File.DirInternal,"114.mp3",False)
File.Copy2(mp3, out)
out.Close
ProgressBarDownloading.Visible = False
ToggleButtonPlayPause.Checked = True
ToggleButtonPlayPause.Enabled = True
blnCurrentPauseCheckedState = True
blnCurrentPauseEnabledState = True
mpTheMediaPlayer.Release
mpTheMediaPlayer.Initialize2("")
mpTheMediaPlayer.Load(File.DirInternal, "114.mp3")
mpTheMediaPlayer.Play
End If
End Select
End Sub
Here is the error from the logs:
Starting Job: Job1
** Service (httputilsservice) Create **
** Service (httputilsservice) Start **
main_jobdone (java line: 518)
java.io.IOException: Prepare failed.: status=0x1
at android.media.MediaPlayer.prepare(Native Method)
at anywheresoftware.b4a.objects.MediaPlayerWrapper.Load(MediaPlayerWrapper.java:79)
at quran.repeater.main._jobdone(main.java:518)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:507)
at anywheresoftware.b4a.BA.raiseEvent2(BA.java:113)
at anywheresoftware.b4a.BA.raiseEvent(BA.java:97)
at anywheresoftware.b4a.keywords.Common.CallSub4(Common.java:772)
at anywheresoftware.b4a.keywords.Common.CallSub2(Common.java:759)
at quran.repeater.httputilsservice._processnexttask(httputilsservice.java:180)
at quran.repeater.httputilsservice._response_streamfinish(httputilsservice.java:244)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:507)
at anywheresoftware.b4a.BA.raiseEvent2(BA.java:113)
at anywheresoftware.b4a.BA$1.run(BA.java:218)
at android.os.Handler.handleCallback(Handler.java:587)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:123)
at android.app.ActivityThread.main(ActivityThread.java:3647)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:507)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
at dalvik.system.NativeStart.main(Native Method)
java.io.IOException: Prepare failed.: status=0x1
Take a look at Android's Data Storage doc for details on saving to internal storage.
If you meant:
/data/data/your.app.package.name/myFiles
Then you don't need extra permissions. That's just regular writing to internal storage
If you meant external storage (which it sure doesn't look like) then you need
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
If you truly meant
/data/myApp/myFiles
Then the answer is that you can't without being rooted. You don't have permissions to write to the /data folder.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />