Start another activity when detected network connection - java

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

Related

How to open Wifi settings inside from a BroadcastReceiver

I am working on an Android application that could recognize if the device is connected to a Network. If not, application display an AlertDialog and give the chance to the user to go to the device settings and open the wifi.
I have create a BroadcastReceiver for this job but i dont know how i can create an AlertDialog and give the option to the user to enable the the wifi.
Here is the code of BroadcastReceiver.
public class ExampleBroadcastReceiver extends BroadcastReceiver {
#Override
public void onReceive(final Context context, Intent intent) {
if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
boolean noConnectivity = intent.getBooleanExtra(
ConnectivityManager.EXTRA_NO_CONNECTIVITY, false
);
if (noConnectivity) {
AlertDialog.Builder builder1 = new AlertDialog.Builder(context);
builder1.setMessage("You must have internet connection");
builder1.setCancelable(true);
builder1.setPositiveButton(
"Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
builder1.setNegativeButton(
"No",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
builder1.create();
builder1.show();
} else {
Toast.makeText(context, "Connected", Toast.LENGTH_SHORT).show();
}
}
}
}
Please note, the below code is just for your reference. You could update/change this code based on your requirement.
public class MainActivity extends AppCompatActivity {
private static final String TAG = MainActivity.class.getSimpleName();
private BroadcastReceiver mNetworkReceiver;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
registerNetworkBroadcastForNougat();
}
private void registerNetworkBroadcastForNougat() {
mNetworkReceiver = new NetworkChangeReceiver();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
registerReceiver(mNetworkReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
registerReceiver(mNetworkReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
}
}
protected void unregisterNetworkChanges() {
try {
unregisterReceiver(mNetworkReceiver);
} catch (IllegalArgumentException e) {
e.printStackTrace();
}
}
#Override
public void onDestroy() {
super.onDestroy();
unregisterNetworkChanges();
}
class NetworkChangeReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent)
{
try
{
if (!isOnline(context)) {
showDialog(context);
}
} catch (NullPointerException e) {
e.printStackTrace();
}
}
private void showDialog(final Context context) {
AlertDialog.Builder builder1 = new AlertDialog.Builder(context);
builder1.setMessage("You must have internet connection");
builder1.setCancelable(true);
builder1.setPositiveButton(
"Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
startActivity(new Intent(WifiManager.ACTION_PICK_WIFI_NETWORK));
}
});
builder1.setNegativeButton(
"No",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
builder1.create();
builder1.show();
}
private 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;
}
}
}
}

How to achieve dialogue box get disappeared when internet or WiFi get connected. and vice versa?

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...

Play a music when WiFi is disconnected

I'm trying to write the codes for my project that's to play a music when WiFi connection is disconnected and also whenever user clicks 'test' button it display the current connection strength. I've tried the following code:
Main activity part (for the test button and call out the class AlarmManagerBroadcastReceiver :
public class MainActivity extends FragmentActivity {
public static final String TAG = "Final Year Project";
private static boolean wifiConnected = false;
private static boolean mobileConnected = false;
private LogFragment mLogFragment;
private AlarmManagerBroadcastReceiver alarm ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sample_main);
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
registerReceiver(alarm, intentFilter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
// When the user clicks TEST, display the connection status.
case R.id.test_action:
checkNetworkStrengh();
return true;
// Clear the log view fragment.
case R.id.clear_action:
mLogFragment.getLogView().setText("");
return true;
}
return false;
}
private void checkNetworkStrengh() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo Info = cm.getActiveNetworkInfo();
if (Info == null || !Info.isConnectedOrConnecting()) {
Log.i(TAG, "No connection");
} else {
int netType = Info.getType();
int netSubtype = Info.getSubtype();
if (netType == ConnectivityManager.TYPE_WIFI) {
Log.i(TAG, "Wifi connection");
WifiManager wifiManager = (WifiManager) getApplication().getSystemService(Context.WIFI_SERVICE);
List<ScanResult> scanResult = wifiManager.getScanResults();
for (int i = 0; i < scanResult.size();) {
Log.d("scanResult", "Speed of wifi" + scanResult.get(i).level);//The db level of signal //
// its okay now thanks guys //
}
} else if (netType == ConnectivityManager.TYPE_MOBILE) {
Log.i(TAG, "GPRS/3G connection");
// Need to get differentiate between 3G/GPRS
}
}
}
}
AlarmManagerBroadcastReceiver part (created in order to scan the current network connectivity all the time):
public class AlarmManagerBroadcastReceiver extends BroadcastReceiver {
private static boolean wifiConnected = false;
private static boolean mobileConnected = false;
#Override
public void onReceive(Context context, Intent intent) {
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)) {
NetworkInfo networkInfo =
intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
if (networkInfo.isConnected()) {
// Wifi is connected
Intent in = new Intent(context, RingService.class);
context.stopService(in);
} else {
Intent in = new Intent(context, RingService.class);
context.startService(in);
}
}
}
and the MusicService part(created in order to play a music whenever the class AlarmMAnagerBroadcastReceiver triggered the specific condition):
public class MusicService extends Service{
private MediaPlayer mp;
#SuppressWarnings("deprecation")
#Override
public void onStart(Intent intent, int startId) {
// TODO Auto-generated method stub
mp.start();
mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub
try {
mp.start();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
mp.setOnErrorListener(new MediaPlayer.OnErrorListener() {
public boolean onError(MediaPlayer mp, int what, int extra) {
// TODO Auto-generated method stub
try {
mp.release();
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
});
super.onStart(intent, startId);
}
#Override
public void onCreate() {
// TODO Auto-generated method stub
try {
mp = new MediaPlayer();
mp = MediaPlayer.create(MusicService.this, R.raw.ly);
mp.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
super.onCreate();
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
mp.stop();
mp.release();
super.onDestroy();
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
}
Manifest file
<service
android:name="com.example.android.basicnetworking.RingService"
android:exported="true"
android:process=":remote" >
</service>
<receiver android:name=".AlarmManagerBroadcastReceiver" >
<intent-filter android:priority="100" android:enabled="true"
android:label="ConnectivityActionReceiver">
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
<action android:name="android.net.wifi.STATE_CHANGE" />
</intent-filter>
</receiver>
Can someone who's professional in android programming helps me in the code cause i'm new in android and java programming) to get return to checkConnectivity class in the AlarmManagerBroadcastReceiver part, and also to play a music when the wifi connection is lost.
Edit: thanks for the helps. I have figured it out. If anyone need the codes you can inbox me or I will upload the complete coding once everything is ok.
Edit: updated some code
WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
int numberOfLevels = 5;
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
int level = WifiManager.calculateSignalLevel(wifiInfo.getRssi(), numberOfLevels);
When you try to play the music AGAIN, then you need to prepare it again, so every time before start call prepare as well:
add this to AlarmManagerBroadcastReceiver:
void play(int musicId) {
MediaPlayer mp = MediaPlayer.create(getContext(), musicId);
mp.prepare();
mp.start();
}
and in checkConnectivity where you want to play music:
play(R.raw.ly); // or use other resource instead of ly
play sound on disconnection... try this:
public class NetworkReceiver extends BroadcastReceiver {
static boolean isConnect = false;
#Override
public void onReceive(Context context, Intent intent) {
Log.d(TAG, "network changed");
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = connectivityManager.getActiveNetworkInfo();
if (activeNetwork != null) { // connected to the internet
if (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI) {
Log.d(TAG, "network type wifi"); // connected on wifi
} else if (activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE) {
Log.d(TAG, "network type mobile"); // connected on mobile (3g/4g)
}
} else {
isConnect = false;
Log.d(TAG, "no connection"); // DISCONNECTED
playMySound(); // <- your play sound function
}
}
public void playMySound() {
MediaPlayer sound = MediaPlayer.create(context, R.raw.song);
sound.start();
}
}

Zxing scan stops

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);
}
}

Application is repeatedly opened

I'm developing an application. When i exit from the application, it will be opened again (The first activity is called again and again). So i couldn't able to exit from it.
In some other activities I use EXIT button and proper code to exit. Even when I click the EXIT button on those activities, it will start login activity. (login page is opened)
In my application, I use
1) Main
2) ScreenActivity
3) Login
flow: (from main->screenActivity->login)
The start page (1st activity) is posted below
public class main extends Activity {
static ConnectivityManager conMgr;
BackgroundThread backgroundThread;
TextView myText;
boolean myTextOn = true;
Cursor cursor;
String response="";
public SQLiteAdapter mySQLiteAdapter;
private SQLiteDatabase sqLiteDatabase;
SimpleCursorAdapter cursorAdapter;
public class BackgroundThread extends Thread {
boolean running = false;
void setRunning(boolean b){
running = b;
}
#Override
public void run() {
// TODO Auto-generated method stub
//super.run();
while(running){
try {
sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch(Exception e)
{
}
handler.sendMessage(handler.obtainMessage());
}
}
}
Handler handler = new Handler(){
#Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
//super.handleMessage(msg);
if (myTextOn){
myTextOn = false;
myText.setVisibility(View.GONE);
}
else{
myTextOn = true;
myText.setVisibility(View.VISIBLE);
}
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.thread);
myText = (TextView)findViewById(R.id.mytext);
}
#Override
protected void onStart() {
conMgr = (ConnectivityManager)getSystemService(CONNECTIVITY_SERVICE);
// TODO Auto-generated method stub
super.onStart();
if(isInternetAvailable())
{
Toast.makeText(this, "online", Toast.LENGTH_LONG).show();
startActivity(new Intent(main.this, ScreenActivity.class));
}
else{
startActivity(new Intent(main.this, splashscreen.class));
Toast.makeText(this, "offline", Toast.LENGTH_LONG).show();
}
backgroundThread = new BackgroundThread();
backgroundThread.setRunning(true);
backgroundThread.start();
}
private boolean isInternetAvailable() {
ConnectivityManager cm=(ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
return true;
}
return false;
}
#Override
protected void onStop() {
// TODO Auto-generated method stub
super.onStop();
boolean retry = true;
backgroundThread.setRunning(false);
while(retry){
try {
backgroundThread.join();
retry = false;
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch(Exception e)
{
}
}
}
public void onDEstroy()
{
super.onDestroy();
}
}
ScreenActivity:
public class ScreenActivity extends Activity implements AnimationListener {
private TextView animatedView3;
//ImageView image;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
/* Animation animation1 = AnimationUtils.loadAnimation(this,
R.anim.anima);
animation1.setAnimationListener(this);
View animatedView1 = findViewById(R.id.aet1);
animatedView1.startAnimation(animation1);
/** set time to splash out */
final int welcomeScreenDisplay = 9000;
/** create a thread to show splash up to splash time */
Thread welcomeThread = new Thread() {
int wait = 0;
#Override
public void run() {
try {
super.run();
/**
* use while to get the splash time. Use sleep() to increase
* the wait variable for every 100L.
*/
while (wait < welcomeScreenDisplay) {
sleep(100);
wait += 100;
}
} catch (Exception e) {
System.out.println("EXc=" + e);
} finally {
/**
* Called after splash times up. Do some action after splash
* times up. Here we moved to another main activity class
*/
startActivity(new Intent(ScreenActivity.this,
login.class));
}
}
};
welcomeThread.start();
}
public void onAnimationStart(Animation animation) {
}
public void onAnimationEnd(Animation animation) {
//Toast.makeText(this, "Animation ended", Toast.LENGTH_SHORT).show();
if (animatedView3.getVisibility() == View.VISIBLE) {
animatedView3.setVisibility(View.INVISIBLE);
} else {
animatedView3.setVisibility(View.VISIBLE);
}
}
public void onAnimationRepeat(Animation animation) {
// Toast.makeText(this, "Animation rep", Toast.LENGTH_SHORT).show();
}
}
Please can anyone explain about the problem and how to solve it? I didn't understand.
Place finish() in your loginActivity and for other Activities as well else stack will store the list of visited Activities.

Categories