Connecting Android studio to Cosmos Database - java

I am working on a project to retrieve data from azure Cosmos database into Android Studio. However, there is an error with it, I can't really find any solutions for it. Please help, thanks!
dependencies: implementation 'com.azure:azure-cosmos:4.3.0'
import com.azure.cosmos.ConsistencyLevel;
import com.azure.cosmos.CosmosClient;
import com.azure.cosmos.CosmosClientBuilder;
import com.azure.cosmos.CosmosContainer;
import com.azure.cosmos.CosmosDatabase;
import com.azure.cosmos.implementation.ConnectionPolicy;
import com.azure.cosmos.models.CosmosItemRequestOptions;
import com.azure.cosmos.models.CosmosQueryRequestOptions;
import com.azure.cosmos.util.CosmosPagedFlux;
import com.azure.cosmos.util.CosmosPagedIterable;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "";
private final String databaseName = "smartwristbanddb";
private final String containerName = "records";
public CosmosDatabase database = null;
public CosmosContainer container = null;
public static CosmosClient client;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
System.out.println("Using Azure Cosmos DB endpoint: " + dbAccount.HOST);
// <CreateSyncClient>
ConnectionPolicy policy = ConnectionPolicy.getDefaultPolicy();
try {
//getStartedDemo();
client = new CosmosClientBuilder()
.endpoint(dbAccount.HOST)
.key(dbAccount.MASTER_KEY)
.consistencyLevel(ConsistencyLevel.SESSION)
.buildClient();
database = client.getDatabase(databaseName);
container = database.getContainer(containerName);
} catch (Exception e) {
e.printStackTrace();
}
}
The error is as below:
W/m.example.myapp: type=1400 audit(0.0:9885): avc: denied { read } for name="somaxconn" dev="proc" ino=4276772 scontext=u:r:untrusted_app:s0:c28,c257,c512,c768 tcontext=u:object_r:proc_net:s0 tclass=file permissive=0 ----------
W/System.err: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean com.azure.cosmos.implementation.DatabaseAccount.getEnableMultipleWriteLocations()' on a null object reference at com.azure.cosmos.BridgeInternal.isEnableMultipleWriteLocations(BridgeInternal.java:163) W/System.err: at com.azure.cosmos.implementation.RxDocumentClientImpl.initializeGatewayConfigurationReader(RxDocumentClientImpl.java:264) at com.azure.cosmos.implementation.RxDocumentClientImpl.init(RxDocumentClientImpl.java:281) at com.azure.cosmos.implementation.AsyncDocumentClient$Builder.build(AsyncDocumentClient.java:203) W/System.err: at com.azure.cosmos.CosmosAsyncClient.<init>(CosmosAsyncClient.java:79) at com.azure.cosmos.CosmosClientBuilder.buildAsyncClient(CosmosClientBuilder.java:649) at com.azure.cosmos.CosmosClient.<init>(CosmosClient.java:30) at com.azure.cosmos.CosmosClientBuilder.buildClient(CosmosClientBuilder.java:661) W/System.err: at com.example.myapp.MainActivity.onCreate(MainActivity.java:52) at android.app.Activity.performCreate(Activity.java:7972) at android.app.Activity.performCreate(Activity.java:7961) W/System.err: at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1306) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3496) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3680) at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83) W/System.err: at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:140) at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:100) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2230) W/System.err: at android.os.Handler.dispatchMessage(Handler.java:107) at android.os.Looper.loop(Looper.java:227) at android.app.ActivityThread.main(ActivityThread.java:7802) at java.lang.reflect.Method.invoke(Native Method) W/System.err: at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1027)

You have got Null reference error. Pls check if config values (HOST, MASTER_KEY) are right and client, database or container instances are not null.
I would suggest you to implement this functionality by following this step by step tutorial: Tutorial: Build a Java web application using Azure Cosmos DB and the SQL API

Related

BluetoothDevice.getUuids() returns null

I am currently working on an app which requires a Bluetooth laser meter. So i tried a few lines of code and went through a loads of failures. The last error I get is an NPE because i try to access the array returned by getUuids().
I also tried to connect the app to my airPods and everything worked well.
I am at minSdk 27 and targetSdk 31
All bluetooth permissions (bluetooth, bluetooth_admin) are granted.
the fact is, the laser thing requires an app to work and i wonder if the constructor could have blocked some functionalities. if so, i'll look to buy another one from another brand, if someone could provide me a link to buy a device working for my app.
Here's my bluetooth connect code (pretty generic I guess)
I also tried the static UUID suggested in this post but i now get this socket error which (i think) mean the uuid's not working either:
BluetoothAdapter blueAdapter = BluetoothAdapter.getDefaultAdapter();
if (blueAdapter != null) {
if (blueAdapter.isEnabled()) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH) != PackageManager.PERMISSION_GRANTED) {
Const.requestAllAppPermissions(this);
return;
}
Set<BluetoothDevice> bondedDevices = blueAdapter.getBondedDevices();
if (bondedDevices.size() > 0) {
Object[] devices = bondedDevices.toArray();
BluetoothDevice device = (BluetoothDevice) devices[0];
System.out.println(device.getName());
if (device.fetchUuidsWithSdp()) {
ParcelUuid[] uuids = device.getUuids();
BluetoothSocket socket = null;
try {
//socket = device.createRfcommSocketToServiceRecord(uuids[0].getUuid());
socket = device.createRfcommSocketToServiceRecord(
UUID.fromString("00001101-0000-1000-8000-00805f9b54fb"));
socket.connect();
} catch (IOException e) {
e.printStackTrace();
}
}
//outputStream = socket.getOutputStream();
// inStream = socket.getInputStream();
} else {
}
} else {
System.out.println("bluetooth disabled");
}
} else {
System.out.println("No bluetooth built-in");
}
here's the static UUID stacktrace:
W/BluetoothAdapter: getBluetoothService() called with no BluetoothManagerCallback
W/System.err: java.io.IOException: read failed, socket might closed or timeout, read ret: -1
W/System.err: at android.bluetooth.BluetoothSocket.readAll(BluetoothSocket.java:920)
W/System.err: at android.bluetooth.BluetoothSocket.readInt(BluetoothSocket.java:934)
W/System.err: at android.bluetooth.BluetoothSocket.connect(BluetoothSocket.java:494)
W/System.err: at com.adici.activities.PlanActivity.lambda$defButton$13$com-adici-activities-PlanActivity(PlanActivity.java:409)
W/System.err: at com.adici.activities.PlanActivity$$ExternalSyntheticLambda10.onClick(Unknown Source:2)
W/System.err: at android.view.View.performClick(View.java:7346)
W/System.err: at android.view.View.performClickInternal(View.java:7312)
W/System.err: at android.view.View.access$3200(View.java:846)
W/System.err: at android.view.View$PerformClick.run(View.java:27794)
W/System.err: at android.os.Handler.handleCallback(Handler.java:873)
W/System.err: at android.os.Handler.dispatchMessage(Handler.java:99)
W/System.err: at android.os.Looper.loop(Looper.java:214)
W/System.err: at android.app.ActivityThread.main(ActivityThread.java:7100)
W/System.err: at java.lang.reflect.Method.invoke(Native Method)
W/System.err: at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:494)
W/System.err: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:964)
I'm open to any suggestion
Looking at the user manual for the Leica DISTO D2 it states the device uses Bluetooth Smart, also known as Bluetooth Low Energy (BLE). You won't be able to connect to it using Bluetooth Sockets (Bluetooth Classic).
Please follow the Android documentation on BLE to develop your app. To debug the connection beforehand, please install a generic BLE scanner such as nRF Connect and investigate the services and characteristics the device offers.

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.

On some phones there is a connection error

I create applications for android and my application connects to a database.
Not waiting for two smartphones pops up when connecting to the database .
finally tested phones work without a problem. Both phones have versions
4.2.2 Android .
Code:
import android.annotation.SuppressLint;
import android.os.StrictMode;
import android.util.Log;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class Database {
String ip,db,DBUserNameStr,DBPasswordStr;
#SuppressLint("NewApi")
public Connection connectionclasss()
{
// Declaring Server ip, username, database name and password
ip = "123.123.123.123:20833";
db = "top";
DBUserNameStr = "userp";
DBPasswordStr = "secret";
// Declaring Server ip, username, database name and password
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
java.sql.Connection connection = null;
String ConnectionURL = null;
try
{
Class.forName("net.sourceforge.jtds.jdbc.Driver");
ConnectionURL = "jdbc:jtds:sqlserver://" + ip +";databaseName="+ db + ";user=" + DBUserNameStr+ ";password=" + DBPasswordStr + ";";
connection = DriverManager.getConnection(ConnectionURL);
}
catch (SQLException se)
{
Log.e("error here 1 : ", se.getMessage());
}
catch (ClassNotFoundException e)
{
Log.e("error here 2 : ", e.getMessage());
}
catch (Exception e)
{
Log.e("error here 3 : ", e.getMessage());
}
return connection;
}
}
The application is crash on the ruler :
connection = DriverManager.getConnection(ConnectionURL);
Log :
04-04 08:58:03.959 8401-8401/com.example.verdent E/error here 1 :: Network error IOException: failed to connect to /12.123.133.123(port 20833): connect failed: ENETUNREACH (Network is unreachable)
--------- beginning of crash
04-04 08:58:03.965 8401-8401/com.example.verdent E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.verdent, PID: 8401
java.lang.IllegalStateException: Could not execute method for android:onClick
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:389)
at android.view.View.performClick(View.java:5280)
at android.view.View$PerformClick.run(View.java:21768)
at android.os.Handler.handleCallback(Handler.java:815)
at android.os.Handler.dispatchMessage(Handler.java:104)
at android.os.Looper.loop(Looper.java:207)
at android.app.ActivityThread.main(ActivityThread.java:5917)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:888)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:749)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:384)
at android.view.View.performClick(View.java:5280) 
at android.view.View$PerformClick.run(View.java:21768) 
at android.os.Handler.handleCallback(Handler.java:815) 
at android.os.Handler.dispatchMessage(Handler.java:104) 
at android.os.Looper.loop(Looper.java:207) 
at android.app.ActivityThread.main(ActivityThread.java:5917) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:888) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:749) 
Caused by: java.lang.NullPointerException: Attempt to invoke interface method 'java.sql.Statement java.sql.Connection.createStatement()' on a null object reference
at com.example.verdent.MainActivity.ChcekDate(MainActivity.java:56)
at com.example.verdent.MainActivity.DownloandData(MainActivity.java:43)
at java.lang.reflect.Method.invoke(Native Method) 
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:384) 
at android.view.View.performClick(View.java:5280) 
at android.view.View$PerformClick.run(View.java:21768) 
at android.os.Handler.handleCallback(Handler.java:815) 
at android.os.Handler.dispatchMessage(Handler.java:104) 
at android.os.Looper.loop(Looper.java:207) 
at android.app.ActivityThread.main(ActivityThread.java:5917) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:888) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:749) 
04-04 08:58:03.970 1199-2287/? E/WindowManager: Unknown window type: 1000
Does anyone have an idea why the application turns off on here?

Android http connection refused

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.

Categories