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);
}
}
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...
this is my base activity that extends class activity. I make my other activities extend this base class:
public abstract class Base extends Activity {
private BroadcastReceiver netStateReceiver;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(getLayoutResourceId());
}
protected abstract int getLayoutResourceId();
#Override
protected void onPause() {
if (netStateReceiver != null) {
unregisterReceiver(netStateReceiver);
netStateReceiver = null;
}
super.onPause();
}
#Override
protected void onResume() {
if (netStateReceiver == null) {
netStateReceiver = new BroadcastReceiver() {
#Override
public void onReceive(final Context context, Intent intent) {
final Dialog offline = new Dialog(context, android.R.style.Theme_Light);
//A change occurred in connection state. Check whether user has been become online or offline:
if (!CheckNet()) {
//User became offline (show offline dialog):
offline.setContentView(R.layout.activity_offline);
offline.setTitle("offline");
offline.getWindow().setBackgroundDrawableResource(R.color.transparent);
offline.show();
final Button retry = (Button) offline.findViewById(R.id.button6);
retry.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (CheckNet()) {
offline.dismiss();
}
}
});
}
else {
//User became online (dismiss offline dialog):
if (offline.isShowing()) {
offline.dismiss();
}
}
}
};
registerReceiver(netStateReceiver, new IntentFilter(Values.CONNECTIVITY_RECEIVER_ACTION));
}
super.onResume();
}
private boolean CheckNet() {
final ConnectivityManager conMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
final NetworkInfo activeNetwork = conMgr.getActiveNetworkInfo();
return (activeNetwork != null && activeNetwork.isConnectedOrConnecting());
}
}
As you see in code I have registered a receiver for checking connectivity status.
I want when user becomes offline a dialog be shown to user and notify him that he is offline and should become online to continue. This part works good.
I also want when that dialog is showing and in the moment user becomes online this dialog be dismissed, but this part doesn't work and dialog stays on the display.
What's the problem, how can I dismiss the dialog?
You create a new dialog on every broadcast instead of using the dialog you already created before.
Make the dialog variable a member variable of the activity class, then it should work.
private Dialog offline;
#Override
protected void onResume() {
if (netStateReceiver == null) {
netStateReceiver = new BroadcastReceiver() {
#Override
public void onReceive(final Context context, Intent intent) {
if (!CheckNet()) {
if(offline==null || !offline.isShowing()){
offline = new Dialog(context, android.R.style.Theme_Light);
}
...
} else {
//User became online (dismiss offline dialog):
if (offline!=null && offline.isShowing()) {
offline.dismiss();
}
}
Make it global access to your dialog object reference :
final Dialog offline = new Dialog(context, android.R.style.Theme_Light);
Then you will able to close your dialog.
You are creating a new dialog everytime you receive a broadcast, so the dialog you dismissed is a whole different dialog than the one used to show "you are currently offline".
Try putting your "offline" dialog in the activity instead of within the onReceive callback.
A simple example would be:
public abstract class Base extends Activity {
private BroadcastReceiver netStateReceiver;
final Dialog offline;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(getLayoutResourceId());
// You create the dialog here instead within the onReceive callback
offline = new Dialog(this, android.R.style.Theme_Light);
offline.setContentView(R.layout.activity_offline);
offline.setTitle("offline");
offline.getWindow().setBackgroundDrawableResource(R.color.transparent);
}
#Override
protected void onResume() {
if (netStateReceiver == null) {
netStateReceiver = new BroadcastReceiver() {
#Override
public void onReceive(final Context context, Intent intent) {
if (!CheckNet()) {
// Your dialog already exists, just show it immediately
offline.show();
final Button retry = (Button) offline.findViewById(R.id.button6);
retry.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (CheckNet()) {
offline.dismiss();
}
}
});
}
else {
//User became online (dismiss offline dialog):
if (offline.isShowing()) {
offline.dismiss();
}
}
}
};
registerReceiver(netStateReceiver, new IntentFilter(Values.CONNECTIVITY_RECEIVER_ACTION));
}
super.onResume();
}
}
I am working on a project in Android Studio where I am supposed to connect two devices using Wifi-Direct.
I have managed to connect to another device with Wifi-direct. My problem is that when I close the app manually on my phone, the devices do not disconnect. How can I achieve this? I am quite new with Android Studio and java.
Here is my WifiDirectActivity class:
public class WiFiDirectActivity extends Activity implements WifiP2pManager.ChannelListener, DeviceListFragment.DeviceActionListener {
public static final String TAG = "wifidirectdemo";
private WifiP2pManager manager;
private boolean isWifiP2pEnabled = false;
private boolean retryChannel = false;
private final IntentFilter intentFilter = new IntentFilter();
private WifiP2pManager.Channel channel;
private BroadcastReceiver receiver = null;
/**
* #param isWifiP2pEnabled the isWifiP2pEnabled to set
*/
public void setIsWifiP2pEnabled(boolean isWifiP2pEnabled) {
this.isWifiP2pEnabled = isWifiP2pEnabled;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_peers);
// add necessary intent values to be matched.
intentFilter.addAction(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION);
intentFilter.addAction(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION);
intentFilter.addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION);
intentFilter.addAction(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION);
manager = (WifiP2pManager) getSystemService(Context.WIFI_P2P_SERVICE);
channel = manager.initialize(this, getMainLooper(), null);
}
/** register the BroadcastReceiver with the intent values to be matched */
#Override
public void onResume() {
super.onResume();
receiver = new WiFiDirectBroadcastReceiver(manager, channel, this);
registerReceiver(receiver, intentFilter);
if (!amConnected) {
performSearch();
}
}
#Override
public void onPause() {
super.onPause();
unregisterReceiver(receiver);
}
/**
* Remove all peers and clear all fields. This is called on
* BroadcastReceiver receiving a state change event.
*/
public void resetData() {
DeviceListFragment fragmentList = (DeviceListFragment) getFragmentManager()
.findFragmentById(R.id.frag_list);
DeviceDetailFragment fragmentDetails = (DeviceDetailFragment) getFragmentManager()
.findFragmentById(R.id.frag_detail);
if (fragmentList != null) {
fragmentList.clearPeers();
}
if (fragmentDetails != null) {
fragmentDetails.resetViews();
}
}
#Override
public void showDetails(WifiP2pDevice device) {
DeviceDetailFragment fragment = (DeviceDetailFragment) getFragmentManager()
.findFragmentById(R.id.frag_detail);
fragment.showDetails(device);
}
#Override
public void connect(WifiP2pConfig config) {
manager.connect(channel, config, new WifiP2pManager.ActionListener() {
#Override
public void onSuccess() {
// WiFiDirectBroadcastReceiver will notify us. Ignore for now.
}
#Override
public void onFailure(int reason) {
Toast.makeText(WiFiDirectActivity.this, "Connect failed. Retry.",
Toast.LENGTH_SHORT).show();
}
});
}
#Override
public void disconnect() {
final DeviceDetailFragment fragment = (DeviceDetailFragment) getFragmentManager()
.findFragmentById(R.id.frag_detail);
fragment.resetViews();
manager.removeGroup(channel, new WifiP2pManager.ActionListener() {
#Override
public void onFailure(int reasonCode) {
Log.d(TAG, "Disconnect failed. Reason :" + reasonCode);
}
#Override
public void onSuccess() {
fragment.getView().setVisibility(View.GONE);
}
});
}
#Override
public void onChannelDisconnected() {
// we will try once more
if (manager != null && !retryChannel) {
Toast.makeText(this, "Channel lost. Trying again", Toast.LENGTH_LONG).show();
resetData();
retryChannel = true;
manager.initialize(this, getMainLooper(), this);
} else {
Toast.makeText(this,
"Severe! Channel is probably lost premanently. Try Disable/Re-Enable P2P.",
Toast.LENGTH_LONG).show();
}
}
#Override
public void cancelDisconnect() {
/*
* A cancel abort request by user. Disconnect i.e. removeGroup if
* already connected. Else, request WifiP2pManager to abort the ongoing
* request
*/
if (manager != null) {
final DeviceListFragment fragment = (DeviceListFragment) getFragmentManager()
.findFragmentById(R.id.frag_list);
if (fragment.getDevice() == null
|| fragment.getDevice().status == WifiP2pDevice.CONNECTED) {
disconnect();
} else if (fragment.getDevice().status == WifiP2pDevice.AVAILABLE
|| fragment.getDevice().status == WifiP2pDevice.INVITED) {
manager.cancelConnect(channel, new WifiP2pManager.ActionListener() {
#Override
public void onSuccess() {
Toast.makeText(WiFiDirectActivity.this, "Aborting connection",
Toast.LENGTH_SHORT).show();
}
#Override
public void onFailure(int reasonCode) {
Toast.makeText(WiFiDirectActivity.this,
"Connect abort request failed. Reason Code: " + reasonCode,
Toast.LENGTH_SHORT).show();
}
});
}
}
}
private void performSearch() {
final DeviceListFragment fragment = (DeviceListFragment) getFragmentManager()
.findFragmentById(R.id.frag_list);
fragment.onInitiateDiscovery();
manager.discoverPeers(channel, new WifiP2pManager.ActionListener() {
#Override
public void onSuccess() {
Toast.makeText(WiFiDirectActivity.this, "Discovery Initiated",
Toast.LENGTH_SHORT).show();
}
#Override
public void onFailure(int reasonCode) {
Toast.makeText(WiFiDirectActivity.this, "Discovery Failed : " + reasonCode,
Toast.LENGTH_SHORT).show();
}
});
}
}
When you close the app the execution will run through onPause() callback, there you should call the disconnect() method. However, take 5 minutes of your time to understand Android's life cycle principle: https://developer.android.com/guide/components/activities/activity-lifecycle.html. It's one of the first things to learn before developing an Android app.
I'm using a simple activity (from this library) with ZXing to scan a barcode.
Everything works fine, but the transition between the MainActivity and the ScannerActivity doesn't work well. Halfway through it gets interrupted. When going back from the ScannerActivity to the MainActivity the transition works like desired. Only while loading the barcodescanner it doesn't look really good.
Do you have any idea how to fix this?
MainActivity:
private void invokeScanner() {
try {
Intent intent = new Intent(this, ScannerActivity.class);
stealFocus(et_loadInput);
startActivityForResult(intent,0);
this.overridePendingTransition(R.anim.detail_anim_up, R.anim.detail_anim_down);
} catch (Exception e){
Log.e(TAG, "couldn't open scanner");
e.printStackTrace();
openAlertDialog(Const.MSG_PROCESSING_ERROR);
}
}
ScannerActivity:
public class ScannerActivity extends AbstractTitleBarActivity implements ZXingScannerView.ResultHandler{
private ZXingScannerView mScannerView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mScannerView = new ZXingScannerView(this);
setContentView(mScannerView);
this.tv_backTitle.setText(getString(R.string.TITLE_SEARCH_VIEW));
this.tv_heading.setText("");
TextView titleClose = (TextView) findViewById(R.id.btn_close);
titleClose.setVisibility(View.VISIBLE);
titleClose.setOnClickListener(titleCloseListener);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
#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
protected boolean isBackBtnVisible() {
return false;
}
#Override
protected boolean isLogoVisible() {
return false;
}
#Override
public void handleResult(Result rawResult) {
Log.v(TAG, rawResult.getText()); // Prints scan results
Log.v(TAG, rawResult.getBarcodeFormat().toString()); // Prints the scan format (qrcode, pdf417 etc.)
MainActivity.scanVal = rawResult.toString();
MainActivity.loadVal = MainActivity.scanVal;
finish();
overridePendingTransition(R.anim.detail_anim_back_down,R.anim.detail_anim_back_up);
}
// listener for close button
protected TextView.OnClickListener titleCloseListener = new TextView.OnClickListener() {
public void onClick(View v) {
finish();
overridePendingTransition(
R.anim.detail_anim_back_down, R.anim.detail_anim_back_up);
}
};
}
I actually solved my own problem :D with this answer.
I just put the ZXingScannerView into a fragment and added a surface view with 0px height as a sibling. Now the animation works fine and the barcode scanner loads without refreshing the complete activity.
i am currently doing a project based on network connections.I am developing an app in which network connection is checked regularly.If there is no connection, a progress dialog should spin showing "No network connection" until the user himself turn the wifi on or any other kind of internet connection .After the wifi is turned on and if the app connects with wifi then the progress dialog should close and the control should pass to another activity. I have searched this in google for many times but didn't get a satisfactory answer. Below are my codes:
public class Alert extends Activity implements Runnable{
ProgressDialog pd;
WifiManager wm,wifiManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_alert);
wm = (WifiManager) getSystemService(WIFI_SERVICE);
if(!wm.isWifiEnabled()) {
pd = ProgressDialog.show(this, "Network Error!!", "Network not found.Please make sure there is presence of any kind of network connection!!");
Thread t = new Thread(this);
t.start();
}
}
#Override
protected void onResume() {
super.onResume();
if(wm.isWifiEnabled()) {
pd.dismiss();
Intent in=new Intent(Alert.this,WebPageView.class);
startActivity(in);
}
}
#Override
public void run() {
// TODO Auto-generated method stub
while(wm.getWifiState() != 3) {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
To check network connection, use ConnectivityManager class.
Add below method to your activity and call it to check network connection, if it returns true then it means network is available otherwise not.
private boolean isNetworkAvailable(Context context) {
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
Now do it in your onCreate(...) method
if(!isNetworkAvailable(Alert.this)) {
pd = ProgressDialog.show(this, "Network Error!!", "Network not found.Please make sure there is presence of any kind of network connection!!");
Thread t = new Thread(this);
t.start();
}else{
if(pd != null && pd.isShowing()){
pd.dismiss();
}
Intent in=new Intent(Alert.this,WebPageView.class);
startActivity(in);
}
Hope this will help you.
Try like this using Handler, It may work.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_alert);
wm = (WifiManager) getSystemService(WIFI_SERVICE);
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
if(!wm.isWifiEnabled()) {
runOnUiThread(new Runnable() {
public void run() {
if(pd == null)
pd = ProgressDialog.show(this, "Network Error!!", "Network not found.Please make sure there is presence of any kind of network connection!!");
}
});
}else{
runOnUiThread(new Runnable() {
public void run() {
if(pd != null)
pd.dismiss();
Intent in=new Intent(Alert.this,WebPageView.class);
startActivity(in);
}
});
}
handler.postDelayed(this, 5000); //now is every 2 minutes
}
}, 5000);
}
#Override
public void run() {
// TODO Auto-generated method stub
while(running) {
try {
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!
Log.i("Post", "Connected");
running=false;
runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
pd.dismiss();
}
});
Intent intent_service=new Intent(this, anotherActivity.class);
context.startService(intent_service);
}
}
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Put this class in your project:
public class Utility {
public static boolean isNetworkConnected(Context context){
boolean connected = false;
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
connected = (cm.getActiveNetworkInfo() != null&&cm.getActiveNetworkInfo().isAvailable() && cm
.getActiveNetworkInfo().isConnected());
return connected;
}
public static void showAlert(final Activity activity, final String message,final String title) {
AlertDialog.Builder builder = new AlertDialog.Builder(activity);
builder.setMessage(message).setTitle(title).setCancelable(false)
.setNegativeButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id){
dialog.cancel();
activity.finish();
}
});
AlertDialog alert = builder.create();
alert.show();
}
public static void showAlertValidation(final Activity activity,final String message,final String title){
AlertDialog.Builder builder = new AlertDialog.Builder(activity);
builder.setMessage(message).setTitle(title).setCancelable(false)
.setNegativeButton("OK", new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog,int id){
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
}
This class detects if your internet connection is on or not. After that in your activity, put the following code:
if(Utility.isNetworkConnected(Alert.this))
{
Intent in=new Intent(Alert.this,WebPageView.class);
startActivity(in);
}
else if(!Utility.isNetworkConnected(Alert.this))
Utility.showAlert(Alert.this,"Internet Connection Not Present.","Network Error!");
Check and see if your problem is solved or not.
Check this link,
Depends on internet state change you can call your activity.
Hope this will solve your problem