I am trying to check server connectivity on splash screen. I want make if server is online then I want download data else if server does not ping, I need to show error. I am trying to user function for server status check like below
static public boolean isServerReachable(Context context) {
ConnectivityManager connMan = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = connMan.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnected()) {
try {
URL urlServer = new URL("your server url");
HttpURLConnection urlConn = (HttpURLConnection) urlServer.openConnection();
urlConn.setConnectTimeout(3000); //<- 3Seconds Timeout
urlConn.connect();
if (urlConn.getResponseCode() == 200) {
return true;
} else {
return false;
}
} catch (MalformedURLException e1) {
return false;
} catch (IOException e) {
return false;
}
}
return false;
}
but I do not know how can I use this method. I am trying like below code
boolean isServerReachable;
if (isServerReachable=true){
}
else
{
}
But this showing me that boolean isServerReachable; is never used.
if I try like this
boolean isServerReachable;
if(isServerReachable(SplashsActivity.this)){
if (isServerReachable==true){
}
else {
}
}
its showing variable isServerReachable might not been initialized
Can someone please help me what's I am missing ? Maybe this is very simple and foolish question but I am learning yet, so please help me. Thanks
If boolean isServerReachable is a local variables then it don't get default values, they have to be initialized. ... Local variables should be initialized with value before using it .Something like this :boolean isServerReachable = false The compiler complains because local variables are not assigned any value by default.
boolean isServerReachable = false;
if(isServerReachable(SplashsActivity.this)){
if (isServerReachable==true){
}
else {
}
}
It will fix that its showing variable isServerReachable might not been initialized issue.
You can call the method inside if condition -
if(isServerReachable(context_value))
{
}
else
{
}
The code you are currently using (given below) doesn't call the method. It actually assign true value to variable - isServerReachable, which is never used in 'if'or 'else' block
boolean isServerReachable;
if (isServerReachable=true){
}
else
{
}
Related
I am writing an android application which interacts with a sensor using bluetooth and obtains temperature values. I am doing this by calling connectGatt() which is asynchronous and calls a callback once the connection is established. The problem I am facing is that my code has to wait until the connection gets established.
This is the implementation of the method which is being used in the code below.
public boolean connect(final String address)
{
Log.v(LOG_TAG,"IN CONNECT METHOD"+Thread.currentThread().getName());
if(btadapter == null || address == null)
{
Log.v(LOG_TAG,"Unable to get Bluetooth Adapter or Address is not valid");
return false;
}
if(address != null && address.equals(btaddress) && btgatt != null)
{
Log.v(LOG_TAG,"Trying to connect to a bt gatt profile directly");
boolean result = btgatt.connect();
if(result)
return true;
return false;
}
btdevice = btadapter.getRemoteDevice(address);
if(btdevice == null)
{
Log.v(LOG_TAG,"Could not find device.");
return false;
}
btgatt = btdevice.connectGatt(this,false,btgattcallback);
Log.v(LOG_TAG,btgatt.toString());
btaddress = address;
Log.v(LOG_TAG,"Connecting to the device");
btConnectionState = STATE_CONNECTING;
return true;
}
Currently I could solve this problem by writing the following code in a handler thread as I don't want to block the UI thread while waiting for the callback. But I am not convinced with the approach.
if(mLocation != null)
{
connect(btaddress); // Method encapsulates calls to connectGatt method.
while (btConnectionState != STATE_CONNECTED) {
continue;
}
while (!services_discovered) {
continue;
}
//Other Code
I feel that there could be better ways of solving this but couldn't find any on the web. I saw a couple of answers using CountDownLatch and Semaphores but I didn't understand them clearly.
Can anyone help me with understanding how to handle situations like these?
Thank you.
I have call receiver which I want to display dialog on incoming call only. For that I have created a global Boolean variable and trying to changes its value to true in ringing state. But when call disconnects, code always picks default value of Boolean not the updated value given in ringing state. The variable is num. Why it always give false value though its value getting true in ringing state only. Here is the code:
public class phonerece extends BroadcastReceiver{
private Boolean num = false;
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_NEW_OUTGOING_CALL)) {
//some task here
}
} else if (extraState != null) {
if (extraState.equals(TelephonyManager.EXTRA_STATE_OFFHOOK)) {
//task
} else if (extraState
.equals(TelephonyManager.EXTRA_STATE_IDLE)) {
if (num) {
phoneNumber = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);
//call dialog }
}
} else if (extraState.equals(TelephonyManager.EXTRA_STATE_RINGING)) {
if (checknumber() != null) {
Log.e("Nummber", "found");
} else {
Log.e("Number", "Not Found");
num = true;
}
}
}
}
public String checknumber() {
String res = null;
try {
ContentResolver resolver = context.getContentResolver();
Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(phoneNumber));
Cursor c = resolver.query(uri, new String[]{ContactsContract.PhoneLookup.DISPLAY_NAME}, null, null, null);
if (c != null) { // cursor not null means number is found contactsTable
if (c.moveToFirst()) { // so now find the contact Name
res = c.getString(c.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
}
c.close();
}
} catch (Exception ex) {
/* Ignore */
}
return res;
}
}
You should use static variables (private static num = false) or save your variable in SharedPreferences (it's better), because BroadcastReceivers are not saved between broadcasts. Every broadcast will create a new instance of the BroadcastReceiver, at least if registered automatically via the manifest.
(Your code snippet looks broken, the num variable is missing its type? This answer assumes its type is boolean.)
This sounds like a multithreading problem. Threads in java may cache values of variables, because synchronizing through the main memory is more expensive. You can force the synchronization by flagging the field in question as volatile. This keyword is explained here.
When a field is flagged as volatile, Threads may not cache its value, and all modifications to the variable become visible to all other Threads.
private volatile boolean num = false;
I am using Volley for webcalls in my application and everything is working fine and smooth except one state in which somehow my device is not getting Network Connection but checking connection via code is returning true using below code.
public static boolean isNetworkAvailable() {
ConnectivityManager connectivityManager = SessionApplication.getConnectivityManager();
if(connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.CONNECTED ||
connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.CONNECTED) {
//we are connected to a network
return true;
}
else
return false;
}
Instead of returning network state false using above code My volley web calls returning me this exception "handle com.android.volley.NoConnectionError: java.net.UnknownHostException".
I checked my internet connection by opening browser in my device and found it is also not working. So i am okay with application behavior but still i need to handle such condition because this is not user friendly user should be prompted a dialog that "Check Your Internet Connection!".
This should be a common issues in Android could any body please help me to give me best approach to handle such cases. Thanks in advance.
Network state is :
This exception indicates the problem in connectivity. In fact you can show some dialog about the connectivity. Overriding the onErrorResponse(VolleyError error) you can do like this -
public void onErrorResponse(VolleyError error) {
Log.d(TAG, error.toString());
if (error instanceof NoConnectionError)
new AlertDialog.Builder(this).setMessage(
"Unable to connect to the server! Please ensure your internet is working!").show();
}
Try this method might help
public boolean isConnectedToInternet(){
connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivityManager != null){
NetworkInfo[] info = connectivityManager.getAllNetworkInfo();
if (info != null){
for (int i = 0; i < info.length; i++){
if (info[i].getState() == NetworkInfo.State.CONNECTED){
return true;
}
}
}
}
return false;
}
Does anyone know how to handle a ConnectTimeoutException? i'm posting variables to a url using AsyncTask but my internet connection is shocking so i'm recieving null data back because of a ConnectTimeoutException. What are the best ways to handle this for example if time out occurs try run again etc i have not had this problem before so don't have a clue how to handle but i feel it needs handling to improve user experience. so any ideas?
You could use an Handler to let your Activity know you got a ConnectTimeoutException
Catch this exception in your AsyncTask and send a message to your Handler (then do whatever you want)
Just for information, AsyncTask aren't designed for long running operation, if so you should use a Thread
this is how you shoud check for the network status
ConnectivityManager connMgr = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
//execute your AsyncTask method
} else {
//maketoast..."No network connection available"
}
Make a separate class called Activity helper, and implement it in your async task for any class that you make in which requires a webservice call.
public class ActivityHelper {
public static final String NETWORK_CONNECTION_MESSAGE = "No Network Connection. Please make sure you have a Network Connection.";
public static boolean isNetworkPresent(Context applicationContext){
boolean hasService = false;
NetworkInfo info=(NetworkInfo)( (ConnectivityManager)applicationContext.getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();
hasService = (info==null || !info.isConnected())?false:true;
return hasService;
}
}
call Activity Helper in "doInBackground" Method kinda like this..
private class YourAsyncTask extends AsyncTask<String, Void, String> {
Message message = new Message();
String type = "";
protected void onPreExecute() {
ActivityHelper.onUserInteraction(getApplicationContext());
dialog = ProgressDialog.show(LocationType.this,
"Connecting to server", "Please wait...", true, true);
dialog.setCancelable(false);
}
protected String doInBackground(final String... args) {
try {
if(!ActivityHelper.isNetworkPresent(getApplicationContext())){
message.what = ActivityHelper.NONETWORKCONNECTION;
return null;
}
} catch (Exception e) {
Log.e(this.getClass().getName(),
"Exception Message");
}
return null;
}
I'm performing a check of internet access in a program. I'd like to do a function to that cause this checking need to often happens... But my original function have to return while it because the screen need to refresh. This is what I have:
public void isOnline(Runnable Rcallback, Ccallback) {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
boolean checkState = cm.getActiveNetworkInfo().isConnectedOrConnecting();
if(checkState) {
isOnline = true;
if(Rcallback != null) Rcallback.run();
if(Ccallback != null) set;}
else {
isOnline = false;
Toast.makeText(gMain.this, R.string.nointernet, Toast.LENGTH_LONG).show();
Handler reTry = new Handler();
reTry.postDelayed(new Runnable() {
#Override
public void run() {
isOnline(callback) ;
}
},3000);
}
}
My really problem is in Ccallback that it's a function to call back when the program turns online. I don't know how to declare a function as a "variable". Any ideas?
You should setup a listener using the Observer Pattern. This will allow you to tell anyone marked as a listener (likely your UI) that you have done something. In this case, something is connected.
One thing to keep in mind while doing this is to ensure that while doing things on the UI, you are on the Event Thread.