Reputation: 548
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
Upvotes: 0
Views: 151
Reputation: 17429
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.
Upvotes: 3