Android http connection refused - java

I created an Android test program with service and activity.
In activity I start sticky service. Service make http requests every 10 seconds.
If I not exit from activity, all works fine. If I exit, service works sometime, then killed by system and restarted. After restart sometimes http requests works, sometimes gives an error message:
09-28 14:55:18.053 31161-31184/home.xmpp W/System.err: java.net.ConnectException: failed to connect to www.ya.ru/87.250.250.242 (port 80) after 15000ms: isConnected failed: ECONNREFUSED (Connection refused)
09-28 14:55:18.053 31161-31184/home.xmpp W/System.err: at libcore.io.IoBridge.isConnected(IoBridge.java:238)
09-28 14:55:18.053 31161-31184/home.xmpp W/System.err: at libcore.io.IoBridge.connectErrno(IoBridge.java:171)
09-28 14:55:18.053 31161-31184/home.xmpp W/System.err: at libcore.io.IoBridge.connect(IoBridge.java:122)
09-28 14:55:18.053 31161-31184/home.xmpp W/System.err: at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:183)
09-28 14:55:18.053 31161-31184/home.xmpp W/System.err: at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:456)
09-28 14:55:18.053 31161-31184/home.xmpp W/System.err: at java.net.Socket.connect(Socket.java:882)
09-28 14:55:18.053 31161-31184/home.xmpp W/System.err: at com.android.okhttp.internal.Platform.connectSocket(Platform.java:174)
09-28 14:55:18.053 31161-31184/home.xmpp W/System.err: at com.android.okhttp.Connection.connect(Connection.java:152)
09-28 14:55:18.053 31161-31184/home.xmpp W/System.err: at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:276)
09-28 14:55:18.053 31161-31184/home.xmpp W/System.err: at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:211)
09-28 14:55:18.053 31161-31184/home.xmpp W/System.err: at com.android.okhttp.internal.http.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:382)
09-28 14:55:18.053 31161-31184/home.xmpp W/System.err: at com.android.okhttp.internal.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:106)
09-28 14:55:18.053 31161-31184/home.xmpp W/System.err: at com.android.okhttp.internal.http.HttpURLConnectionImpl.getOutputStream(HttpURLConnectionImpl.java:217)
09-28 14:55:18.053 31161-31184/home.xmpp W/System.err: at home.xmpp.MyService.sendPostRequest(MyService.java:160)
09-28 14:55:18.053 31161-31184/home.xmpp W/System.err: at home.xmpp.MyService$MyTask.doInBackground(MyService.java:128)
09-28 14:55:18.053 31161-31184/home.xmpp W/System.err: at home.xmpp.MyService$MyTask.doInBackground(MyService.java:109)
09-28 14:55:18.053 31161-31184/home.xmpp W/System.err: at android.os.AsyncTask$2.call(AsyncTask.java:292)
09-28 14:55:18.053 31161-31184/home.xmpp W/System.err: at java.util.concurrent.FutureTask.run(FutureTask.java:237)
09-28 14:55:18.053 31161-31184/home.xmpp W/System.err: at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
09-28 14:55:18.053 31161-31184/home.xmpp W/System.err: at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
09-28 14:55:18.053 31161-31184/home.xmpp W/System.err: at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
09-28 14:55:18.053 31161-31184/home.xmpp W/System.err: at java.lang.Thread.run(Thread.java:818)
09-28 14:55:18.053 31161-31184/home.xmpp W/System.err: Caused by: android.system.ErrnoException: isConnected failed: ECONNREFUSED (Connection refused)
09-28 14:55:18.053 31161-31184/home.xmpp W/System.err: at libcore.io.IoBridge.isConnected(IoBridge.java:223)
09-28 14:55:18.053 31161-31184/home.xmpp W/System.err: ... 21 more
After the appearance of this error, the following requests will also fail.
I tried to start service in another process, tried to start each http request in new IntentService, tried to restart service after this error, but no results.
If an error has occurred, then other subsequent requests will also give an error. Only application restart helps.
Has anyone encountered such problem? How to make a stable connection? I read a lot of topics, but did not find the right answer.
MyService.java
package home.xmpp;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.ComponentCallbacks2;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;
import javax.net.ssl.HttpsURLConnection;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
public class MyService extends Service implements ComponentCallbacks2 {
private Boolean disconnectAppeared = false;
static MyService instance;
private Handler mHandler = new Handler();
MyTask mt;
Boolean mtruned = false;
public static MyService getInstance(){
return instance;
}
#Override
public IBinder onBind(final Intent intent) {
//throw new UnsupportedOperationException("Not yet implemented");
return new LocalBinder<MyService>(this);
}
#Override
public void onCreate() {
super.onCreate();
instance = this;
mHandler.postDelayed(timeUpdaterRunnable, 100);
Log.e("MyService"," created");
}
#Override
public int onStartCommand(final Intent intent, final int flags,
final int startId) {
return Service.START_STICKY;
}
#Override
public boolean onUnbind(final Intent intent) {
return super.onUnbind(intent);
}
#Override
public void onDestroy() {
super.onDestroy();
Log.e("MyService"," destroyed");
mHandler.removeCallbacks(timeUpdaterRunnable);
}
public void onTrimMemory(int level) {
switch (level) {
case ComponentCallbacks2.TRIM_MEMORY_RUNNING_CRITICAL: //Release any memory that your app doesn't need to run.
//the system will begin killing background processes. !!!
Log.e("Memory level","4");
break;
default:
break;
}
}
private Runnable timeUpdaterRunnable = new Runnable() {
public void run() {
if (mtruned == false) {
Log.e("Time", " update");
mt = new MyTask();
mt.execute();
mHandler.postDelayed(this, 10000);
} else {
cancelTask();
}
}
};
private void cancelTask() {
if (mt == null) return;
Log.d("MyService", "cancel result: " + mt.cancel(false));
}
class MyTask extends AsyncTask<String,Void,String> {
#Override
protected void onPreExecute() {
mtruned = true;
super.onPreExecute();
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
Log.e("http","updated");
mtruned = false;
}
#Override
protected String doInBackground(String... params) {
String result = "";
HashMap<String,String> data = new HashMap<>();
data.put("data", "data");
result = sendPostRequest("http://www.ya.ru", data);
return result;
}
#Override
protected void onCancelled() {
super.onCancelled();
mtruned = false;
}
}
public String sendPostRequest(String requestURL,
HashMap<String, String> postDataParams) {
//Creating a URL
URL url;
//StringBuilder object to store the message retrieved from the server
StringBuilder sb = new StringBuilder();
try {
//Initializing Url
url = new URL(requestURL);
//Creating an httmlurl connection
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//Configuring connection properties
conn.setReadTimeout(15000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
//Creating an output stream
OutputStream os = conn.getOutputStream();
//Writing parameters to the request
//We are using a method getPostDataString which is defined below
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(getPostDataString(postDataParams));
writer.flush();
writer.close();
os.close();
int responseCode = conn.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
sb = new StringBuilder();
String response;
//Reading server response
while ((response = br.readLine()) != null){
sb.append(response);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return sb.toString();
}
private String getPostDataString(HashMap<String, String> params) throws UnsupportedEncodingException {
StringBuilder result = new StringBuilder();
boolean first = true;
for (Map.Entry<String, String> entry : params.entrySet()) {
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
}
return result.toString();
}
}
Update 05.10.17 I still not find a solution. I tested this programm on Android 4.1.2. It works fine. On Android 5.1.1 it works about 3 minutes after exiting the activity and then I receive connection refused error. When I return to activity, errors disappears. On Android 6.0.1 similar situation, but the error is slightly different java.net.SocketTimeoutException: failed to connect to /94.130.25.242 (port 80) after 10000ms. I think that the system blocks network activity in services after a while, but never in activities (?).
Update 05.10.17
I noticed that the connection disappears not only after the restart of the service, but also after 2-3 minutes, when exiting activity. When I return to activity, connections are restored.
I have made a video Link
Update 06.10.17
One Android specialist told me, that this problem appear only in Xiaomi phones. MIUI rejects network connections after some minutes. Only OkHttp helps. I will try it and will make feedback here.

A "connect failed: ECONNREFUSED (Connection refused)" most likely means that there is nothing listening on that port AND that IP address. Possible explanations include:
the service has crashed or hasn't been started,
your client is trying to connect using the wrong IP address or port,
or
server access is being blocked by a firewall that is "refusing" on
the server/service's behalf. This is pretty unlikely given that
normal practice (these days) is for firewalls to "blackhole" all
unwanted connection attempts.

It is impossible to use long network connections in background on Xiaomi phones. It's MIUI blocks any network connections after some time. For critical network connections, you can use Firebase Cloud Messaging, which have high priority in Android system. It can initiate necesary background job.

Related

How can you execute a repeating JSoup task which will work even if the app is in background in android

For my app I need values which are parsed by jSoup from a website and then returned to the user using a notification, these values change ~ every minute, so to be up-todate with the values I set up a task using a handler, this works good when the app is in foreground, but as soon as the user goes to the homescreen the app will return multiple exceptions like e.g. java.net.UnknownHostException or java.net.SocketTimeoutException, in the code this happens when jSoup is connecting to the specified site, I already tried using Services and AsyncTasks instead of threads, but it was always the exact same problem, I also searched for people with similar experiences, but I guess my issue is quite specific.
This is the code for the handler:
private final static int INTERVAL = 1000 * 60;
Handler mHandler = new Handler();
Runnable mHandlerTask = new Runnable()
{
#Override
public void run() {
try {
wakeLock.release();
} catch (RuntimeException e) {
e.printStackTrace();
}
if (!isUpdating) {
isUpdating = true;
App.shouldUpdate = true;
System.out.println("update");
final TinyDB tinydb = new TinyDB(getApplicationContext());
TextView priceEditText = loadedLayouts.get(1).findViewById(R.id.priceTextView);
TextView increaseEditText = loadedLayouts.get(1).findViewById(R.id.increaseTextView);
updatePricesStock(tinydb.getString("current_isin"), priceEditText, increaseEditText);
}
wakeLock.acquire(2*60*1000L /*10 minutes*/);
}
mHandler.postDelayed(mHandlerTask, INTERVAL);
}
}
};
and this is the code for the updateStockPrices method (I will not include updatePricesWarrant and updatePricesKnockout since they are essentially doing the same things and also throw the same exceptions)
public void updatePricesStock(final String ISIN, TextView priceText, TextView increaseText) {
final TinyDB tinydb = new TinyDB(getApplicationContext());
final Thread thread = new Thread(new Runnable() {
#Override
public void run() {
TinyDB tinydb = new TinyDB(getApplicationContext());
try {
Document doc = Jsoup.connect("https://www.ls-tc.de/de/aktie/" + ISIN).get();
System.out.println(ISIN);
increase = doc.selectFirst("#page_content > div > div:nth-child(1) > div > div.mpe_bootstrapgrid.col-md-8 > div > div:nth-child(3) > div > span:nth-child(3)").text().replace(" ", "");
tinydb.putString(ISIN + "notification_price", doc.selectFirst("#page_content > div > div:nth-child(1) > div > div.mpe_bootstrapgrid.col-md-8 > div > div:nth-child(3) > div > span:nth-child(1)").text() + "€");
} catch (IOException e) {
e.printStackTrace();
tinydb.putString(ISIN + "notification_price", "Error Scraping Price");
}
}
});
if(!thread.isAlive()) {
thread.start();
}
try{
thread.join();
}catch (Exception ex){
ex.printStackTrace();
}
if(!thread.isAlive()) {
notificationCompat = NotificationManagerCompat.from(getApplicationContext());
System.out.println("done");
System.out.println(tinydb.getString(ISIN + "notification_price"));
priceText.setText(tinydb.getString(ISIN + "notification_price"));
increaseText.setText(increase);
System.out.println("Text Updated " + priceText.getText().toString());
if(tinydb.getBoolean(ISIN + "_notification_status")) {
Notification notification = new NotificationCompat.Builder(getApplicationContext(), App.notificationChannel)
.setSmallIcon(R.drawable.ic_baseline_attach_money_24).setContentTitle(tinydb.getString(ISIN + "notification_name")).setContentText(tinydb.getString(ISIN + "notification_price")).setPriority(NotificationCompat.PRIORITY_MAX).setCategory(NotificationCompat.CATEGORY_STATUS).setOnlyAlertOnce(true).build();
notificationCompat.notify(tinydb.getInt(ISIN + "_notification_id"), notification);
}
isUpdating = false;
}
}
finnally these are the stacktraces I get:
W/System.err: java.net.SocketTimeoutException: timeout
W/System.err: at com.android.okhttp.okio.Okio$3.newTimeoutException(Okio.java:225)
at com.android.okhttp.okio.AsyncTimeout.exit(AsyncTimeout.java:263)
W/System.err: at com.android.okhttp.okio.AsyncTimeout$2.read(AsyncTimeout.java:217)
at com.android.okhttp.okio.RealBufferedSource.indexOf(RealBufferedSource.java:317)
at com.android.okhttp.okio.RealBufferedSource.indexOf(RealBufferedSource.java:311)
W/System.err: at com.android.okhttp.okio.RealBufferedSource.readUtf8LineStrict(RealBufferedSource.java:207)
W/System.err: at com.android.okhttp.internal.http.Http1xStream.readResponse(Http1xStream.java:388)
at com.android.okhttp.internal.http.Http1xStream.readResponseHeaders(Http1xStream.java:146)
W/System.err: at com.android.okhttp.internal.http.HttpEngine.readNetworkResponse(HttpEngine.java:900)
at com.android.okhttp.internal.http.HttpEngine.readResponse(HttpEngine.java:772)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:493)
W/System.err: at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:429)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getResponseCode(HttpURLConnectionImpl.java:560)
W/System.err: at com.android.okhttp.internal.huc.DelegatingHttpsURLConnection.getResponseCode(DelegatingHttpsURLConnection.java:106)
at com.android.okhttp.internal.huc.HttpsURLConnectionImpl.getResponseCode(HttpsURLConnectionImpl.java:30)
at org.jsoup.helper.HttpConnection$Response.execute(HttpConnection.java:734)
W/System.err: at org.jsoup.helper.HttpConnection$Response.execute(HttpConnection.java:706)
W/System.err: at org.jsoup.helper.HttpConnection.execute(HttpConnection.java:299)
W/System.err: at org.jsoup.helper.HttpConnection.get(HttpConnection.java:288)
at de.xliquid.stockwatchultimate.MainActivity$4.run(MainActivity.java:266)
W/System.err: at java.lang.Thread.run(Thread.java:919)
W/System.err: Caused by: java.net.SocketException: socket is closed
at com.android.org.conscrypt.ConscryptFileDescriptorSocket$SSLInputStream.read(ConscryptFileDescriptorSocket.java:588)
at com.android.okhttp.okio.Okio$2.read(Okio.java:145)
at com.android.okhttp.okio.AsyncTimeout$2.read(AsyncTimeout.java:213)
W/System.err: ... 18 more
java.net.UnknownHostException: Unable to resolve host "www.onvista.de": No address associated with hostname
at java.net.Inet6AddressImpl.lookupHostByName(Inet6AddressImpl.java:156)
W/System.err: at java.net.Inet6AddressImpl.lookupAllHostAddr(Inet6AddressImpl.java:103)
at java.net.InetAddress.getAllByName(InetAddress.java:1152)
at com.android.okhttp.Dns$1.lookup(Dns.java:41)
W/System.err: at com.android.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:178)
at com.android.okhttp.internal.http.RouteSelector.nextProxy(RouteSelector.java:144)
at com.android.okhttp.internal.http.RouteSelector.next(RouteSelector.java:86)
at com.android.okhttp.internal.http.StreamAllocation.findConnection(StreamAllocation.java:192)
at com.android.okhttp.internal.http.StreamAllocation.findHealthyConnection(StreamAllocation.java:144)
at com.android.okhttp.internal.http.StreamAllocation.newStream(StreamAllocation.java:106)
at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:400)
W/System.err: at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:333)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:483)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:429)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getResponseCode(HttpURLConnectionImpl.java:560)
at com.android.okhttp.internal.huc.DelegatingHttpsURLConnection.getResponseCode(DelegatingHttpsURLConnection.java:106)
at com.android.okhttp.internal.huc.HttpsURLConnectionImpl.getResponseCode(HttpsURLConnectionImpl.java:30)
at org.jsoup.helper.HttpConnection$Response.execute(HttpConnection.java:734)
at org.jsoup.helper.HttpConnection$Response.execute(HttpConnection.java:706)
at org.jsoup.helper.HttpConnection.execute(HttpConnection.java:299)
at org.jsoup.helper.HttpConnection.get(HttpConnection.java:288)
W/System.err: at de.xliquid.stockwatchultimate.MainActivity$6.run(MainActivity.java:371)
at java.lang.Thread.run(Thread.java:919)
W/System.err: Caused by: android.system.GaiException: android_getaddrinfo failed: EAI_NODATA (No address associated with hostname)
W/System.err: at libcore.io.Linux.android_getaddrinfo(Native Method)
W/System.err: at libcore.io.ForwardingOs.android_getaddrinfo(ForwardingOs.java:74)
at libcore.io.BlockGuardOs.android_getaddrinfo(BlockGuardOs.java:200)
at libcore.io.ForwardingOs.android_getaddrinfo(ForwardingOs.java:74)
at java.net.Inet6AddressImpl.lookupHostByName(Inet6AddressImpl.java:135)
W/System.err: ... 22 more
Also this app is solely for me so I don't really bother if the solution isn't the cleanest or drains the battery faster.
The problem was energy saving mode, if it is turned on the phone won't do requests in background / idle mode, no matter the wakelock, I solved my problem by adding a permission, so the app can request data even when the phone is in energy saving standby.

java.io.FileNotFoundException: open failed: EACCES (Permission denied) while trying to record using JobIntentService

I'm trying to set up an android call recorder using a Broadcast Receiver and a JobIntentService. However, whenever I launch the JobIntentService, the Mediarecorder.prepare() method throws an error as follows:
W/System.err: java.io.FileNotFoundException: /storage/emulated/0/Music/filename.3gp: open failed: EACCES (Permission denied)
W/System.err: at libcore.io.IoBridge.open(IoBridge.java:496)
W/System.err: at java.io.RandomAccessFile.<init>(RandomAccessFile.java:289)
W/System.err: at java.io.RandomAccessFile.<init>(RandomAccessFile.java:152)
W/System.err: at android.media.MediaRecorder.prepare(MediaRecorder.java:1046)
W/System.err: at com.example.callrecorder.Job.recordCall(Job.java:77)
W/System.err: at com.example.callrecorder.Job.onHandleWork(Job.java:38)
W/System.err: at androidx.core.app.JobIntentService$CommandProcessor.doInBackground(JobIntentService.java:392)
W/System.err: at androidx.core.app.JobIntentService$CommandProcessor.doInBackground(JobIntentService.java:383)
W/System.err: at android.os.AsyncTask$3.call(AsyncTask.java:378)
W/System.err: at java.util.concurrent.FutureTask.run(FutureTask.java:266)
W/System.err: at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
W/System.err: at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
W/System.err: at java.lang.Thread.run(Thread.java:919)
W/System.err: Caused by: android.system.ErrnoException: open failed: EACCES (Permission denied)
W/System.err: at libcore.io.Linux.open(Native Method)
W/System.err: at libcore.io.ForwardingOs.open(ForwardingOs.java:167)
W/System.err: at libcore.io.BlockGuardOs.open(BlockGuardOs.java:252)
W/System.err: at libcore.io.ForwardingOs.open(ForwardingOs.java:167)
W/System.err: at android.app.ActivityThread$AndroidOs.open(ActivityThread.java:7255)
W/System.err: at libcore.io.IoBridge.open(IoBridge.java:482)
W/System.err: ... 12 more
I/Try: java.io.FileNotFoundException: /storage/emulated/0/Music/filename.3gp: open failed: EACCES (Permission denied)
E/MediaRecorder: start called in an invalid state: 4
E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #1
Process: com.example.callrecorder, PID: 10311
java.lang.RuntimeException: An error occurred while executing doInBackground()
at android.os.AsyncTask$4.done(AsyncTask.java:399)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:383)
at java.util.concurrent.FutureTask.setException(FutureTask.java:252)
at java.util.concurrent.FutureTask.run(FutureTask.java:271)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
at java.lang.Thread.run(Thread.java:919)
Caused by: java.lang.IllegalStateException
at android.media.MediaRecorder.start(Native Method)
at com.example.callrecorder.Job.recordCall(Job.java:82)
at com.example.callrecorder.Job.onHandleWork(Job.java:38)
at androidx.core.app.JobIntentService$CommandProcessor.doInBackground(JobIntentService.java:392)
at androidx.core.app.JobIntentService$CommandProcessor.doInBackground(JobIntentService.java:383)
at android.os.AsyncTask$3.call(AsyncTask.java:378)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167) 
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641) 
at java.lang.Thread.run(Thread.java:919)
The code for my JobIntentService is as follows:
public class Job extends JobIntentService {
static final int JOB_ID = 1000;
String state;
MediaRecorder mediaRecorder;
static void enqueueWork(Context context, Intent intent) {
enqueueWork(context, Job.class, JOB_ID, intent);
}
#Override
protected void onHandleWork(#NonNull Intent intent) {
Log.i("Job", "Triggered");
state = intent.getExtras().getString(TelephonyManager.EXTRA_STATE);
switch (state) {
case "OFFHOOK": {
recordCall();
}
break;
case "IDLE": {
stopRecording();
}
break;
}
}
#Override
public void onDestroy() {
super.onDestroy();
}
private void stopRecording() {
Log.i("Stato", "Stopped");
mediaRecorder.stop();
mediaRecorder.release();
mediaRecorder = null;
}
private void recordCall() {
String recordPath = null;
String path = Environment.getExternalStoragePublicDirectory(DIRECTORY_MUSIC).getAbsolutePath();
File dir = new File(path);
if(!dir.exists()) {
dir.mkdirs();
}
String myFile = "filename.3gp";
mediaRecorder = new MediaRecorder();
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mediaRecorder.setOutputFile(dir + "/" + myFile);
mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
try {
mediaRecorder.prepare();
} catch (Exception e) {
e.printStackTrace();
Log.i("Try", String.valueOf(e));
}
mediaRecorder.start();
Log.i("Stato", "Started");
}
}
The intent for this service is passed from a Broadcast Receiver and it all runs fine is I try to check by removing the media recorder part. For some reason, it throws errors whenever I try to start the media recorder saying Permission Denied.
I have given WRITE_EXTERNAL_STORAGE, READ_EXTERNAL_STORAGE, RECORD_AUDIO, READ_PHONE_STATE, PROCESS_OUTGOING_CALLS permissions in the Android Manifest file.
The jobservice and receiver have been registered as well.
From Android 10 onwards, you need legacy permission to access storage the old way or switch to using the new methods.
Add this under applications in Manifest for legacy storage.
android:requestLegacyExternalStorage="true"
Recording calls feature has also been stopped from android 10 so you can no longer record calls on it without accessibility options.

how to resolve failed to connect to /192.168.15.186 (port 80): connect failed: ETIMEDOUT (Connection timed out) in Windows Firewall

I'm trying to test android studio connection to mysql based on this tutorial using my android device for debugging purposes instead of android emulator. But the problem is, it results to:
java.net.ConnectException: failed to connect to /192.168.15.186 (port 80): connect failed: ETIMEDOUT (Connection timed out)
Take note that this is running on real device. localhost or 127.0.0.1:80 would return a result of ECONNREFUSED because obviously, this are computer addresses that the database aren't in the device but in the computer itself so it would be a completely waste of time if I test these 2 out or any alternative IP's.
I've tested out 10.0.2.2:80/login.php on emulator and it returns a true result hinting that the login and connection is success.
So I'm guessing that maybe the connection is block through the windows firewall, but I dont know how to modify it.
LOGCAT
03-06 13:59:29.935 20951-20951/com.example.smdojt.mysqldemo W/InputEventReceiver: Attempted to finish an input event but the input event receiver has already been disposed.
03-06 14:01:30.744 20951-25612/com.example.smdojt.mysqldemo W/System.err: java.net.ConnectException: failed to connect to /192.168.15.186 (port 80): connect failed: ETIMEDOUT (Connection timed out)
03-06 14:01:30.744 20951-25612/com.example.smdojt.mysqldemo W/System.err: at libcore.io.IoBridge.connect(IoBridge.java:124)
03-06 14:01:30.744 20951-25612/com.example.smdojt.mysqldemo W/System.err: at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:200)
03-06 14:01:30.744 20951-25612/com.example.smdojt.mysqldemo W/System.err: at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:513)
03-06 14:01:30.744 20951-25612/com.example.smdojt.mysqldemo W/System.err: at java.net.Socket.connect(Socket.java:894)
03-06 14:01:30.744 20951-25612/com.example.smdojt.mysqldemo W/System.err: at com.android.okhttp.internal.Platform.connectSocket(Platform.java:174)
03-06 14:01:30.744 20951-25612/com.example.smdojt.mysqldemo W/System.err: at com.android.okhttp.Connection.connect(Connection.java:152)
03-06 14:01:30.744 20951-25612/com.example.smdojt.mysqldemo W/System.err: at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:276)
03-06 14:01:30.744 20951-25612/com.example.smdojt.mysqldemo W/System.err: at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:211)
03-06 14:01:30.744 20951-25612/com.example.smdojt.mysqldemo W/System.err: at com.android.okhttp.internal.http.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:382)
03-06 14:01:30.744 20951-25612/com.example.smdojt.mysqldemo W/System.err: at com.android.okhttp.internal.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:106)
03-06 14:01:30.744 20951-25612/com.example.smdojt.mysqldemo W/System.err: at com.android.okhttp.internal.http.HttpURLConnectionImpl.getOutputStream(HttpURLConnectionImpl.java:217)
03-06 14:01:30.745 20951-25612/com.example.smdojt.mysqldemo W/System.err: at com.example.smdojt.mysqldemo.BackgroundWorker.doInBackground(BackgroundWorker.java:48)
03-06 14:01:30.745 20951-25612/com.example.smdojt.mysqldemo W/System.err: at com.example.smdojt.mysqldemo.BackgroundWorker.doInBackground(BackgroundWorker.java:23)
03-06 14:01:30.745 20951-25612/com.example.smdojt.mysqldemo W/System.err: at android.os.AsyncTask$2.call(AsyncTask.java:292)
03-06 14:01:30.745 20951-25612/com.example.smdojt.mysqldemo W/System.err: at java.util.concurrent.FutureTask.run(FutureTask.java:237)
03-06 14:01:30.745 20951-25612/com.example.smdojt.mysqldemo W/System.err: at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
03-06 14:01:30.745 20951-25612/com.example.smdojt.mysqldemo W/System.err: at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
03-06 14:01:30.745 20951-25612/com.example.smdojt.mysqldemo W/System.err: at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
03-06 14:01:30.745 20951-25612/com.example.smdojt.mysqldemo W/System.err: at java.lang.Thread.run(Thread.java:818)
03-06 14:01:30.745 20951-25612/com.example.smdojt.mysqldemo W/System.err: Caused by: android.system.ErrnoException: connect failed: ETIMEDOUT (Connection timed out)
03-06 14:01:30.745 20951-25612/com.example.smdojt.mysqldemo W/System.err: at libcore.io.Posix.connect(Native Method)
03-06 14:01:30.745 20951-25612/com.example.smdojt.mysqldemo W/System.err: at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:111)
03-06 14:01:30.745 20951-25612/com.example.smdojt.mysqldemo W/System.err: at libcore.io.IoBridge.connectErrno(IoBridge.java:137)
03-06 14:01:30.745 20951-25612/com.example.smdojt.mysqldemo W/System.err: at libcore.io.IoBridge.connect(IoBridge.java:122)
03-06 14:01:30.745 20951-25612/com.example.smdojt.mysqldemo W/System.err: ... 18 more
03-06 14:01:30.748 20951-20951/com.example.smdojt.mysqldemo D/wangcy9: setStatusIcon occur wrong theme!
03-06 14:01:30.782 20951-20951/com.example.smdojt.mysqldemo D/ViewRootImpl: loadSystemProperties PersistDebugEvent: false RoDebugEvent: false
03-06 14:02:30.313 20951-20951/com.example.smdojt.mysqldemo W/InputEventReceiver: Attempted to finish an input event but the input event receiver has already been disposed.
MAINACTIVITY.java
public class MainActivity extends AppCompatActivity {
EditText UsernameEt, PasswordEt;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
UsernameEt = (EditText) findViewById(R.id.etUserName);
PasswordEt = (EditText) findViewById(R.id.etPassword);
}
public void OnLogin(View view)
{
String username = UsernameEt.getText().toString();
String password = PasswordEt.getText().toString();
String type = "login";
BackgroundWorker backgroundWorker = new BackgroundWorker(this);
backgroundWorker.execute(type, username, password);
}
}
BACKGROUNDWORKER.java
public class BackgroundWorker extends AsyncTask<String, Void, String> {
Context context;
AlertDialog alertDialog;
BackgroundWorker (Context ctx)
{
context = ctx;
}
#Override
protected String doInBackground(String... params) {
String type = params[0];
String login_url = "http://192.168.15.186:80/login.php"; //declare want you want to connect with
if (type.equals("login"))
{
try {
String user_name = params[1];
String password = params[2];
URL url = new URL(login_url);
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection(); //declare http connection class
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
String post_data = URLEncoder.encode("user_name","UTF-8") + "=" +URLEncoder.encode(user_name, "UTF-8")+"&"
+URLEncoder.encode("password","UTF-8") + "=" +URLEncoder.encode(password, "UTF-8");
bufferedWriter.write(post_data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
//below: read and get post respone
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"));
String result="";
String line="";
while ((line = bufferedReader.readLine())!=null)
{
result += line;
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return result;
} catch (MalformedURLException e) {
e.printStackTrace();
}
//Clause for httpurlconnection
catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPreExecute() {
alertDialog = new AlertDialog.Builder(context).create();
alertDialog.setTitle("Login Status");
}
#Override
protected void onPostExecute(String result) {
alertDialog.setMessage(result);
alertDialog.show();
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
}
I had the same Issue today, and i solved it by making my PC discoverable in private networks.
Steps to make your PC Discoverable:
Go to network settings.
>Go to Manage known networks.
>Choose your network.
>Now turn on the PC discoverable feature.
It helped for me, i hope it will help you.
I have faced such problem but overcome through allow port 1433(my port) to firewall .
I have Followed below Steps:
Configure Firewall and Security Setting -> Advanced Setting ->Inbound Rules -> New Rule-> Port -> Next ->Specific Local Port(1433)->Next-> Allow the Connection -> Next ->Next-> Add Name-> Finish
I also faced the same problem today and I solved it when I turned off the fire wall and network protection setting.
I solved my problem when I change Network profile from private to public.

Getting FileNotFoundException when trying to upload File to Google Cloud Storage

I'm trying to upload an image from Android to Cloud Storage. I'm following this official guide on how to upload files to Google Cloud Storage using the JSON API. Here is my code
private class uploadImage extends AsyncTask<File, Void, String> {
File file = mPhotoFile;
private String delimiter = "--";
#Override
protected void onPreExecute() {
Toast.makeText(getActivity(), mPhotoFile.getPath(), Toast.LENGTH_SHORT).show();
}
#Override
protected String doInBackground(File... params) {
try {
URL url = new URL("https://www.googleapis.com/upload/storage/v1/b/backend-images/o?uploadType=media&name=myObject?key=my_key");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("POST");
urlConnection.setChunkedStreamingMode(0);
urlConnection.setRequestProperty("Content-Type", "image/jpeg");
urlConnection.setRequestProperty("Content-Length", String.valueOf(mPhotoFile.getPath().getBytes().length));
urlConnection.setRequestProperty("Authorization", "my_key");
urlConnection.setDoOutput(true);
urlConnection.setDoOutput(true);
OutputStream out = new BufferedOutputStream(urlConnection.getOutputStream());
InputStream responseStream = new BufferedInputStream(urlConnection.getInputStream());
BufferedReader responseStreamReader = new BufferedReader(new InputStreamReader(responseStream));
out.write(("Content-Type: image/jpeg\r\n").getBytes());
out.write(("Content-Length: " + String.valueOf(mPhotoFile.getPath().getBytes().length)).getBytes());
out.write("\r\n".getBytes());
out.write(mPhotoFile.getPath().getBytes());
out.write("\r\n".getBytes());
String line = "";
StringBuilder stringBuilder = new StringBuilder();
while((line = responseStreamReader.readLine()) != null) {
stringBuilder.append(line).append("\n");
}
String response = stringBuilder.toString();
Log.i("CloudStorage", response);
} catch (IOException e) {
e.printStackTrace();
return e.getMessage();
}
return "Everything was a success";
}
}
I'm using the Public API access method and appending the Api key to the link like the guide says I could to authorize requests
Here is the error i'm getting
05-22 10:24:01.798 3747-4045/com.example.kid.uimockup W/System.err: java.io.FileNotFoundException:https://www.googleapis.com/upload/storage/v1/b/backend-images/o?uploadType=media&name=myObject?key=my_key
05-22 10:24:01.798 3747-4045/com.example.kid.uimockup W/System.err: at com.android.okhttp.internal.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:197)
05-22 10:24:01.798 3747-4045/com.example.kid.uimockup W/System.err: at com.android.okhttp.internal.http.DelegatingHttpsURLConnection.getInputStream(DelegatingHttpsURLConnection.java:210)
05-22 10:24:01.798 3747-4045/com.example.kid.uimockup W/System.err: at com.android.okhttp.internal.http.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:25)
05-22 10:24:01.798 3747-4045/com.example.kid.uimockup W/System.err: at com.example.kid.uimockup.HomeFragment$uploadImage.doInBackground(HomeFragment.java:636)
05-22 10:24:01.803 3747-4045/com.example.kid.uimockup W/System.err: at com.example.kid.uimockup.HomeFragment$uploadImage.doInBackground(HomeFragment.java:605)
05-22 10:24:01.803 3747-4045/com.example.kid.uimockup W/System.err: at android.os.AsyncTask$2.call(AsyncTask.java:288)
05-22 10:24:01.803 3747-4045/com.example.kid.uimockup W/System.err: at java.util.concurrent.FutureTask.run(FutureTask.java:237)
05-22 10:24:01.803 3747-4045/com.example.kid.uimockup W/System.err: at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
05-22 10:24:01.803 3747-4045/com.example.kid.uimockup W/System.err: at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
05-22 10:24:01.803 3747-4045/com.example.kid.uimockup W/System.err: at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
05-22 10:24:01.803 3747-4045/com.example.kid.uimockup W/System.err: at java.lang.Thread.run(Thread.java:818)
I don't have a clue if this is a problem on the client side or the server side
I got it work after making a few changes. I was getting a 401 Unauthorized Error code which means I didn't have authorization to access the bucket.
So instead of appending the query parameter key=api_key, i appended access_token=auth_token to authorize requests.
I then added allUsers permission to my bucket (making it public for everyone to write and read) and it worked.

BufferedInputStream is closed when setting postDelayed Runnable

I have my GameActivity that is a simple quiz. I set up two Runnables, mRunnableQuestion and mRunnableQuestionWithPenalty. The logic is: mRunnableQuestion shows new question and waits 30 seconds, when user doesn't answer in this time, the other Runnable is called, which gives user points penalty:
private Runnable mRunnableQuestion = new Runnable() {
#Override
public void run() {
new AsyncAPIGetQuestion().execute(mCategoryId);
mHandler.postDelayed(mRunnableQuestionWithPenalty, 30000);
}
};
Of course, when user answers in time, I give user points and restart the Runnable:
mHandler.removeCallbacksAndMessages(null);
mHandler.post(mRunnableQuestion);
It works very well. However, I wanted to color the Cards based on correct/wrong answer and wait 5 seconds. So i changed code above to:
mHandler.removeCallbacksAndMessages(null);
colorAnswers();
mHandler.postDelayed(mRunnableQuestion, 5000);
This is where the problem begins. When I run my app, after 2, 3 or 4 questions I get a EOF/BufferedInputStream error:
03-04 13:38:24.107 16506-16532/com.my.pkg W/System.err: java.io.EOFException
03-04 13:38:24.107 16506-16532/com.my.pkg W/System.err: at com.android.okio.RealBufferedSource.readUtf8LineStrict(RealBufferedSource.java:95)
03-04 13:38:24.107 16506-16532/com.my.pkg W/System.err: at com.
android.okhttp.internal.http.HttpConnection.readResponse(HttpConnection.java:175)
03-04 13:38:24.107 16506-16532/com.my.pkg W/System.err: at com.android.okhttp.internal.http.HttpTransport.readResponseHeaders(HttpTransport.java:101)
03-04 13:38:24.107 16506-16532/com.my.pkg W/System.err: at com.android.okhttp.internal.http.HttpEngine.readResponse(HttpEngine.java:616)
03-04 13:38:24.107 16506-16532/com.my.pkg W/System.err: at com.android.okhttp.internal.http.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:379)
03-04 13:38:24.107 16506-16532/com.my.pkg W/System.err: at com.android.okhttp.internal.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:323)
03-04 13:38:24.108 16506-16532/com.my.pkg W/System.err: at com.android.okhttp.internal.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:190)
03-04 13:38:24.108 16506-16532/com.my.pkg W/System.err: at com.my.pkg.JSONParser.getJSONFromUrl(JSONParser.java:45)
03-04 13:38:24.108 16506-16532/com.my.pkg W/System.err: at com.my.pkg.GameActivity$AsyncAPIGetQuestion.doInBackground(GameActivity.java:317)
03-04 13:38:24.108 16506-16532/com.my.pkg W/System.err: at com.my.pkg.GameActivity$AsyncAPIGetQuestion.doInBackground(GameActivity.java:299)
03-04 13:38:24.108 16506-16532/com.my.pkg W/System.err: at android.os.AsyncTask$2.call(AsyncTask.java:288)
03-04 13:38:24.108 16506-16532/com.my.pkg W/System.err: at java.util.concurrent.FutureTask.run(FutureTask.java:237)
03-04 13:38:24.108 16506-16532/com.my.pkg W/System.err: at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
03-04 13:38:24.108 16506-16532/com.my.pkg W/System.err: at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
03-04 13:38:24.108 16506-16532/com.my.pkg W/System.err: at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
03-04 13:38:24.108 16506-16532/com.my.pkg W/System.err: at java.lang.Thread.run(Thread.java:818)
03-04 13:38:24.108 16506-16532/com.my.pkg E/JSONParser.java: Error converting result java.io.IOException: BufferedInputStream is closed
It ONLY happens, when I add the extra postDelayed() there. No problems before.
My doInBackground part of AsyncTask that is executed by Runnable and that returns an error as stated above
#Override
protected JSONArray doInBackground(String... params) {
JSONParser jParser = new JSONParser();
JSONArray json = jParser.getJSONFromUrl(apiURL);
return json;
}
And the JSONParser.getJSONFromURL:
public JSONArray getJSONFromUrl(String urlSource) {
try {
URL url = new URL(urlSource);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setDoOutput(true);
urlConnection.setChunkedStreamingMode(0);
inputStream = new BufferedInputStream(urlConnection.getInputStream());
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
if(!reader.ready()) {
break;
}
}
inputStream.close();
json = sb.toString();
} catch (Exception e) {
Log.e(TAG, "Error converting result " + e.toString());
}
try {
jArr = new JSONArray(json);
} catch (JSONException e) {
Log.e(TAG, "Error parsing data " + e.toString());
}
return jArr;
}
I would really appreciate any help. All the best!
It looks like I solved this issue.
The problem was in my jParser.getJSONFromUrl() method, specifically these lines:
URL url = new URL(urlSource);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setDoOutput(true);
It seems that you only set setDoOutput parameter as true, when you are using POST/PUT requests. If you want only perform a GET request, such as in my case, you should set it as false:
urlConnection.setDoOutput(false);
Otherwise, you can end up getting errors as described above.
Best regards to the Community!

Categories