Manu Sai
Manu Sai

Reputation: 25

How to navigate to another activity if network available?

I am new to android app based on java. I want to start new activity(another screen) if internet connection is available.

I tried it in app inventor.

It was like when on clicking a button it checks internet connection by url https://www.google.com and if returs status code 200 navigate to next screen else a toast message as " Enable internet connection". How can I do it in android app.

(Question edited)

How to insert connection check inside this

public class mainmenu extends Activity {
	

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// Get the view from activity_main.xml
		setContentView(R.layout.main_menu);
		
		// Locate the button in activity_main.xml
		Button indiabt = (Button)findViewById(R.id.indiab);
 
		// Capture button clicks
	indiabt.setOnClickListener(new OnClickListener() {
			public void onClick(View arg0) {
 
				// Start NewActivity.class
				Intent myIntent = new Intent(mainmenu.this,
						exampage.class);
				startActivity(myIntent);
			}
	});

Thank you All for helping. I got the code. Expecting more help in the future. My required code was as below.

public class mainmenu extends Activity {
	
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// Get the view from activity_main.xml
		setContentView(R.layout.main_menu);

 Button indiabt  = (Button)findViewById(R.id.indiab);
    indiabt.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
            android.net.NetworkInfo wifi = cm
                    .getNetworkInfo(ConnectivityManager.TYPE_WIFI);
            android.net.NetworkInfo datac = cm
                    .getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
            if ((wifi != null & datac != null)
                    && (wifi.isConnected() | datac.isConnected())) {
                setContentView(R.layout.question);
            }else{
                //no connection
                Toast toast = Toast.makeText(mainmenu.this, "No Internet Connection", Toast.LENGTH_LONG);
                toast.show();
            }
        }
    });
}}

Upvotes: 2

Views: 2615

Answers (5)

Harshad
Harshad

Reputation: 1344

Use this to perform task.

 Button indiabt  = (Button)findViewById(R.id.indiab);
    indiabt .setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
            android.net.NetworkInfo wifi = cm
                    .getNetworkInfo(ConnectivityManager.TYPE_WIFI);
            android.net.NetworkInfo datac = cm
                    .getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
            if ((wifi != null & datac != null)
                    && (wifi.isConnected() | datac.isConnected())) {
                setContentView(R.layout.activity_main2);
            }else{
                //no connection
                Toast toast = Toast.makeText(MainActivity.this, "No Internet Connection", Toast.LENGTH_LONG);
                toast.show();
            }
        }
    });

Upvotes: 3

Android Geek
Android Geek

Reputation: 9225

First of all create a 'ConnectionDetector' class and put the following code into that:

 private Context _context;

public ConnectionDetector(Context context){
    this._context = context;
}

/**
 * Checking for all possible internet providers
 * **/
public boolean isConnectingToInternet(){
    ConnectivityManager connectivity = (ConnectivityManager) _context.getSystemService(Context.CONNECTIVITY_SERVICE);
    if (connectivity != null)
    {
        NetworkInfo[] info = connectivity.getAllNetworkInfo();
        if (info != null)
            for (int i = 0; i < info.length; i++)
                if (info[i].getState() == NetworkInfo.State.CONNECTED)
                {
                    return true;
                }

    }
    return false;
}

Then in your activity check for network connection on button click by adding this:

 cd = new ConnectionDetector(getApplicationContext());
    if (!cd.isConnectingToInternet()) {
        AlertDialog alertDialog=new AlertDialog.Builder(LoginActivity.this, R.style.cust_dialog).create();
        alertDialog.setTitle("Alert!");
        alertDialog.setMessage("Internet Connection Error, Please connect to working Internet connection");
        alertDialog.setButton("OK", new DialogInterface.OnClickListener() {

            public void onClick(DialogInterface dialog,int which)
            {
                Toast.makeText(A.this, "You clicked on OK", Toast.LENGTH_SHORT).show();
            }
        });

        // Showing Alert Message
        alertDialog.show();

    }
    if(cd.isConnectingToInternet()) {

Intent i=new Intent(A.this, B.class);

 startActivity(i);

 }

Also add the following permissions into your 'AndroidManifest.xml' file:

  <uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

Upvotes: 0

user5779175
user5779175

Reputation:

Check the answer to this question. With the by Alexandre Jasmin provided function you can check if you have an internet connection or not.

All you need to do then is checking the result of this function and do your action in an if-clause.

if(isNetworkAvailable()){
  //start your activity
} else{
  //show your toast
}

Upvotes: 0

Strider
Strider

Reputation: 4490

If u really want to check internet access, and not just connection status, use the answer of this post:

Android: Check network and real internet connectivity

and than change the handler to:

Handler h = new Handler() {

    @Override
    public void handleMessage(Message msg) {

        if (msg.what != 1) {          // code if not connected
            Toast.makeText(getActivity(), "Enable internet connection", Toast.LENGTH_SHORT).show();
        } else {                      // code if connected
            Intent intent = new Intent (this, ActivityUWantToStart.class); 
            startActivity(intent);
        }
    }
};

Hope this will solve your problem

Upvotes: 0

Spirrow
Spirrow

Reputation: 1150

Try this inside your button:

if(isNetworkAvailable()){
    startActivity(context, yourActivity.class);
}

The method to check if internet connection is available:

private boolean isNetworkAvailable() {
    ConnectivityManager connectivityManager 
      = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
    return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}

You will also need a permision added in your manifest

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

Upvotes: 1

Related Questions