How to check internet connection after reboot android every 5min? - java

Hello I just start learn java, and need to check internet connection after reboot device. But after reboot has error
My code:
BroadcastReceiver:
public class MainBroadcastReceiver extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
if ("android.intent.action.BOOT_COMPLETED".equals(intent.getAction())) {
MainService.startService(context);
}
}
Service:
public class MainService extends Service {
public static void startService(Context context) {
context.startService(new Intent(context, MainService.class));
}
Handler handler;
Runnable test;
public MainService() {
handler = new Handler();
test = new Runnable() {
#Override
public void run() {
qqq();
handler.postDelayed(test, 300000); // 5min
}
};
handler.postDelayed(test, 100);
}
public void qqq() {
// Check for Internet Connection
if (isConnected()) {
Toast.makeText(getApplicationContext(), "Internet Connected", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "No Internet Connection", Toast.LENGTH_SHORT).show();
}
}
public boolean isConnected() {
boolean connected = false;
try {
ConnectivityManager cm = (ConnectivityManager)getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo nInfo = cm.getActiveNetworkInfo();
connected = nInfo != null && nInfo.isAvailable() && nInfo.isConnected();
return connected;
} catch (Exception e) {
Log.e("Connectivity Exception", e.getMessage());
}
return connected;
}
But after reboot I have messege: "YourApp has stopped!"

For this to work, you need to add following permission in your manifest file.
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
Hope this helps.

Related

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

How to handle online media player on network state change (network shifts between WiFi or mobile data)?

In my app there is a media player which is playing streamed url.
The player starts in oncreate method when the connection to internet is available.I have a broadcast receiver which checks the connection to the internet and notify the user. I am facing a problem here that when my app shifts from Wifi to cellular network, media player should take a little pause and starts again because the network is available again. But i'am unable to find the logic that how can i achieve this?
Here is my sample code,Kindly solve the issue?
Any help will be grateful.
Manifest:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<receiver android:name=".receivers.NetworkChangeReciever">
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
</intent-filter>
</receiver>
Main Activity:
private BroadcastReceiver mNetworkReceiver;
static TextView tv_check_connection;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv_check_connection=(TextView) findViewById(R.id.tv_check_connection);
mNetworkReceiver = new NetworkChangeReciever();
registerNetworkBroadcastForNougat();
// checkNetworkStatus();
mSelectedTrackTitle = (TextView) findViewById(R.id.selected_track_title);
nowplaying = (TextView) findViewById(R.id.nowplaying);
mPlayerControl = (ImageView) findViewById(R.id.player_control);
mPlayerControl.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
togglePlayPause();
}
});
mSelectedTrackTitle.setText("FM World Pakistan");
nowplaying.setText("Now Playing");
mPlayerControl.setImageResource(R.drawable.ic_pause_circle_filled);
mMediaPlayer = new MediaPlayer();
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
mMediaPlayer.setDataSource(url);
mMediaPlayer.prepare();
mMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mMediaPlayer.start();
}
});
} catch (IOException e) {
e.printStackTrace();
nowplaying.setText("Offline");
Toast.makeText(MainActivity.this, "Radio Offline", Toast.LENGTH_LONG).show();
mPlayerControl.setImageResource(R.drawable.ic_play_circle_filled);
}
public static void dialog(boolean value){
if(value){
tv_check_connection.setText("We are back !!!");
tv_check_connection.setBackgroundResource(R.color.neton);
tv_check_connection.setTextColor(Color.WHITE);
Handler handler = new Handler();
Runnable delayrunnable = new Runnable() {
#Override
public void run() {
tv_check_connection.setVisibility(View.GONE);
}
};
handler.postDelayed(delayrunnable, 3000);
}else {
tv_check_connection.setVisibility(View.VISIBLE);
tv_check_connection.setText("Could not connect to Internet.");
tv_check_connection.setBackgroundResource(R.color.colorAccent);
tv_check_connection.setTextColor(Color.WHITE);
nowplaying.setText("Buffering...");
mPlayerControl.setImageResource(R.drawable.ic_play_circle_filled);
}
}
private void registerNetworkBroadcastForNougat() {
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();
}
}
private void togglePlayPause() {
if (mMediaPlayer.isPlaying()) {
mMediaPlayer.pause();
nowplaying.setText("Offline");
mPlayerControl.setImageResource(R.drawable.ic_play_circle_filled);
} else {
mMediaPlayer.start();
nowplaying.setText("Now Playing");
mPlayerControl.setImageResource(R.drawable.ic_pause_circle_filled);
}
}
#Override
protected void onDestroy() {
super.onDestroy();
unregisterNetworkChanges();
if (mMediaPlayer != null) {
if (mMediaPlayer.isPlaying()) {
mMediaPlayer.stop();
}
mMediaPlayer.release();
mMediaPlayer = null;
}
}
Receiver Class:
public class NetworkChangeReciever extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
try
{
if (isOnline(context)) {
dialog(true);
Log.e("Hi", "Online Connect Intenet ");
} else {
dialog(false);
Log.e("Sorry","Conectivity Failure !!! ");
}
} catch (NullPointerException e) {
e.printStackTrace();
}
}
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;
}
}
I found a solution as, if media player is declared as static; we can reinitialize it in dialog()
public static void dialog(boolean value){
if(value){
tv_check_connection.setText("We are back !!!");
tv_check_connection.setBackgroundResource(R.color.neton);
tv_check_connection.setTextColor(Color.WHITE);
//recreate media player
Handler handler = new Handler();
Runnable delayrunnable = new Runnable() {
#Override
public void run() {
tv_check_connection.setVisibility(View.GONE);
}
};
handler.postDelayed(delayrunnable, 3000);
}else {
tv_check_connection.setVisibility(View.VISIBLE);
tv_check_connection.setText("Could not connect to Internet.");
tv_check_connection.setBackgroundResource(R.color.colorAccent);
tv_check_connection.setTextColor(Color.WHITE);
nowplaying.setText("Buffering...");
mPlayerControl.setImageResource(R.drawable.ic_play_circle_filled);
//pause media player
}
}

WebService request response in Service when app is closed android

I have a Service class in my android app.
This service get user location and send location to server with ASP WebService.
Below is my service code :
public class ServiceSendLocation extends Service {
private static final String TAG = "ServiceSendLocation";
final long milliseconds_sleep = 3000;
private boolean isRunning = false;
#Override
public void onCreate() {
super.onCreate();
isRunning = true;
Log.i(TAG, "Service onCreate");
}
#Override
public int onStartCommand(Intent intent, int flags, final int startId) {
Log.i(TAG, "Service onStartCommand");
new Thread(new Runnable() {
#Override
public void run() {
while (true) {
try {
Thread.sleep(milliseconds_sleep);
} catch (Exception e) {}
getLocationAndSend();
if (isRunning)
Log.i(TAG, "Service running");
}
}
}
}).start();
return Service.START_STICKY;
}
private void getLocationAndSend() {
Log.i(TAG, "Service getLocationAndSend");
LocationManager locationManager = null;
LocationListener locationListener = new ServiceGetLocation();
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
Log.i(TAG, "Service PERMISSION_GRANTED");
try {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
HelperWS.register(structCheckUser.getUserId(), ServiceGetLocation.lat + "", ServiceGetLocation.lng + "", new HelperWS.InsertGpsDriver() {
#Override
public void onSuccess(StructInsertGpsDriver success) {
Log.i(TAG, "Success : " +ServiceGetLocation.lat + ", " + ServiceGetLocation.lng);
Toast.makeText(ServiceSendLocation.this, "success : " +ServiceGetLocation.lat + ", " + ServiceGetLocation.lng , Toast.LENGTH_SHORT).show();
}
#Override
public void onFail(String message) {
Log.i(TAG, "onFail");
}
});
} catch (Exception e) {}
} else {
Log.i(TAG, "Service PERMISSION_NOT_GRANTED");
}
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onDestroy() {
super.onDestroy();
isRunning = false;
Log.i(TAG, "Service onDestroy");
}
}
and in manifest :
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<application
...>
<service
android:name=".SendLocation.ServiceSendLocation" />
</application>
This code sends the location information to the server and get the response form WebService. But when app is closed this code get the location information and also send request but we don't get webService response
Somebody please help me.

Android Machine is not on the network

I am having a problem Running a network service when my app connects to a WiFi network.
I am getting a the following exception,
java.net.SocketException: socket failed: ENONET (Machine is not on the network) in the openPort() method bellow
BroadcastReceiver
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (WifiManager.NETWORK_STATE_CHANGED_ACTION.equals(action)) {
NetworkInfo networkInfo = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
if (networkInfo.getState() == NetworkInfo.State.CONNECTED) {
welcomeService = new BroadcastService(context, "Welcome");
Log.i(TAG, "onReceive: SUPPLICANT-STATE ---> Connected");
//do something
if (!serviceRegistered) {
welcomeService.registerService();
serviceRegistered = true;
}
}
if (networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
Log.i(TAG, "onReceive: SUPPLICANT-STATE ---> Disconnected");
//do something
unRegisterService();
}
}
}
public void unRegisterService() {
if (serviceRegistered && welcomeService != null) {
welcomeService.unregisterService();
serviceRegistered = false;
}
}
BroadcastService
public void registerService() {
NsdServiceInfo serviceInfo = new NsdServiceInfo();
serviceInfo.setServiceName(mServiceName);
serviceInfo.setServiceType("_http._tcp.");
serviceInfo.setPort(openPort());
mNsdManager = (NsdManager) mContext.getSystemService(Context.NSD_SERVICE);
mNsdManager.registerService(serviceInfo, NsdManager.PROTOCOL_DNS_SD, mRegistrationListener);
}
private int openPort() {
try{
// Line that throws the exception
return new ServerSocket(0).getLocalPort();
}catch (IOException ioe){
Crashlytics.logException(ioe);
ioe.printStackTrace();
return 0;
}
}
This the Broadcast Receiver only runs on when the main activity is showing. and it works fine on the first run but when I change the WiFi network this happens. Help world be greatly appreciated.
Use Service which start service and stop service when network would be change or when stop network.Also check same port which is using release first and after that use that port.Do whatever task you want in onStartCommand().
#Override
public void onReceive(Context context, Intent intent) {
Date now = new Date();
Long time = now.getTime();
String action = intent.getAction();
NetworkInfo networkInfo = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
if (networkInfo.getState() == NetworkInfo.State.CONNECTED) {
boolean check = isMyServiceRunning(context,
service.getName());
if (check) {
Intent i = new Intent(sqlitewraper.context,service.class);
stopService(i);
}
else{
Intent i = new Intent(sqlitewraper.context,service.class);
startservice(i);
}
}
if (networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
boolean check = isMyServiceRunning(context,
service.getName());
if (check) {
Intent i = new Intent(sqlitewraper.context,service.class);
stopService(i);
}
}
private boolean isMyServiceRunning(Context context, String Myservice) {
ActivityManager manager = (ActivityManager) context
.getSystemService(Context.ACTIVITY_SERVICE);
for (RunningServiceInfo service : manager
.getRunningServices(Integer.MAX_VALUE)) {
if (Myservice.equals(service.service.getClassName())) {
return true;
}
}
return false;
}
}

Android: Network connectivity check always fail

in my app there is a modul with a weather activity. When the user click and activate the weather function there is a check for network connectivity. The Problem is, direct on start, there comes my toast message "No network connectivity" with the Android Dialog to enable.
When the user click "enable" there is nothing to activate in the options (Everything is on).
When the user click "cancel" the Dialog disappears and the app is working.
Here is my code from the activity:
#Override
public void onNewIntent(Intent intent) {
super.onNewIntent(intent);
setIntent(intent);
}
#Override
public void onStart() {
super.onStart();
EasyTracker.getInstance(this).activityStart(this);
// Connect the client.
mLocationClient.connect();
// Registers BroadcastReceiver to track network connection changes.
mNetworkReceiver = new NetworkReceiver() {
private MyAlertDialog enableNetworkDialog = null;
#Override
public void onNoConnectivity() {
Toast.makeText(MainActivity.this,
getString(R.string.network_disabled), Toast.LENGTH_LONG)
.show();
// If the dialog already prompted, do nothing
if (enableNetworkDialog != null
&& enableNetworkDialog.isShowing())
return;
// Prompt a dialog for user to open the network settings screen
enableNetworkDialog = new MyAlertDialog(MainActivity.this,
null, getString(R.string.network_disabled), false);
enableNetworkDialog.setPositiveButton("Enable",
new OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
toggleNetworkSourceSetting();
}
});
enableNetworkDialog.setNegativeButton("Cancel",
new OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
dialog.dismiss();
}
});
enableNetworkDialog.show();
}
#Override
public void onConnect() {
if (enableNetworkDialog != null
&& enableNetworkDialog.isShowing())
enableNetworkDialog.dismiss();
}
#Override
public void onNetworkChange() {
}
#Override
public void onReconnect() {
}
};
}
UPDATE: This is my manifest:
<!-- Grant the network access permission -->
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
This are cutouts from my logcat:
[ 07-19 10:43:17.876 18037:18037 D/ ]
Current Network Info : NetworkInfo: type: mobile_supl[HSPA+, type_ext: mobile_supl], state: DISCONNECTED/DISCONNECTED, reason: dataDisabled, extra: internet.telekom, roaming: false, failover: false, isAvailable: true, isConnectedToProvisioningNetwork: false, isIpv4Connected: false, isIpv6Connected: false
[ 07-19 10:43:17.876 18037:18037 D/ ]
No network is available
07-19 10:43:19.778 18037-18037/bakteriusdeveloper.master D/Network Connection: mobile is available
Update super method:
/**
* The subclass of the BroadcastReeiver is used to detect the change of
* connectivity.
*
*/
public class NetworkReceiver extends BroadcastReceiver {
public NetworkReceiver() {
super();
}
public void onNoConnectivity() {
};
public void onNetworkChange() {
};
public void onConnect() {
};
public void onReconnect() {
};
public void toggleNetworkSourceSetting() {
startActivity(new Intent(
android.provider.Settings.ACTION_WIRELESS_SETTINGS));
}
#Override
public void onReceive(Context context, Intent intent) {
ConnectivityManager conn = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activNetworkInfo = conn.getActiveNetworkInfo();
String failMessage = intent
.getStringExtra(ConnectivityManager.EXTRA_REASON);
Logger.printMessage(getClass().getSimpleName(), failMessage,
Logger.DEBUG);
Boolean isNoConnectivity = intent.getBooleanExtra(
ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);
Boolean isFailOver = intent.getBooleanExtra(
ConnectivityManager.EXTRA_IS_FAILOVER, false);
Logger.printMessage(getClass().getSimpleName(), "is Failover: "
+ isFailOver, Logger.DEBUG);
Boolean isNetworkChanged = false;
NetworkInfo otherNetworkInfo = (NetworkInfo) intent
.getParcelableExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO);
NetworkInfo networkInfo = (NetworkInfo) intent
.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
Logger.printMessage(getClass().getSimpleName(),
"Current Network Info : " + networkInfo, Logger.DEBUG);
Logger.printMessage(getClass().getSimpleName(),
"Other Network Info : " + otherNetworkInfo, Logger.DEBUG);
if (networkInfo != null && networkInfo.isConnected()) {
if (isFailOver) {
Logger.printMessage(getClass().getSimpleName(),
"Network is re-connected and available now",
Logger.DEBUG);
onReconnect();
return;
} else {
Logger.printMessage(getClass().getSimpleName(),
"Network is available", Logger.DEBUG);
onConnect();
return;
}
} else if (networkInfo != null
&& !networkInfo.isConnectedOrConnecting()) {
// do application-specific task(s) based on the current network
// state, such
// as enabling queuing of HTTP requests when currentNetworkInfo
// is connected etc.
if (otherNetworkInfo != null
&& otherNetworkInfo.isConnectedOrConnecting()) {
isNetworkChanged = true;
} else {
Logger.printMessage(getClass().getSimpleName(),
"No network is available", Logger.DEBUG);
onNoConnectivity();
return;
}
}
// No network is active OR no network is available
if (activNetworkInfo == null || isNoConnectivity) {
if (isNetworkChanged) {
Logger.printMessage(getClass().getSimpleName(),
"Change network connectivity", Logger.DEBUG);
onNetworkChange();
return;
} else {
Logger.printMessage(getClass().getSimpleName(),
"No network is available", Logger.DEBUG);
onNoConnectivity();
return;
}
}
}
}
Whats wrong with my request? Any ideas?
You can register the NetworkReceiver in onResume instead of onStart and check if it works
Make sure you added network permissions in your AndroidManifest.xml:
<uses-permission android:name="android.permission.INTERNET" />
Register a broadcastreceiver in your manifest also:
<receiver
android:name=".NetworkReceiver"
android:enabled="true">
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
</intent-filter>
</receiver>
Then the NetworkReceiver class:
public class NetworkReceiver extends BroadcastReceiver {
private static volatile boolean connected;
#Override
public void onReceive(final Context context, final Intent intent) {
Log.d("Network", "Network changed");
if (intent.getExtras() != null) {
update();
}
}
public static void update() {
ConnectivityManager connectivityManager = (ConnectivityManager) ApplicationLoader
.applicationContext.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
connected = networkInfo != null && networkInfo.isConnected();
}
public static boolean isConnected() {
return connected;
}
}
Then if you want to check the network status call:
NetworkReceiver.update(); // Updates network status
if (NetworkReceiver.isConnected()) {
// do whatever you want.
}

Categories