I am trying to do a task where check the internet and then alert the user using an alertdialog using a connectivity manager.. does anybody know how I would implement this in my main activity when both my buttons are pressed ( separately)?
public class MainActivity extends Activity implements OnClickListener {
Button login, register;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
login = (Button) findViewById(R.id.login_bt);
register = (Button) findViewById(R.id.register_bt);
login.setOnClickListener(this);
register.setOnClickListener(this);
}
#Override
public void onClick(View v) {
Intent i = null;
if (v.getId() == login.getId()) {
i = new Intent(getBaseContext(), RegistrationActivity.class);
startActivity(i);
} else if (v.getId() == register.getId()) {
i = new Intent(getBaseContext(), RegistrationActivity.class);
startActivity(i);
}
}
}
Check for internet connection
ConnectivityManager manager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo ni = manager.getActiveNetworkInfo();
boolean connected=ni != null && ni.getState() == NetworkInfo.State.CONNECTED;
if(connected){
//network connected
}else{
//network disconnected
}
Manifest
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
Create a new class CustomClickListener :
class CustomClickListener implements View.OnClickListener {
#Override
public void onClick(View v) {
if(isOnline()) {
Intent i = null;
i = new Intent(getBaseContext(), RegistrationActivity.class);
startActivity(i);
}
}
}
And in the OnCreate method :
login.setOnClickListener(new CustomClickListener());
register.setOnClickListener(new CustomClickListener());
This method checks for Internet connection :
protected boolean isOnline() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
return true;
} else {
return false;
}
}
Related
I have two activities in my project. There is a button in the main activity when I click it, it takes me to second activity. When I press back button there it's not coming to main activity. It checks for internet first and then when I click button It takes me to second activity.
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
try {
this.getSupportActionBar().hide();
}catch (Exception e){
}
if (isNetworkConnected(this)) {
Button button = findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent activity2Intent = new Intent(getApplicationContext(), playlive.class);
startActivity(activity2Intent);
}
});
} else {
buildDialog(MainActivity.this).show();
}
}
public static boolean isNetworkConnected(Context context) {
boolean result = false;
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (cm != null) {
NetworkCapabilities capabilities = cm.getNetworkCapabilities(cm.getActiveNetwork());
if (capabilities != null) {
if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
result = true;
} else if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
result = true;
}
}
}
} else {
if (cm != null) {
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
if (activeNetwork != null) {
// connected to the internet
if (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI) {
result = true;
} else if (activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE) {
result = true;
}
}
}
}
return result;
}
This is the error code
Process: com.example.mythrimedia, PID: 3343
java.lang.RuntimeException: Unable to stop activity {com.example.mythrimedia/com.example.mythrimedia.playlive}: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.exoplayer2.SimpleExoPlayer.release()' on a null object reference
at android.app.ActivityThread.callActivityOnStop(ActivityThread.java:4624)
at android.app.ActivityThread.performStopActivityInner(ActivityThread.java:4594)
at android.app.ActivityThread.handleStopActivity(ActivityThread.java:4669)
at android.app.servertransaction.TransactionExecutor.performLifecycleSequence(TransactionExecutor.java:233)
at android.app.servertransaction.TransactionExecutor.cycleToPath(TransactionExecutor.java:201)
at android.app.servertransaction.TransactionExecutor.executeLifecycleState(TransactionExecutor.java:173)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:97)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2016)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7356)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.exoplayer2.SimpleExoPlayer.release()' on a null object reference
at com.example.mythrimedia.playlive.onStop(playlive.java:76)
at android.app.Instrumentation.callActivityOnStop(Instrumentation.java:1466)
at android.app.Activity.performStop(Activity.java:8018)
at android.app.ActivityThread.callActivityOnStop(ActivityThread.java:4616)
at android.app.ActivityThread.performStopActivityInner(ActivityThread.java:4594)
at android.app.ActivityThread.handleStopActivity(ActivityThread.java:4669)
at android.app.servertransaction.TransactionExecutor.performLifecycleSequence(TransactionExecutor.java:233)
at android.app.servertransaction.TransactionExecutor.cycleToPath(TransactionExecutor.java:201)
at android.app.servertransaction.TransactionExecutor.executeLifecycleState(TransactionExecutor.java:173)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:97)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2016)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7356)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
second activity
public class playlive extends AppCompatActivity {
private SimpleExoPlayer player;
private PlayerView playerView;
private Uri uri;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_playlive);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
try {
this.getSupportActionBar().hide();
} catch (Exception e) {
}
if (isNetworkConnected(this)) {
play();
} else {
buildDialog(playlive.this).show();
}
}
private void play() {
SimpleExoPlayer player = ExoPlayerFactory.newSimpleInstance(this);
playerView = findViewById(R.id.player_view);
playerView.setPlayer(player);
uri = Uri.parse("http://localhost:1935/live/mystream/index.m3u8");
DataSource.Factory dataSourceFactory =
new DefaultHttpDataSourceFactory(Util.getUserAgent(this, "app-name"));
// Create a HLS media source pointing to a playlist uri.
HlsMediaSource hlsMediaSource =
new HlsMediaSource.Factory(dataSourceFactory).createMediaSource(uri);
player.prepare(hlsMediaSource);
player.setPlayWhenReady(true);
}
public void onStop(){
super.onStop();
player.release();
}
public void onDestroy(){
super.onDestroy();
player.release();
}
public static boolean isNetworkConnected(Context context) {
boolean result = false;
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (cm != null) {
NetworkCapabilities capabilities = cm.getNetworkCapabilities(cm.getActiveNetwork());
if (capabilities != null) {
if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
result = true;
} else if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
result = true;
}
}
}
} else {
if (cm != null) {
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
if (activeNetwork != null) {
// connected to the internet
if (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI) {
result = true;
} else if (activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE) {
result = true;
}
}
}
}
return result;
}
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 Play this. Press ok to Exit");
builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
return builder;
}
}
add a double check in your 2 methods onDestory and onStop on the secondActivity.
if (player != null) {
player.release;
}
add move it before the line super.onStop(); or super.onDestroy()
your global variable private SimpleExoPlayer player; is alwaus null
I guess you should init it here
private void play() {
player = ExoPlayerFactory.newSimpleInstance(this);...
instead of creating new instance
I'm trying to execute CheckInternetConnection class inside my main activity on create but when the oncreate is called the class is not getting launced however when i press back navigation button Main Activity successfully executes CheckInternetConnection :
Here's my code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDrawer=findViewById(R.id.drawerlayout);
mDrawer.setTouchMode(ElasticDrawer.TOUCH_MODE_BEZEL);
Context context=this.getApplicationContext();
setupToolbar();
setupMenu();
search();
new CheckInternetConnection(this).checkConnection();
FragmentManager pr = getSupportFragmentManager();
ProjectListFragment prjlist = (ProjectListFragment)
pr.findFragmentById(R.id.frame);
if (prjlist == null) {
prjlist = new ProjectListFragment();
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.setCustomAnimations(android.R.anim.fade_in,
android.R.anim.fade_out);
fragmentTransaction.commitAllowingStateLoss();
pr.beginTransaction().replace(R.id.id_main_frame, prjlist).commit();
}
public void onBackPressed() {
int count = getFragmentManager().getBackStackEntryCount();
if (count == 0) {
Intent intent=new Intent(MainActivity.this,MainActivity.class);//This intent will refresh mainactivity on back press
startActivity(intent);
finish();
//additional code
} else {
getFragmentManager().popBackStack();
finish();
}
}
This class will basically check for internet connection and display dialog if connection is not present.
public class CheckInternetConnection {
Context ctx;
public CheckInternetConnection(Context context){
ctx=context;
}
public void checkConnection(){
if(!isInternetConnected()) {
final FancyAlertDialog.Builder alert = new FancyAlertDialog.Builder(ctx)
.setBackgroundColor(R.color.colorAccent)
.setimageResource(R.drawable.internetconnection)
.setTextTitle("No Internet")
.setTextSubTitle("Cannot connect to server")
.setBody(R.string.noconnection)
.setPositiveButtonText("Connect Now")
.setNegativeButtonText("Go Offline")
.setOnNegativeClicked(new FancyAlertDialog.OnNegativeClicked() {
#Override
public void OnClick(View view, Dialog dialog) {
Intent in=new Intent(ctx,MainActivity.class);
in.putExtra("offline","offline");
ctx.startActivity(in);
dialog.dismiss();
}
})
.setPositiveColor(R.color.colorPrimaryDark)
.setOnPositiveClicked(new FancyAlertDialog.OnPositiveClicked() {
#Override
public void OnClick(View view, Dialog dialog) {
if(isInternetConnected()){
Intent in=new Intent(ctx,MainActivity.class);
ctx.startActivity(in);
dialog.dismiss();
}else {
Intent dialogIntent = new Intent(Settings.ACTION_SETTINGS);
dialogIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
ctx.startActivity(dialogIntent);
}
}
})
.setBodyGravity(FancyAlertDialog.TextGravity.CENTER)
.setTitleGravity(FancyAlertDialog.TextGravity.CENTER)
.setSubtitleGravity(FancyAlertDialog.TextGravity.CENTER)
.setCancelable(false)
.build();
alert.show();
}
}
public boolean isInternetConnected() {
ConnectivityManager cm = (ConnectivityManager) ctx.getSystemService(Context.CONNECTIVITY_SERVICE);
return cm.getActiveNetworkInfo() != null
&& cm.getActiveNetworkInfo().isConnectedOrConnecting();
}
}
When connection get back I want to run this task, I want to call NewortchangeReceiver() constructor. I wrote "android.net.conn.CONNECTIVITY_CHANGE" in Mainactivity IntentFilter because "android.net.conn.CONNECTIVITY_CHANGE" not work in androidmanifest.xml in android N (7). I want to automatic reload webview at internet connection change.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
wvDailyDarshan = (WebView) findViewById(R.id.wvDailyDarshan);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
IntentFilter intentFilter = new IntentFilter("android.net.conn.CONNECTIVITY_CHANGE");
context.registerReceiver(new NetworkChangeReceiver(), intentFilter);
Boolean connection = isNetworkConnected();
if (connection == false) {
Snackbar.make(this.getWindow().getDecorView().findViewById(android.R.id.content), "Please check your Internet Connection", Snackbar.LENGTH_SHORT).show();
} else if (connection == true) {
wvDailyDarshan.getSettings().setJavaScriptEnabled(true);
//wvDailyDarshan.loadUrl("http://www.swaminarayanbhagwan.com/daily-darshan/");
wvDailyDarshan.setWebViewClient(new myWebClient());
wvDailyDarshan.getSettings().setJavaScriptEnabled(true);
wvDailyDarshan.getSettings().setBuiltInZoomControls(true);
wvDailyDarshan.getSettings().setDisplayZoomControls(false);
wvDailyDarshan.loadUrl("https://www.google.co.in/");
}
}
What I get from your question is that you want to get callback when there is change in connectivity.
So I'll answer for that.
NetworkChangeReceiver:
public class NetworkChangeReceiver extends BroadcastReceiver {
ConnectionChangeCallback connectionChangeCallback;
#Override
public void onReceive(Context context, Intent intent) {
ConnectivityManager cm = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean isConnected = activeNetwork != null
&& activeNetwork.isConnectedOrConnecting();
if (connectionChangeCallback != null) {
connectionChangeCallback.onConnectionChange(isConnected);
}
}
public void setConnectionChangeCallback(ConnectionChangeCallback
connectionChangeCallback) {
this.connectionChangeCallback = connectionChangeCallback;
}
public interface ConnectionChangeCallback {
void onConnectionChange(boolean isConnected);
}
}
Now your Activity should call setConnectionChangeCallback on BraodCastReceiver ie NetworkChangeReceiver's object and provide ConnectionChangeCallback's implementation.
Which may look like this.
Activity:
public class YourActivity implments NetworkChangeReceiver.ConnectionChangeCallback
{
#Override
protected void onCreate(Bundle savedInstanceState) {
.....
IntentFilter intentFilter = new
IntentFilter("android.net.conn.CONNECTIVITY_CHANGE");
NetworkChangeReceiver networkChangeReceiver = new NetworkChangeReceiver();
registerReceiver(networkChangeReceiver, intentFilter);
networkChangeReceiver.setConnectionChangeCallback(this);
}
#Override
public void onConnectionChange(boolean isConnected) {
if(isConnected){
// will be called when internet is back
}
else{
// will be called when internet is gone.
}
}
}
You can create a new method, which will call itself if internet is not connected. A rough example is below. Change it to more efficient way.
private boolean shoudShowSnackbar = true;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
wvDailyDarshan = (WebView) findViewById(R.id.wvDailyDarshan);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
IntentFilter intentFilter = new IntentFilter("android.net.conn.CONNECTIVITY_CHANGE");
context.registerReceiver(new NetworkChangeReceiver(), intentFilter);
doThisThingIfFoundInternet();
}
private void doThisThingIfFoundInternet() {
if (isNetworkConnected()) {
wvDailyDarshan.getSettings().setJavaScriptEnabled(true);
//wvDailyDarshan.loadUrl("http://www.swaminarayanbhagwan.com/daily-darshan/");
wvDailyDarshan.setWebViewClient(new myWebClient());
wvDailyDarshan.getSettings().setJavaScriptEnabled(true);
wvDailyDarshan.getSettings().setBuiltInZoomControls(true);
wvDailyDarshan.getSettings().setDisplayZoomControls(false);
wvDailyDarshan.loadUrl("https://www.google.co.in/");
}else{
if (this.shoudShowSnackbar) {
Snackbar.make(this.getWindow().getDecorView().findViewById(android.R.id.content), "Please check your Internet Connection", Snackbar.LENGTH_SHORT).show();
shoudShowSnackbar = !shoudShowSnackbar;
}
doThisThingIfFoundInternet();
}
}
Hello Everyone I'm having problem in my android application. I have android app install in ubuntu 16.0.4 which work fine in my work pc but when I imports my app in window 8.1. From login it doesnot work.
First Off My android studio doesn't recognized my mobile in window 8.1 so I have install pdaNet and it work fine.
when I debug my code
An established connection was aborted by the software in your host machine
ConnectivityManager return both true as well as false. It never did in linux
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivityManager != null) {
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isAvailable()
&& networkInfo.isConnected()) {
return true;
} else {
return false;
}
} else {
return false;
}
I dont know what's the problem with window 8.1 but I connected my mobile with my laptop sharing same wifi and web services run on
http://192.168.0.102:8080/payroll-services-ws/api/secured/message
and When I checked on Postman, It is working correctly..
So here is my code of login
public class Login extends AppCompatActivity {
private ProgressBar progressBar;
List<MyTask> myTasksList;
private static final String RESTLOGIN="http://192.168.0.102:8080/payroll-services-ws/api/secured/message";
private EditText usernameEditText;
private EditText passwordEdittext;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
progressBar =(ProgressBar)findViewById(R.id.progressBarLogin);
progressBar.setVisibility(View.INVISIBLE);
myTasksList = new ArrayList<>();
usernameEditText = (EditText)findViewById(R.id.etUsername);
passwordEdittext = (EditText)findViewById(R.id.etPass);
}
public void onBtnClick(View view){
Button buttonLogin = (Button)findViewById(R.id.btnSingIn);
if (view.getId()==R.id.btnSingIn){
//updateDisplay();
if (isOnline()){
requestData(RESTLOGIN);
}
else{
Toast.makeText(Login.this, "Not Connect WIth Network", Toast.LENGTH_LONG).show();
}
}
else if (view.getId()==R.id.btnSignUp){
Intent intent = new Intent(Login.this,Register.class);
startActivity(intent);
}
}
protected boolean isOnline(){
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivityManager != null) {
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isAvailable()
&& networkInfo.isConnected()) {
return true;
} else {
return false;
}
} else {
return false;
}
}
private void requestData(String uri){
MyTask myTask = new MyTask();
myTask.execute(uri,usernameEditText.getText().toString(),passwordEdittext.getText().toString());
}
public void updateDisplay(){
Toast.makeText(Login.this, "Login Successfull", Toast.LENGTH_SHORT).show();
Intent mainActivity = new Intent(Login.this,Home.class);
mainActivity.putExtra("username",usernameEditText.getText().toString());
mainActivity.putExtra("password",passwordEdittext.getText().toString());
startActivity(mainActivity);
}
//param progress and result
private class MyTask extends AsyncTask<String,String,String>{
#Override
protected void onPreExecute() {
if (myTasksList.size()==0){
progressBar.setVisibility(View.VISIBLE);
}
myTasksList.add(this);
}
#Override
protected String doInBackground(String... params) {
//param 0 which is come from requestData
String content = HttpManager.getData(params[0],params[1],params[2]);
return content;
}
//content of dobackground pass to the dopostexcute
#Override
protected void onPostExecute(String result) {
myTasksList.remove(this);
if (myTasksList.size()==0){
progressBar.setVisibility(View.INVISIBLE);
}
if (result==null){
Toast.makeText(Login.this,"Sorry Username or password doesnot match",Toast.LENGTH_LONG).show();
return;
}
//list of object from content
//from json
updateDisplay();
}
}
}
I can only access in postman via localhost:8080
problem occur due to the firewall of window 8.1 are blocking any public IP address, So editing the firewall setting esp TCP 80 port solve the problem for me.
I built an app that streams audio using a webview. Now I added a check if there's connectivity (or not). Using toast I show a message with "true" or "false", but I'd like show a toast only when the connectivity changes. What should I do?
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
update();
private void update() {
new Thread() {
public void run() {
while (true) {
runOnUiThread(new Runnable() {
#Override
public void run() {
isOnline();
}
});
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}.start();
}
public boolean isOnline() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
Toast.makeText(getApplicationContext(), "true",Toast.LENGTH_LONG).show();
return true;
}
Toast.makeText(getApplicationContext(), "false",Toast.LENGTH_LONG).show();
return false;
Try this :
public class BroadCastSampleActivity extends Activity {
/** Called when the activity is first created. */
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
this.registerReceiver(this.mConnReceiver,
new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
}
private BroadcastReceiver mConnReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
boolean noConnectivity = intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);
String reason = intent.getStringExtra(ConnectivityManager.EXTRA_REASON);
boolean isFailover = intent.getBooleanExtra(ConnectivityManager.EXTRA_IS_FAILOVER, false);
NetworkInfo currentNetworkInfo = (NetworkInfo) intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
NetworkInfo otherNetworkInfo = (NetworkInfo) intent.getParcelableExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO);
if(currentNetworkInfo.isConnected()){
Toast.makeText(getApplicationContext(), "Connected", Toast.LENGTH_LONG).show();
}else{
Toast.makeText(getApplicationContext(), "Not Connected", Toast.LENGTH_LONG).show();
}
}
};
}
Add this permission in your Manifest :
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
The ConnectivityManager broadcasts the CONNECTIVITY_ACTION ("android.net.conn.CONNECTIVITY_CHANGE") action whenever the connectivity details have changed. You can register a broadcast receiver in your manifest to listen for these changes and resume (or suspend) your background updates accordingly.
That comes from the android developer information.
You can read more here: http://developer.android.com/training/monitoring-device-state/connectivity-monitoring.html
That should have everything you need to show the toast notifications.
You should register for android.net.conn.CONNECTIVITY_CHANGE. And show a dialog only on receiving the intent.
You can create an inner class that extends a BroadcastReceiver and shows a toast in it's onReceive method.
That should work :)