Start activity from another activity? - android

I want in my application this functionality:
When i start my app
-check if there is interne access : if yes {
start LogInActivity { if login is succesfull
dialog:"synced!" for 3second
else
dialog:"no synced!" for 3second
}
}
dialog:"no synced!"
startMainActivity
I want the first activity just to performs checks.Not to be visible and if there is internet
then forward to login Activity else login to Main activity
This is because i want my app to be used without interner.But for the logged users it will download from web service some information to be stored in Shared Preferences.Any help?

The best way is to create a small function which checks both for wifi and mobile net as follows :-
/**
* Function to check whether internet connection is available or not
*
* #return true - if net is available
*/
public boolean haveNetworkConnection() {
mHaveConnectedWifi = false;
mHaveConnectedMobile = false;
mConnectivityManager = (ConnectivityManager) mContext
.getSystemService(Context.CONNECTIVITY_SERVICE);
mNetworkInfo = mConnectivityManager.getAllNetworkInfo();
for (NetworkInfo mNetInfo : mNetworkInfo) {
if (mNetInfo.getTypeName().equalsIgnoreCase("WIFI"))
if (mNetInfo.isConnected())
mHaveConnectedWifi = true;
if (mNetInfo.getTypeName().equalsIgnoreCase("MOBILE"))
if (mNetInfo.isConnected())
mHaveConnectedMobile = true;
}
return mHaveConnectedWifi || mHaveConnectedMobile;
}
Now in your code just do :-
if(haveNetworkConnection){
// do something
}else{
// no internet
}
The advantage is that we are checking for both wifi and mobile net...
Hope the explanation was useful....

Just create a third activity that starts first and on the onCreate of that activity you run your code and call other activity.
Also you could show a splash screen on this third activity, while you decide which activity to show.

You'll want to either use startActivity() or startActivityForResult().
The advantage of startActivityForResult() is that you can receive data back from the activity you started, upon its completion.

To launch your other activity:
if(connection/login fails){
Intent loginfailed = new Intent(MainActivity.this, loginfailedactivity.class);
startActivity(loginfailed);
}
else {.....}

Here is what I did to make sure there was a wifi connection:
private void checkWifiConnection(String menuUrl){
ConnectivityManager connManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if(mWifi.isConnected()){
LoadJSON lJs = new LoadJSON();
lJs.execute(menuUrl);
} else {
AlertDialog.Builder ab = new AlertDialog.Builder(context);
ab.setCancelable(true);
ab.setTitle("No Connection");
ab.setMessage("Your device is currently not connected to the Internet, please check your connection and launch the app again.");
ab.setInverseBackgroundForced(true);
ab.setPositiveButton("Okay", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
MainActivity.this.finish();
}
});
AlertDialog alert = ab.create();
alert.show();
}
You could insert an Intent call in the if statement that launches your Activity

Related

Show Internet Connection Dialog on Android Studio with Redirection

*Not a duplicate resource, I have accessed all answers available.
I am trying to build an android studio app.
How can I make it mandatory for the app to show a dialog on the app when there is no connection and then redirect user to activity when there is either mobile or wifi connection.
Users must not be able to quit the dialog until they turn on their Internet connection.
Dialog should automatically disappear when data is on.
I have tried all the codes I see on Stackoverflow, but all codes I have used, none worked some make the app to crash.
What is the simplest way to achieve this result in API 30?
Step 1:
Add this Typealias below import file or above class
typealias OnRetryInternetConnection = () -> Unit
Step 2:
Add this code (Custom Alert Dialog)
fun internetValidationDialog(
activity: Activity,
onRetryInternetConnection: OnRetryInternetConnection
) {
try{
val mDialogView = LayoutInflater.from(activity).inflate(R.layout.your_custom_layout_with_retry_button, null)
val mBuilder = AlertDialog.Builder(activity)
.setView(mDialogView)
val mAlertDialog = mBuilder.show()
mAlertDialog.setCancelable(false)
mDialogView.llRetry.setOnClickListener {
run {
onRetryInternetConnection.invoke()
}
mAlertDialog.dismiss()
}
}catch (e: Exception){
e.printStackTrace()
}
}
Step 3:
This Function will use to check internet connection
fun isNetworkConnected(): Boolean {
var result = false
val cm = application!!.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager?
cm?.run {
cm.getNetworkCapabilities(cm.activeNetwork)?.run {
result = when {
hasTransport(NetworkCapabilities.TRANSPORT_WIFI) -> true
hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) -> true
hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET) -> true
else -> false
}
}
}
return result
}
Step 4:
Add this code where you want to validate the Internet connectivity
If the internet is not connected it will show the alert dialog and if
you click the retry button again this method called and come to else
repeat until condition satisfied.
fun callYourNextLogin() {
button.setOnClickListener {
when {
isNetworkConnected() -> {
// Go ahead internet is connected
}
else -> {
internetValidationDialog(requireActivity()) {
callYourNextLogin()
}
}
}
}
}
Step 5:
To auto dismiss the internet connection just use Live data to observe.
You can create a BroadcastReceiver and register it in your main activity.
The receiver will be notified whenever there is a change in the connection of the device to the internet.
1. Create a custom dialog dialog.xml in layout. For example:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:padding="20dp">
<ProgressBar
android:layout_width="0dp"
android:layout_height="wrap_content"
android:backgroundTint="#color/light_purple"
android:layout_weight="1" />
<TextView
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="4"
android:gravity="center"
android:textSize="18sp"
android:text="You're not connected!" />
</LinearLayout>
2. Create a static method to check the connection status:
public static boolean checkConnection(Context context)
{
ConnectivityManager cm =
(ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean isConnected = activeNetwork != null &&
activeNetwork.isConnected();
return isConnected;
}
3. Create a new class that extends from BroadcastReceiver:
public class OfflineBroadcastReceiver extends BroadcastReceiver
{
public OfflineBroadcastReceiver() {}
#Override
public void onReceive(final Context context, final Intent intent)
{
// No connection
if(!checkConnection(context))
{
// Activity with dialog
Intent offline = new Intent(context, Activity.class);
context.startActivity(offline);
}
// Connected
else
{
Intent offline = new Intent(context, OfflineActivity.class);
context.startActivity(offline);
}
}
}
4. Create the receiver in your launched activity (MainActivity by default) in onCreate, add a CONNECTIVITY_ACTION action to the filter, and register it:
OfflineBroadcastReceiver offlineForeground = new OfflineBroadcastReceiver();
IntentFilter filter = new IntentFilter();
filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
registerReceiver(offlineForeground, filter);
Add the following permission to your manifest file:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
NOTE: The receiver will not be notified in the background while the app is not running. You could create a Manifest declared receiver to do that.
In Github: https://github.com/shahar0809/OfflineReceiver

Android:No source path

Im having a pretty simple requirement.I have a Login activity. Once user enters login details and clicks on submit button, the application should perform a internet access check. If device is not connected to internet then it should display a toast saying "No internet access". If internet is accessible then the application will perform authentication and navigate to Home page.
I have written the code snippet to perform internet check in a separate class for re usability. The code snippet is as below:
package com.example.rinventory.Common;
import android.content.Context;
import android.net.NetworkInfo;
import android.net.ConnectivityManager;
public class ConnectionDetector
{
private Context _context;
public ConnectionDetector(Context context)
{
this._context = context;
}
public boolean isConnectingToInternet()
{
ConnectivityManager connectivity = (ConnectivityManager) _context.getSystemService(Context.CONNECTIVITY_SERVICE);
//Get all the active networks available.
NetworkInfo info = connectivity.getActiveNetworkInfo();
//If it is connected to available networks return true else false.
if(info != null && info.isConnected())
return true;
else
return false;
}
}
And my Login activity's submit button functionality is as below:
public class RInventoryLogin extends ActionBarActivity
{
boolean isInternetPresent = false;
ConnectionDetector detect;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_rinventory_login);
Button btnLogin = (Button) findViewById(R.id.btnSubmit);
btnLogin.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
//Throws error at this particular line
isInternetPresent = detect.isConnectingToInternet();
if(isInternetPresent)
{
EditText editEmail = (EditText)findViewById(R.id.editEmail);
EditText editPassword = (EditText)findViewById(R.id.editPassword);
LoginData data = new LoginData();
data.setEmail(editEmail.getText().toString());
data.setPassword(editPassword.getText().toString());
new CallJsonParserLogin().execute(data);
}
else
{
Toast.makeText(RInventoryLogin.this, "No Internet Access", Toast.LENGTH_SHORT).show();
}
}
});
}
}
When I try to execute, it loads the activity. However once I enter login details and click on submit the application shuts down with "unexpectedly your application has stopped working"
I have included Internet, Network state parameters in Manifest file.
When I comment the line
isInternetPresent = detect.isConnectingToInternet();
and subsequent if else blocks it just works fine. What might be the issue I'm missing here?
I have tried the same creating a demo application and that works fine.
Please help
you are not initializing detect object.
add this line before setting click listener to your button :
detect = new ConnectionDetector(this);

code to get phone nos from contacts in android

I am building an app that gets 3 contacts from CONTACTS ,,
i want a ready made code to do this and to also show to the user in a layout,, which numbers he has choosen. I have heard that this task is to be done in a background thread I was thinking that if i would do this using
extending AsynTask
is it true?? Please give me full code to do that.
My activity in which i have to include this code is like this:
public class Registration extends Activity implements View.OnClickListener {
RegisteredUser user;
EditText name,mobile ;
Button guardian1,guardian2;
#Override
protected void onCreate(Bundle savedInstanceState) {
Button submit;
super.onCreate(savedInstanceState);
setContentView(R.layout.registration);
submit = (Button) findViewById(R.id.register_registration_submit);
submit.setOnClickListener(this);
}
#Override
public void onClick(View view) {
switch(view.getId()){
case R.id.register_registration_submit:
if(isConnected()){
if(inputData())
Log.d("gone","hum");
new SendRegistrationData(getBaseContext(),Registration.this).execute(user);
}
else
Toast.makeText(getBaseContext(), "You are not connected to internet.Please connect yourself and try again.", Toast.LENGTH_LONG).show();
break;
default: Log.d("application","no button match");
}
}
private boolean inputData() {
user = new RegisteredUser();
name = (EditText) findViewById(R.id.registration_name);
mobile = (EditText) findViewById(R.id.registration_mob);
user.setName(name.getText().toString().trim());
user.setMobile(mobile.getText().toString().trim());
//code to input name and mobile and also validation
//** HERE I WANT CODE TO GET 3 CONTACTS .WHEN USER CLICK ON BUTTON.
button.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0) {
new GetContact().execute();
}
});
/*/ also put a validation to check either the user has choosen
all three contacts if not,, return false to input data ,,
so that form can not be submitted */
return true;
}
public boolean isConnected(){
ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Activity.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected())
return true;
else
return false;
}
}
basically what you need to do to retrieve contacts from your phone is to use Content Providers: http://developer.android.com/guide/topics/providers/content-providers.html
You'll have to query your contacts and say what fields you want to retrieve from them, this query will return a Cursor to you and this cursor can be used to iterate through your contacts.
You can get a complete documentation about it on this page: http://developer.android.com/guide/topics/providers/contacts-provider.html
Once you get a hold of it, it's quite simple.

Prevent offline mode or reroute to URL

I would like my android app to be only available online.
If user has no internet connection, I would like to prevent the user from using any content from it, and to show him a popup with a quick message and a browser link to the play store.
I have seen other questions with answer about checking connection status, but I am not sure
1) where in my app to put this code
2) how to prevent the user from reaching any content at all if he is offline
2) what is the best solution to display a popup with a short text message and a link to the playstore
Thanks for your help
For your first question, you could easily close the app on startup:
ConnectivityManager connectivityManager
= (ConnectivityManager) ctx.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
if(activeNetworkInfo == null){
finish();
}
This wouldn't give the user any indication that your app was restricted without WiFi but it'd do the job, you could easily add dialog before closing. This would need to be placed in onCreate() of your main launcher activity.
Secondly:
AlertDialog.Builder builder = new AlertDialog.Builder(mActivity)
.setTitle(title)
.setMessage(message)
.setPositiveButton("Play Store", new Dialog.OnClickListener() {
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
final Intent MyIntent = new Intent(Intent.ACTION_VIEW,
Uri.parse("market://details?id=myid"));
startActivity(MyIntent);
}
})
.setNeutralButton("No thanks!", new Dialog.OnClickListener(){
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
});
builder.create().show();
This will give a small popup and when clicked will take the user to the market.

Deal with inactive wi-fi networks

Suppose phone finds open wi-fi network and connects to it. But wi-fi network is "inactive", i.e. when you open browser you see prompt for credentials. I have many apps on my phone(for example web-browser), which fail to work in such cases.
I want to send data using mobile network, but system still tries to use wi-fi.
NetworkInfo.isAvailable() and NetworkInfo.isConnected() still return true for the described wi-fi networks.
Any solution?
I've been having the same problem, and what I found is there is no such possibility via the Android SDK, you have to write your own way to do it.
It depends what do you want to do with the network and what do you mean by 'inactive' - you can be connected to a router, which doesn't have connection to the Internet, and there is no Android method to check such situation. As MrMichael wrote, ping is one way to check it, but in that case positive test gives you just info about ping - the network can have some heavy firewall which allows you to send pings, but i. e. will not let HTTP request through.
In that case, you have to write your own custom test for your own needs, alas - that's what I did. I just implemented simple ping-like protocol (I try to connect my socket on proper IP/port and send short message waiting for short answer). Only that gives me 100% warranty that the connection I want can be established.
As far as I am aware there is no way to force the use of a data connection over wifi (perhaps something that you shouldn't do without user interaction anyway).
I have the same requirements in many of my applications, I want to know if they have a viable network connection whilst the splash screen is loading (for example I show a read only version of the app if not).
The way that I get around this is to fire a simple service call to my server called isAlive which just returns a true imedialtly. This not only tells me that I am able to see my service, it also confirms that my server is on-line (no issues at my end). In the case that I do not get a response back in a timely fashion I inform the user that they have no network connection and "Please ensure you have a valid data/wifi connection before continuing". I then take the isConnected property for the wifi and modify this message to say "Your current Wireless connection does not internet access" or something similar.
Not quite the answer you were hoping for but maybe a possibility?
Just a suggestion: You may try using requestRouteToHost(). But first search SO for problems in using this method.
Also you'll need the CHANGE_NETWORK_STATE permission.
Try this....
I needed to do some custom work..but got it up and running...
My code switches from Wifi to Mobile network when its off.
And I am using the TimeService at port 37 to know that the Internet is DEAD while the wifi connection is still ON
//////////////////////////Edited//////////////////////////////////
Now i am putting here a complete working code i made. Please pardon me as the DRY (Don't Repeat Yourself Principle ) has been abused here. So please refactor the code and convert the duplicate codes into method , ie into a single sensible place, when using in production network
/////---------------------------Intial Available Network Checking
private boolean checkConnection(){
boolean connected = false;
ConnectivityManager cm = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
if (cm != null) {
NetworkInfo[] netInfo = cm.getAllNetworkInfo();
for (NetworkInfo ni : netInfo) {
if ((ni.getTypeName().equalsIgnoreCase("WIFI")
|| ni.getTypeName().equalsIgnoreCase("MOBILE"))
& ni.isConnected() & ni.isAvailable()) {
connected = true;
}
}
}
return connected;
}
/////---------------------------Intial Available Network Checking
/////-------------------------------Check for the working Internet Connection
public boolean inetAddr(){
boolean x1 = false;
try {
Socket s = new Socket("utcnist.colorado.edu", 37);
InputStream i = s.getInputStream();
Scanner scan = new Scanner(i);
while(scan.hasNextLine()){
System.out.println(scan.nextLine());
x1 = true;
}
} catch (Exception e) {
x1 = false;
}
return x1;
}
/////-------------------------------Check for the working Internet Connection
////-------------------------------Check Mobile Conectivity Again
public boolean mobileConnect(){
boolean conn = false;
ConnectivityManager cm = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNet = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
if(activeNet != null){
conn = true;
}else{
conn = false;
}
return conn;
}
////------------------------------Check Mobile Conectivity Again
Here i am using the Above Methods....
try{
if (!checkConnection()){
AlertDialog.Builder myAlertDialog = new AlertDialog.Builder(YumZingSplashActivity.this);
myAlertDialog.setTitle("--- Connectivity Check ---");
myAlertDialog.setMessage("No Internet Connectivity");
myAlertDialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
YumZingSplashActivity.this.finish();
//splashHandler.removeCallbacks(launcherRunnable);
}});
System.out.println("No Internet Connectivity");
myAlertDialog.show();
}
else{
if(inetAddr()){
aphandle = APIHandling.getInstance();
aphandle.xmlCreateSession();
System.out.println("Net Connectivity is Present");
DURATION = Integer.valueOf(getString(R.string.splash_duration));
splashHandler = new Handler();
// ================ Main Code of the Application
launcherRunnable = new Runnable() {
public void run() {
Intent i = new Intent(YumZingSplashActivity.this, YumZingTabHostActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
YumZingSplashActivity.this.finish();
}
};
if (DEBUG)
{
splashHandler.post(launcherRunnable);
}
else{
splashHandler.postDelayed(launcherRunnable, DURATION);
}
}
else{
if(mobileConnect()){
if(inetAddr()){
aphandle = APIHandling.getInstance();
aphandle.xmlCreateSession();
System.out.println("Net Connectivity is Present");
DURATION = Integer.valueOf(getString(R.string.splash_duration));
splashHandler = new Handler();
// ================ Main Code of the Application
launcherRunnable = new Runnable() {
public void run() {
Intent i = new Intent(YumZingSplashActivity.this, YumZingTabHostActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
YumZingSplashActivity.this.finish();
}
};
if (DEBUG)
{
splashHandler.post(launcherRunnable);
}
else{
splashHandler.postDelayed(launcherRunnable, DURATION);
}
}else{
AlertDialog.Builder myAlertDialog = new AlertDialog.Builder(YumZingSplashActivity.this);
myAlertDialog.setTitle("--- Connectivity Check ---");
myAlertDialog.setMessage("No Internet Connectivity");
myAlertDialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
YumZingSplashActivity.this.finish();
//splashHandler.removeCallbacks(launcherRunnable);
}});
System.out.println("No Internet Connectivity");
myAlertDialog.show();
}
}else{
AlertDialog.Builder myAlertDialog = new AlertDialog.Builder(YumZingSplashActivity.this);
myAlertDialog.setTitle("--- Connectivity Check ---");
myAlertDialog.setMessage("No Internet Connectivity");
myAlertDialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
YumZingSplashActivity.this.finish();
//splashHandler.removeCallbacks(launcherRunnable);
}});
System.out.println("No Internet Connectivity");
myAlertDialog.show();
}
}
}
//setContentView(R.layout.yumzing_splash_layout);
} catch(Exception ex){
System.out.println("Leak ko catch");
}
}
You could connect to the wifi network, try connect to any page in background and verify if there is any redirection. If so, it is very likely to be the credential pages. In fact when I was trying to find how to implement the solution I have just described, I found it to be described in HttpURLConnection class documentation at Android developers site. There you can read:
Handling Network Sign-On
Some Wi-Fi networks block Internet access until the user clicks through a sign-on page. Such sign-on pages are typically presented by using HTTP redirects. You can use getURL() to test if your connection has been unexpectedly redirected. This check is not valid until after the response headers have been received, which you can trigger by calling getHeaderFields() or getInputStream(). For example, to check that a response was not redirected to an unexpected host:
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
if (!url.getHost().equals(urlConnection.getURL().getHost())) {
// we were redirected! Kick the user out to the browser to sign on?
...
} finally {
urlConnection.disconnect();
}
}
Try
InetAddress.getByName(host).isReachable(timeOut)

Categories

Resources