I know this question might be replica of another question but can someone help me figure out where I have gone wrong and possibly correct it if possible?
public class MainActivity extends ActionBarActivity {
TextView ford;
public String TAG=MainActivity.class.getSimpleName();
protected static final long TIME_DELAY = 1000;
//the default update interval for your text, this is in your hand , just run this sample
TextView mTextView;
Handler handler=new Handler();
Random trust = new Random();
int count =0;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTextView=(TextView)findViewById(R.id.textview);}
protected void onResume({
super.onResume();handler.post(updateTextRunnable);}
ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
Runnable updateTextRunnable=new Runnable(){
public void run() {
if (networkInfo != null && networkInfo.isConnected()) {
mTextView.setText("connected!");
} else {
mTextView.setText("No network connection available.");
}
}
};
}
Efficient way is to create a broacast receiver which will reguralry check wifi status. Register receiver like this-
WifiMonitor wifiMonitor = new WifiMonitor();
registerReceiver(wifiMonitor, new IntentFilter(WifiManager.WIFI_STATE_CHANGED_ACTION));
registerReceiver(wifiMonitor, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
public class WifiMonitor extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
//do your work here
}
}
Related
Hi I have been creating an app that would check if the phone is using wifi or mobile data, using timerTask to inform the user and broadcast Receivers to check if WIFI or MOBILE DATA is open.
Even after I cancel the timerTask it goes to an Error notification and then the wifi notification runs again.
I have been stuck with this problem for hours now and I decided to ask for some help.
This is my MainActivity Class:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public String getConnectivityStatus(Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
String status = null;
if (null != activeNetwork) {
if(activeNetwork.getType() == ConnectivityManager.TYPE_WIFI)
status = "WIFI";
if(activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE)
status = "DATA";
}
else{
status = "ERROR";
}
return status;
}
And this is my NetworkChangeReceiver Class:
public class NetworkChangeReceiver extends BroadcastReceiver {
//WIFI TIMER
public void startWIFITimer() {
wifiTimer = new Timer();
initializeWIFITimer();
wifiTimer.schedule(wifiTimerTask, 1000, 5000);
}
public void stopWIFITimer() {
if (wifiTimer != null) {
wifiTimer.cancel();
wifiTimer = null;
}
}
public void initializeWIFITimer() {
wifiTimerTask = new TimerTask() {
public void run() {
wifiHandler.post(new Runnable() {
public void run() {displayNotificationWIFI();
}
});
}
};
}
#Override
public void onReceive(Context context, final Intent intent) {
contexts = context.getApplicationContext();
String status = main.getConnectivityStatus(context);
if (status.contains("WIFI")){
startWIFITimer();
}
else if (status.contains("DATA")){]
}
else if (status.contains("ERROR")){
displayNotificationERROR();
stopWIFITimer();
}
}
And if someone decides to downvote, it would be nice to get a reason why. Thanks again in advance for any help! :D
Each time you receive a broadcast message, a new instance of the BroadcastReceiver is created. So when you call stopWIFITimer() you are actually trying to stop a never started timer, because the started timer is an object of another instance of the BroadcastReceiver.
So, you should move your timer somewhere else.
So I just implemented a checking connectivity method, but should I do this for every activity? Is there a simpler way to continually check for connectivity?
public static boolean isNetworkAvailable(Context context) {
ConnectivityManager cm =
(ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean isConnected = activeNetwork != null &&
activeNetwork.isConnectedOrConnecting();
return isConnected;
}
First create a ConnectivityChangeReceiver like the following:
public class ConnectivityChangeReceiver extends BroadcastReceiver {
private OnConnectivityChangedListener listener;
public ConnectivityChangeReceiver(OnConnectivityChangedListener listener) {
this.listener = listener;
}
#Override
public void onReceive(Context context, Intent intent) {
ConnectivityManager connectivityManager = (ConnectivityManager)
context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
boolean isConnected = activeNetInfo != null && activeNetInfo.isConnectedOrConnecting();
listener.onConnectivityChanged(isConnected);
}
public interface OnConnectivityChangedListener {
void onConnectivityChanged(boolean isConnected);
}
}
Then create a BaseActivity which extends all of your activites:
public class BaseActivity extends Activity implements OnConnectivityChangedListener {
private ConnectivityChangeReceiver connectivityChangeReceiver;
#Override
public void onCreate(Bundle savedInstanceState) {
connectivityChangeReceiver = new ConnectivityChangeReceiver(this);
IntentFilter filter = new IntentFilter();
filter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
registerReceiver(connectivityChangeReceiver, filter);
}
#Override
public void onConnectivityChanged(boolean isConnected) {
// TODO handle connectivity change
}
#Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(connectivityChangeReceiver);
}
}
(If you don't want a BaseActivity, you can implement OnConnectivityChangedListener in all of your activities. But in that case you have to register the receiver in all of your Activity.)
You can check this out: This is service that will continuously check the connection. This will be the proper way to do it
`private void installListener() {
if (broadcastReceiver == null) {
broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Bundle extras = intent.getExtras();
NetworkInfo info = (NetworkInfo) extras
.getParcelable("networkInfo");
State state = info.getState();
Log.d("InternalBroadcastReceiver", info.toString() + " "
+ state.toString());
if (state == State.CONNECTED) {
onNetworkUp();
} else {
onNetworkDown();
}
}
};
final IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
registerReceiver(broadcastReceiver, intentFilter);
}
}`
Look on this link: Android service to check internet connectivity?
Create some sort of util class, for example ConnectionUtils.
Add a public static method to that class and add a Context object to the parameters. For example:
public static boolean isNetworkAvailable(Context context) {
ConnectivityManager cm = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting();
return isConnected;
}
Then in your Activity just call ConnectionUtils.isNetworkAvailable(this) to know if you're connected.
It would even be better to create some sort of base Activity that you extend with this method in it.
public abstract class BaseActivity extends Activity {
protected boolean isConnected() {
return ConnectionUtils.isNetworkAvailable(this);
}
}
And then let all your Activities extend BaseActivity instead of Activity
You should check before every request to the internet! The user can terminate the connection at any given time... even while your Activity is running.
I suggest you make an Utils class and put this method inside and make it public static so you can access it from everywhere within the Application.
I say it is better to check before every request. It might happen that the connection got broken in between. So its not wise to rely on a check sometime earlier
I want to show a TextView to current active activity if internet is not availabe.
I am getting internet state but how to notify it to current active activity (In which activity my concentration is).
public class NetworkChangeReceiver extends BroadcastReceiver {
#Override
public void onReceive(final Context context, final Intent intent)
{
final ConnectivityManager connMgr = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
final android.net.NetworkInfo wifi = connMgr
.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
final android.net.NetworkInfo mobile = connMgr
.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
if (wifi.isAvailable() || mobile.isAvailable()) {
Log.d("TAG", "Netowk Available");
} else {
//notify it to current active activity and show a textview as
//"No internet connection"
}
}
}
In your activity:
public class YourActivity extends Activity {
private TextView mTextView;
public static final String NETWORK_DISABLE_ACTION = "yourpackagename.action.network_disbale";
private LocalBroadcastManager mLocalBroadcastManager;
private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(NETWORK_DISABLE_ACTION)) {
mTextView.setText("No internet connection");
}
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.your_xml);
mTextView = (TextView) findViewById(R.id.your_textView_id);
mLocalBroadcastManager = LocalBroadcastManager.getInstance(this);
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(NETWORK_DISABLE_ACTION);
mLocalBroadcastManager.registerReceiver(mBroadcastReceiver, intentFilter);
}
#Override
protected void onDestroy() {
super.onDestroy();
mLocalBroadcastManager.unregisterReceiver(mBroadcastReceiver);
}
}
and in your NetworkChangeReceiver:
if (wifi.isAvailable() || mobile.isAvailable()) {
Log.d("TAG", "Netowk Available");
} else {
//notify it to current active activity and show a textview as
//"No internet connection"
LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent(
YourActivity.NETWORK_DISABLE_ACTION ));
}
String data ="";
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WifiManager mainWifiObj;
mainWifiObj = (WifiManager) getSystemService(Context.WIFI_SERVICE);
class WifiScanReceiver extends BroadcastReceiver
{
public void onReceive(Context c, Intent intent)
{
}
}
WifiScanReceiver wifiReciever = new WifiScanReceiver();
registerReceiver(wifiReciever, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
List<ScanResult> wifiScanList = mainWifiObj.getScanResults(); int signalLevel =
0; StringBuilder sb = new StringBuilder();
data = wifiScanList.get(8).toString();
TextView tv = new TextView(this);
tv.setText(sb);
setContentView(tv);
}
handler.post(runnable);
I want to add my timer such that this code should run 5 times and it should run every 2 seconds. I am new to android. I found the timer code from the internet, but whenever and whichever code i try to implement, it gives me error. Basically, I think I am not adding the code at proper place.
But, I am unaware, where should I keep it. In the oncreate method or the onCreate method should be between the run().
I am new so asked this question. Can anyone please help me out.
Here, the answers given run but I am unable to print the code
do something like this
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Runnable runnable = new Runnable() {
#Override
public void run() {
handler.postDelayed(this, 2000); //2 seconds
WifiManager mainWifiObj;
mainWifiObj = (WifiManager) getSystemService(Context.WIFI_SERVICE);
class WifiScanReceiver extends BroadcastReceiver {
public void onReceive(Context c, Intent intent) {
}
}
WifiScanReceiver wifiReciever = new WifiScanReceiver();
}
}; }}
//start it with:
handler.post(runnable);
hope this helps..
private Handler handler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
handler = new Handler();
Runnable runnable = new Runnable() {
#Override
public void run() {
handler.postDelayed(this, 2000); //2 seconds
//////Process to be executed every 2 seconds ////
WifiManager mainWifiObj;
mainWifiObj = (WifiManager) getSystemService(Context.WIFI_SERVICE);
class WifiScanReceiver extends BroadcastReceiver {
public void onReceive(Context c, Intent intent) {
}
}
WifiScanReceiver wifiReciever = new WifiScanReceiver();
//////////
}
};
//start it with:
handler.post(runnable);
}
You can create a BroadcastReceiver that handles wifi connection changes.
To be more precise, you will want to create a class - say NetWatcher:
public class NetWatcher extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
//here, check that the network connection is available. If yes, start your service. If not, stop your service.
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = cm.getActiveNetworkInfo();
if (info != null) {
if (info.isConnected()) {
//start service
Intent intent = new Intent(this, MyService.class);
startService(intent);
}
else {
//stop service
Intent intent = new Intent(this, MyService.class);
stopService(intent);
}
}
}}
Also, in your AndroidManifest, you need to add the following lines:
<receiver android:name="Yourpakege name.NetWatcher">
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE"/>
</intent-filter>
also more info : http://android-er.blogspot.in/2011/01/monitor-wifi-status-and-information.html
This question already has answers here:
Check INTENT internet connection
(13 answers)
Closed 4 years ago.
I am making an app where a user is uploading information and files to my server on a somewhat frequent basis. This is done in new threads through a dedicated uploader service.
I know from this thread
Detect whether there is an Internet connection available on Android
that you can check if there is an internet connection relatively easily. You can also get socketTimeoutExceptions to detect internet connectivity issues. All that is well and good, and lets me cache my uploads easily enough when the connection didn't work for whatever reason.
My question though is how do I know when to reattempt the upload? Is there an event triggered when the connection is restored? Or am I stuck making a new thread that sleeps and then checks internet connectivity every 30 seconds or something?
Any ideas would be appreciated!
very old post
but i would like to share my receiver
no need to put your hands on manifest or other boring resources :)
USAGE
YOUR ACTIVITY:
/*
* You need to implement NetworkStateReceiverListener.
* This interface is described inside the NewtworkStateReceiver class
*/
public class MyActivity implements NetworkStateReceiverListener {
/* ... */
private NetworkStateReceiver networkStateReceiver;
}
IN YOUR ACTIVITY: INSTANTIATE THE RECEIVER
public void onCreate(Bundle savedInstanceState) {
/* ... */
networkStateReceiver = new NetworkStateReceiver();
networkStateReceiver.addListener(this);
this.registerReceiver(networkStateReceiver, new IntentFilter(android.net.ConnectivityManager.CONNECTIVITY_ACTION));
}
public void onDestroy() {
super.onDestroy();
networkStateReceiver.removeListener(this);
this.unregisterReceiver(networkStateReceiver);
}
IN YOUR ACTIVITY: IMPLEMENTS THE REQUIRED METHODS
#Override
public void networkAvailable() {
Log.d("tommydevall", "I'm in, baby!");
/* TODO: Your connection-oriented stuff here */
}
#Override
public void networkUnavailable() {
Log.d("tommydevall", "I'm dancing with myself");
/* TODO: Your disconnection-oriented stuff here */
}
THE RECEIVER
just copy and paste into your project as NetworkStateReceiver.java
public class NetworkStateReceiver extends BroadcastReceiver {
protected Set<NetworkStateReceiverListener> listeners;
protected Boolean connected;
public NetworkStateReceiver() {
listeners = new HashSet<NetworkStateReceiverListener>();
connected = null;
}
public void onReceive(Context context, Intent intent) {
if(intent == null || intent.getExtras() == null)
return;
ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo ni = manager.getActiveNetworkInfo();
if(ni != null && ni.getState() == NetworkInfo.State.CONNECTED) {
connected = true;
} else if(intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY,Boolean.FALSE)) {
connected = false;
}
notifyStateToAll();
}
private void notifyStateToAll() {
for(NetworkStateReceiverListener listener : listeners)
notifyState(listener);
}
private void notifyState(NetworkStateReceiverListener listener) {
if(connected == null || listener == null)
return;
if(connected == true)
listener.networkAvailable();
else
listener.networkUnavailable();
}
public void addListener(NetworkStateReceiverListener l) {
listeners.add(l);
notifyState(l);
}
public void removeListener(NetworkStateReceiverListener l) {
listeners.remove(l);
}
public interface NetworkStateReceiverListener {
public void networkAvailable();
public void networkUnavailable();
}
}
ENJOY ;)
If you just want to do something simple when the connectivity changes, there is a much easier solution.
In your activity, create a Broadcast Receiver:
private BroadcastReceiver networkStateReceiver=new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo ni = manager.getActiveNetworkInfo();
doSomethingOnNetworkChange(ni);
}
};
Then in onResume and onPause do the registration:
#Override
public void onResume() {
super.onResume();
registerReceiver(networkStateReceiver, new IntentFilter(android.net.ConnectivityManager.CONNECTIVITY_ACTION));
}
#Override
public void onPause() {
unregisterReceiver(networkStateReceiver);
super.onPause();
}
Not quite sure what was going on in Tommaso's broadcast receiver but it wasn't working for me, here's my implementation. It only notifies on change between connectivity available/unavailable.
Also I register it in onResume() and unregister in onPause(). Otherwise it's the same as above.
public class NetworkStateReceiver extends BroadcastReceiver {
private ConnectivityManager mManager;
private List<NetworkStateReceiverListener> mListeners;
private boolean mConnected;
public NetworkStateReceiver(Context context) {
mListeners = new ArrayList<NetworkStateReceiverListener>();
mManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
checkStateChanged();
}
public void onReceive(Context context, Intent intent) {
if (intent == null || intent.getExtras() == null)
return;
if (checkStateChanged()) notifyStateToAll();
}
private boolean checkStateChanged() {
boolean prev = mConnected;
NetworkInfo activeNetwork = mManager.getActiveNetworkInfo();
mConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting();
return prev != mConnected;
}
private void notifyStateToAll() {
for (NetworkStateReceiverListener listener : mListeners) {
notifyState(listener);
}
}
private void notifyState(NetworkStateReceiverListener listener) {
if (listener != null) {
if (mConnected) listener.onNetworkAvailable();
else listener.onNetworkUnavailable();
}
}
public void addListener(NetworkStateReceiverListener l) {
mListeners.add(l);
notifyState(l);
}
public void removeListener(NetworkStateReceiverListener l) {
mListeners.remove(l);
}
public interface NetworkStateReceiverListener {
public void onNetworkAvailable();
public void onNetworkUnavailable();
}
}
Android Nougat & O (API 24+) - Network State
Changes mades to #darnmason answer (constructor) to make it work on API 24+.
public NetworkStateReceiver(Context context) {
mListeners = new ArrayList<>();
mManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
context.registerReceiver(NetworkStateReceiver.this, intentFilter);
checkStateChanged();
}