I have this class that I'm using for detecting in every Activity if there is internet connection. My problem is that I don't want to loop every time over the AsyncTask , because I got a problem in my progressDialog when I change the context. This is my class:
public class InternetConnection {
public Boolean isInternetPresent;
public ConnectionDetector cd;
public Context con;
public ProgressDialog progressBar;
public InternetConnection () {
this.isInternetPresent = false;
}
public void hay_internet(){
new Async().execute();
}
public void cambiar_context(Context c) {
this.con = c;
this.cd = new ConnectionDetector(c);
progressBar=new ProgressDialog(con);
progressBar.setCancelable(false);
progressBar.setMessage("Buscando conexión de internet");
progressBar.setTitle("Conectando ...");
progressBar.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressBar.setProgress(0);
}
class Async extends AsyncTask<String, Integer, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
isInternetPresent = cd.isConnectingToInternet();
if(!isInternetPresent) {
progressBar.show();
}
}
#Override
protected String doInBackground(String... params) {
while(!isInternetPresent){
isInternetPresent = cd.isConnectingToInternet();
}
return null;
}
#Override
protected void onPostExecute(String file_url) {
progressBar.dismiss();
new Async().execute();
}
}
}
How can I fix this loop, so I can stop calling everytime the AsyncTask.
use the ConnectivityManager to check if there is a network connection available.
for example i use this method in my apps:
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager=(ConnectivityManager)ctx.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
that method is to check if there is a connection available.
if you want to get notified when the connection status changes (for example wifi is lost) you should use a broadcast receiver.
public class NetworkStateChangeReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = cm.getActiveNetworkInfo();
if (info != null) {
if (info.isConnected()) {
// you got a connection! tell your user!
}
}
}
}
and you need to register this broadcast receiver in your manifest:
<receiver android:name=".receiver.NetworkStateChangeReceiver">
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE"/>
</intent-filter>
</receiver>
best is you check out the official android example:
http://developer.android.com/training/monitoring-device-state/connectivity-monitoring.html
Related
I build the dialogue box for my android app. Its working well, but i encountered some issues related to the dialogue box.
(1) I want when internet connection or WiFi get connected. automatically dialogue box get disappeared.
(2) In middle of the app is running if internet connection get lost. dialogue box again appears automatically.
if (!isConnected(Dashboard.this)) buildDialog(Dashboard.this).show();
else {
setContentView(R.layout.activity_dashboard);
}
public boolean isConnected(Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netinfo = cm.getActiveNetworkInfo();
if (netinfo != null && netinfo.isConnectedOrConnecting()) {
android.net.NetworkInfo wifi = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
android.net.NetworkInfo mobile = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
if ((mobile != null && mobile.isConnectedOrConnecting()) || (wifi != null && wifi.isConnectedOrConnecting()))
return true;
else return false;
} else
return false;
}
public AlertDialog.Builder buildDialog(Context c) {
AlertDialog.Builder builder = new AlertDialog.Builder(c);
builder.setTitle("No Internet Connection");
builder.setMessage("You need to have Mobile Data or WiFi to access this. Press OK to Exit");
builder.setCancelable(false);
builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Dashboard.super.onBackPressed();
}
});
return builder;
}
Use properties builder.setCancelable(false); in your aleart dailog
Put this line out of the alert dialog code
alertDialog.setCancelable(false);
To automatically get internet connectivity events try setting up a network change listener. Here is a sample:
/**
* Broadcast receiver that detects receives notification when change in internet connection to alert when there is no Internet.
*/
public class NetworkChangeReceiver extends BroadcastReceiver {
private NetworkChangeListener mListener;
public NetworkChangeReceiver(NetworkChangeListener listener) {
mListener = listener;
}
#Override
public void onReceive(final Context context, #NonNull final Intent intent) {
if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = connectivityManager.getActiveNetworkInfo();
boolean connected = activeNetwork != null && activeNetwork.isConnected();
mListener.onNetworkConnectedStateChanged(connected);
}
}
public interface NetworkChangeListener {
void onNetworkConnectedStateChanged(boolean connected);
}
}
You then register the listener in your Activity or Fragment
#Override
public void onStart() {
super.onStart();
if (mNetworkChangeReceiver == null) {
mNetworkChangeReceiver = new NetworkChangeReceiver(this);
getContext().registerReceiver(mNetworkChangeReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
}
}
Then show / dismiss your dialog on network connected state changed
#Override
public void onNetworkConnectedStateChanged(boolean connected) {
if (connected) {
//dismiss dialog
} else {
//show dialog
}
}
You have to setCancelable == false for stop tounching outside of dialog.
In Your case You have to put like this in your AlertDialog.Builder after setMessage
builder.setCancelable(false);
and Use this functionality for User that on Backpress button You have to setCancelable == true
for that You have to write code in onBackPressed like this :-
builder.setCancelable(true);
You need add Broadcast receiver to get connectivity status.
Then you need to keep builder global.
private AlertDialog.Builder builder;
Just create a BroadcastReceiver to track your internet connectivity
first, create a NetworkChangeReceiver class like this
public class NetworkChangeReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
try {
if (isOnline(context)) {
//show dialog when internet on
dialogHome(true);
Log.e("pradeep", "Online Connect Internet ");
} else {
//hide dialog when internet off
dialogHome(false);
Log.e("pradeep", "Connectivity Failure !!");
}
} catch (NullPointerException e) {
e.printStackTrace();
Log.i(getClass().getName(), "exceptional " + e.toString());
}
}
public boolean isOnline(Context context) {
try {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
//should check null because in airplane mode it will be null
return (netInfo != null && netInfo.isConnected());
} catch (NullPointerException e) {
e.printStackTrace();
return false;
}
}
}
after that just add below code in application tag which is located in AndroidMenifest.xml
<receiver android:name=".utils.NetworkChangeReceiver">
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
</intent-filter>
</receiver>
Final step
just create your BroadcastReceiver instance in your activity where you check the internet activity
private BroadcastReceiver mNetworkReceiver;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
//init broadcast receiver
mNetworkReceiver = new NetworkChangeReceiver();
}
#Override
protected void onResume() {
super.onResume();
if (((NetworkChangeReceiver) mNetworkReceiver).isOnline(mContext)) {
} else {
registerNetworkBroadcastForNougat();
}
}
private void registerNetworkBroadcastForNougat() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
try {
registerReceiver(mNetworkReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
} catch (Exception e) {
Log.i(getClass().getName(), "easdfdf" + e.toString());
}
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
try {
registerReceiver(mNetworkReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
} catch (Exception e) {
Log.i(getClass().getName(), "easdfdfdd" + e.toString());
}
}
}
protected void unregisterNetworkChanges() {
try {
unregisterReceiver(mNetworkReceiver);
} catch (IllegalArgumentException e) {
e.printStackTrace();
}
}
#Override
public void onDestroy() {
super.onDestroy();
unregisterNetworkChanges();
}
whenever internet connection changes BroadcastReceiver call onReceive Method.
Hope helpful for you...
I am getting error:-
"java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.juhi_gupta.pizza_corner/com.example.juhi_gupta.pizza_corner.SplashScreen}: java.lang.InstantiationException: java.lang.Class has no zero argument constructor"
What's going wrong in my code? I am new to Asynctask.
public class SplashScreen extends Activity {
Context context;
SplashScreen(Context context)
{
this.context = context;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
int SPLASH_TIME_OUT = 3000;
new Handler().postDelayed(new Runnable() {
/*
* Showing splash screen with a timer. This will be useful when you
* want to show case your app logo / company
*/
#Override
public void run() {
// This method will be executed once the timer is over
// Start your app main activity
Intent i = new Intent(SplashScreen.this, LoginActivity.class);
startActivity(i);
overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
// close this activity
finish();
}
}, SPLASH_TIME_OUT);
if (isNetworkAvailable()) {
new CheckInternetAsyncTask(getApplicationContext()).execute();
}
else {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setTitle("No Internet Connection");
alertDialogBuilder.setPositiveButton("yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
Toast.makeText(getApplicationContext(), "Please check your internet connection and try again", Toast.LENGTH_SHORT).show();
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
}
public boolean isNetworkAvailable() {
ConnectivityManager cm = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = cm.getActiveNetworkInfo();
return networkInfo != null && networkInfo.isConnected();
}
#SuppressLint("StaticFieldLeak")
class CheckInternetAsyncTask extends AsyncTask<Void, Integer, Boolean> {
private Context context;
CheckInternetAsyncTask(Context context) {
this.context = context;
}
#Override
protected Boolean doInBackground(Void... params) {
ConnectivityManager cm =
(ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
assert cm != null;
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean isConnected = activeNetwork != null &&
activeNetwork.isConnected();
if (isConnected) {
try {
HttpURLConnection urlc = (HttpURLConnection)
(new URL("http://clients3.google.com/generate_204")
.openConnection());
urlc.setRequestProperty("User-Agent", "Android");
urlc.setRequestProperty("Connection", "close");
urlc.setConnectTimeout(1500);
urlc.connect();
if (urlc.getResponseCode() == 204 &&
urlc.getContentLength() == 0)
return true;
} catch (IOException e) {
Log.e("TAG", "Error checking internet connection", e);
Toast.makeText(getApplicationContext(), "Error checking internet connection", Toast.LENGTH_LONG).show();
return false;
}
} else {
Log.d("TAG", "No network available!");
Toast.makeText(getApplicationContext(), "No network available!", Toast.LENGTH_LONG).show();
return false;
}
return null;
}
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
Log.d("TAG", "result" + result);
}
}
}
And my Manifest.xml file:-
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.juhi_gupta.pizza_corner">
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.SEND_SMS"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme" >
<!-- Splash screen -->
<activity
android:name="com.example.juhi_gupta.pizza_corner.SplashScreen"
android:label="#string/app_name"
android:screenOrientation="portrait"
android:theme="#android:style/Theme.Black.NoTitleBar" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
Solution: There are 2 corrections:
1. Remove this:
SplashScreen(Context context)
{
this.context = context;
}
Write this instead, inside your onCreate() just after the line setContentView(...):
this.context = SplashScreen.this;
2. Instead of this:
new CheckInternetAsyncTask(getApplicationContext()).execute();
Write this:
new CheckInternetAsyncTask(this.context).execute();
Then:
Remove this below mentioned code from your onCreate(..) and try disconnecting your wifi and run the app, It will show.
int SPLASH_TIME_OUT = 3000;
new Handler().postDelayed(new Runnable() {
/*
* Showing splash screen with a timer. This will be useful when you
* want to show case your app logo / company
*/
#Override
public void run() {
// This method will be executed once the timer is over
// Start your app main activity
Intent i = new Intent(SplashScreen.this, LoginActivity.class);
startActivity(i);
overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
// close this activity
finish();
}
}, SPLASH_TIME_OUT);
Write The above code inside onPostExecute(...):
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
Log.d("TAG", "result" + result);
...... (Over Here)
}
Hope it works.
Mission is to check if the mobile is connected on internet or not. I have problem.
It shows "Connected" even when wifi is off. Here is my class.
public class InterneProvjera {
Context context;
#SuppressLint("MissingPermission")
public InterneProvjera(Context context){
this.context = context;
}
public boolean isNetworkAvailable() {
ConnectivityManager connectivity = (ConnectivityManager) this.context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity != null) {
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null) {
for (NetworkInfo i: info) {
if (i.getState() == NetworkInfo.State.CONNECTED)
return true;
}
}
}
return false;
}
}
And here is in the main activity :
InterneProvjera interneProvjera = new InterneProvjera(this);
String tKonekcija = (interneProvjera.isNetworkAvailable()) ? "Connected" : "No connection";
txtIspis.setText(tKonekcija);
Sorry if its trivial question im new in android programming.
Ps: is there any Connection listener and how to check internet signal strength (3G, 4G, wifi)?
You should use BroadcastReceiver to check the network status using ConnectivityManager
Below is the code to check in your activity if network is connected or not. If connected, it will show you name of network in Toast:
ConnectivityStatusReceiver.java
public class ConnectivityStatusReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
final ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connMgr.getActiveNetworkInfo();
if (activeNetworkInfo != null) {
Toast.makeText(context, activeNetworkInfo.getTypeName() + " connected", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(context, "No Internet or Network connection available", Toast.LENGTH_LONG).show();
}
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
ConnectivityStatusReceiver connectivityStatusReceiver;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
connectivityStatusReceiver = new ConnectivityStatusReceiver();
}
#Override
protected void onResume() {
super.onResume();
IntentFilter intentFilter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
registerReceiver(connectivityStatusReceiver, intentFilter);
}
#Override
protected void onDestroy() {
super.onDestroy();
if (connectivityStatusReceiver != null) {
// unregister receiver
unregisterReceiver(connectivityStatusReceiver);
}
}
}
found a code that will check internet connectivity here
but I do not have any idea how to implement or call this class or method as I am still studying android programming using android studio.
Please see my code below and kindly let me know how to arrange it in a way that it will fire on application launch plus including the toast message stating that it is connected or not..
package com.example.enan.checkinternetconnection;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "";
private static final String LOG_TAG = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
}
public boolean hasActiveInternetConnection(Context context) {
if (isNetworkAvailable(context)) {
try {
HttpURLConnection urlc = (HttpURLConnection) (new URL("http://www.google.com").openConnection());
urlc.setRequestProperty("User-Agent", "Test");
urlc.setRequestProperty("Connection", "close");
urlc.setConnectTimeout(1500);
urlc.connect();
return (urlc.getResponseCode() == 200);
} catch (IOException e) {
Log.e(LOG_TAG, "Error checking internet connection", e);
}
} else {
Log.d(LOG_TAG, "No network available!");
}
return false;
}
public boolean isNetworkAvailable(Context context) {
ConnectivityManager connectivityManager
= (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null;
}
}
First of all, calling a web page and waiting for its response is NOT a good option when trying to determine whether there is or is not an available internet connection.
There are android built-in helper methods to check for connectivity such as:
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager
= (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
Also, if what you want is to check the connectivity on application's launch, the best option is to create a new class that extends from android.app.Application and override the onCreate method as follows:
public class YourApplication extends android.app.Application {
#Override
public void onCreate() {
super.onCreate();
if (isNetworkAvailable()) {
//Connected to the Internet
} else {
//Not connected
}
}
}
Full code would look like this:
public class YourApplication extends android.app.Application {
#Override
public void onCreate() {
super.onCreate();
if (isNetworkAvailable()) {
//Connected to the Internet
} else {
//Not connected
}
}
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
}
Finally, on your AndroidManifest.xml set the name as android:name=".YourApplication"
<application
android:name=".YourApplication"
... >
</application>
first add this permision to your manifest:
<uses-permission android:name="android.permission.INTERNET" />
Then in your main Activity innitiaize the connectivity manager:
private boolean connected(){
ConnectivityManager connectivityManager=(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo !=null && activeNetworkInfo.isConnected();
}
And in your onCreate(Main Activities oncreate)check if user is connected.For the UI message,you can always add your own custom snackbar or dialog.
if(connected()){
Log.i("TRUE","User is connected");
}else{
Log.i("TRUE","User is not connected");
}
Call hasActiveInternetConnection(getApplicationContext()); inside onCreate method.
Im using Zxing for scanning Qr-codes and https://github.com/pedant/sweet-alert-dialog for some pretty dialogs. I check if i have internet connection when i launch the app and each time when i do a scan. My problem is that the scanner stops after 1st scan , it shows dialog popup , i press ok button and stops the scanning process , but camera is still showing. Do i have any mistakes in my code or logic ???
It doesnt enter second time in handleResult
public class MainActivity extends Activity implements ZXingScannerView.ResultHandler {
private SweetAlertDialog pDialog;
private ZXingScannerView mScannerView;
#Override
public void onCreate(Bundle state) {
super.onCreate(state);
mScannerView = new ZXingScannerView(this); // Programmatically initialize the scanner view
setContentView(mScannerView); // Set the scanner view as the content view
pDialog = new SweetAlertDialog(this, SweetAlertDialog.SUCCESS_TYPE);
if (!Utils.isNetworkAvailable(MainActivity.this)) {
alertBadNetworkConnection("Network connection error", "Please check your internet connection");
}
}
private void alertBadNetworkConnection(String title, String context) {
pDialog.changeAlertType(SweetAlertDialog.ERROR_TYPE);
pDialog.setTitleText(title)
.setContentText(context)
.setConfirmText("OK")
.setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
#Override
public void onClick(SweetAlertDialog sweetAlertDialog) {
pDialog.dismiss();
mScannerView.startCamera();
}
})
.show()
;
}
private void alertSuccess(String title, String context) {
pDialog.changeAlertType(SweetAlertDialog.SUCCESS_TYPE);
pDialog.setTitleText(title)
.setContentText(context)
.setConfirmText("OK")
.setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
#Override
public void onClick(SweetAlertDialog sweetAlertDialog) {
pDialog.dismiss();
mScannerView.startCamera();
}
})
.show();
}
#Override
public void onResume() {
super.onResume();
mScannerView.setResultHandler(this); // Register ourselves as a handler for scan results.
mScannerView.startCamera(); // Start camera on resume
}
#Override
public void onPause() {
super.onPause();
mScannerView.stopCamera(); // Stop camera on pause
}
#Override
public void handleResult(Result result) {
if (!Utils.isNetworkAvailable(MainActivity.this)) {
alertBadNetworkConnection("Network connection error", "Please check your internet connection");
} else {
alertSuccess("Good job!", result.getText());
}
}
}
Here is the method that checks internet connection
public static boolean isNetworkAvailable(Context context) {
ConnectivityManager connectivityManager
= (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
DO the following in your handleResult() method
// If you would like to resume scanning, call this method below:
mScannerView.resumeCameraPreview(this);
Example :
#Override
public void handleResult(Result result) {
if (!Utils.isNetworkAvailable(MainActivity.this)) {
alertBadNetworkConnection("Network connection error", "Please check your internet connection");
} else {
alertSuccess("Good job!", result.getText());
// If you would like to resume scanning, call this method below:
mScannerView.resumeCameraPreview(this);
}
}