I am aiming to build a android app which record everything going on with devices WiFi adapter. For example WiFi being turned on/off, device getting connected/moving out of range of a WiFi router, etc.
My app should be able to record these events as soon as the device is turned on. Clearing the app from RECENTS should not affect the ability of the app to record these events.
I have gone through BroadcastReceiver. It gets tied to the life cycle of the app and hence will not record the events once app gets cleared from RECENTS.
public class MainActivity extends Activity {
BroadcastReceiver mybroadcastReceiver;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mybroadcastReceiver = new WifiBroadcastReceiver(this);
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(WifiManager.SUPPLICANT_STATE_CHANGED_ACTION);
registerReceiver(mybroadcastReceiver, intentFilter);
}
#Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(mybroadcastReceiver);
}
}
public class WifiBroadcastReceiver extends BroadcastReceiver {
final String TAG = "WifiBroadcastReceiver";
final String desiredMacAddress = "02:17:1c:96:42:fa";
Activity activity;
WifiBroadcastReceiver(Activity activity) {
this.activity = activity;
}
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (WifiManager.SUPPLICANT_STATE_CHANGED_ACTION.equals(action)) {
SupplicantState state = intent.getParcelableExtra(WifiManager.EXTRA_NEW_STATE);
if (SupplicantState.isValidState(state) && state == SupplicantState.COMPLETED)
checkConnectedToDesiredWifi();
}
}
/** Detect you are connected to a specific network. */
private void checkConnectedToDesiredWifi() {
WifiManager myWifiManager = (WifiManager)activity.getSystemService(Context.WIFI_SERVICE);
WifiInfo wifiInfo = myWifiManager.getConnectionInfo();
if (wifiInfo != null) {
// get current router MAC address
String bssid = wifiInfo.getBSSID();
if (desiredMacAddress.equals(bssid))
Log.d(TAG, "Connected to " + bssid + " i.e., desiredMacAddress");
else
Log.d(TAG, "Connected to " + bssid + " not " + desiredMacAddress);
}
}
}
One solution could be to run the BroadcastReceiver from a Service that doesn't depend on the lifecycle of any Activity.
1) Declare the network state permission usage in the manifest
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
1) Create a Service class
public class WifiService extends Service {
private BroadcastReceiver mReceiver;
#Nullable
#Override
public IBinder onBind(Intent intent) {
// When creating the service, register a broadcast receiver
// to listen for network state changes
IntentFilter filter = new IntentFilter();
filter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
mReceiver = new WifiReceiver();
registerReceiver(mReceiver, filter);
return null;
}
#Override
public boolean onUnbind(Intent intent) {
// Unregister the receiver when unbinding the service
unregisterReceiver(mReceiver);
mReceiver = null;
return super.onUnbind(intent);
}
}
2) Create a BroadcastReceiver
public class WifiReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = manager.getActiveNetworkInfo();
boolean isConnected = networkInfo != null &&
networkInfo.isConnectedOrConnecting();
if (isConnected) {
switch (networkInfo.getType()) {
case ConnectivityManager.TYPE_WIFI:
// Connected via wifi
checkConnectedToDesiredWifi();
break;
case ConnectivityManager.TYPE_ETHERNET:
// Connected via ethernet
break;
case ConnectivityManager.TYPE_MOBILE:
// Connected via mobile data
break;
}
}
}
private void checkConnectedToDesiredWifi() {
// ...
}
}
3) Declare the service in the manifest
<service android:name=".receivers.WifiService"
android:stopWithTask="false"
android:enabled="true"/>
Related
I have updated target version from Android 8 to Android 10 after that I am facing an issue that broadcast receiver is not being called on devices(I have tested on Samsung s9(Pie), Mi Note 5(Oreo)) accept Google Pixel 2 XL device(Android 10) but it's working fine on Genymotion Samsung s9 emulator or any emulator. Can anybody tell what could be the possible issue?
There is Service called SipService inside that it registering the Intent filters and we trigger one of the Intent filter from one of the activity. Some codes are as below.
ACtivity
inside onCreate() method
registerReceiver(registrationStateReceiver, new IntentFilter(SipManager.ACTION_SIP_REGISTRATION_CHANGED));
bindService(new Intent(mContext, SipService.class), connection, Context.BIND_AUTO_CREATE);
And after some Webservice calls and operation we are calling one of the registered Intent Filter as below.
Intent intent = new Intent(SipManager.ACTION_SIP_REQUEST_RESTART);
sendBroadcast(intent);
Inside SipService class
private void registerBroadcasts() {
// Register own broadcast receiver
if (deviceStateReceiver == null) {
IntentFilter intentfilter = new IntentFilter();
intentfilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
intentfilter.addAction(SipManager.ACTION_SIP_ACCOUNT_CHANGED);
intentfilter.addAction(SipManager.ACTION_SIP_ACCOUNT_DELETED);
intentfilter.addAction(SipManager.ACTION_SIP_CAN_BE_STOPPED);
intentfilter.addAction(SipManager.ACTION_SIP_REQUEST_RESTART);
intentfilter.addAction(DynamicReceiver4.ACTION_VPN_CONNECTIVITY);
if (Compatibility.isCompatible(5)) {
deviceStateReceiver = new DynamicReceiver5(this);
} else {
deviceStateReceiver = new DynamicReceiver4(this);
}
registerReceiver(deviceStateReceiver, intentfilter);
deviceStateReceiver.startMonitoring();
}
}
Receiver Class
public class DynamicReceiver4 extends BroadcastReceiver {
private static final String THIS_FILE = "DynamicReceiver";
// Comes from android.net.vpn.VpnManager.java
// Action for broadcasting a connectivity state.
public static final String ACTION_VPN_CONNECTIVITY = "vpn.connectivity";
/** Key to the connectivity state of a connectivity broadcast event. */
public static final String BROADCAST_CONNECTION_STATE = "connection_state";
private SipService service;
// Store current state
private String mNetworkType;
private boolean mConnected = false;
private String mRoutes = "";
private boolean hasStartedWifi = false;
private Timer pollingTimer;
/**
* Check if the intent received is a sticky broadcast one
* A compat way
* #param it intent received
* #return true if it's an initial sticky broadcast
*/
public boolean compatIsInitialStickyBroadcast(Intent it) {
if(ConnectivityManager.CONNECTIVITY_ACTION.equals(it.getAction())) {
if(!hasStartedWifi) {
hasStartedWifi = true;
return true;
}
}
return false;
}
public DynamicReceiver4(SipService aService) {
service = aService;
}
#Override
public void onReceive(final Context context, final Intent intent) {
// Run the handler in SipServiceExecutor to be protected by wake lock
service.getExecutor().execute(new SipService.SipRunnable() {
public void doRun() throws SipService.SameThreadException {
onReceiveInternal(context, intent, compatIsInitialStickyBroadcast(intent));
}
});
}
/**
* Internal receiver that will run on sip executor thread
* #param context Application context
* #param intent Intent received
* #throws SameThreadException
*/
private void onReceiveInternal(Context context, Intent intent, boolean isSticky) throws SipService.SameThreadException {
String action = intent.getAction();
Log.d(THIS_FILE, "Internal receive " + action);
if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
ConnectivityManager cm =
(ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
onConnectivityChanged(activeNetwork, isSticky);
} else if (action.equals(SipManager.ACTION_SIP_ACCOUNT_CHANGED)) {
final long accountId = intent.getLongExtra(SipProfile.FIELD_ID, SipProfile.INVALID_ID);
// Should that be threaded?
if (accountId != SipProfile.INVALID_ID) {
final SipProfile account = service.getAccount(accountId);
if (account != null) {
Log.d(THIS_FILE, "Enqueue set account registration");
service.setAccountRegistration(account, account.active ? 1 : 0, true);
}
}
} else if (action.equals(SipManager.ACTION_SIP_ACCOUNT_DELETED)){
final long accountId = intent.getLongExtra(SipProfile.FIELD_ID, SipProfile.INVALID_ID);
if(accountId != SipProfile.INVALID_ID) {
final SipProfile fakeProfile = new SipProfile();
fakeProfile.id = accountId;
service.setAccountRegistration(fakeProfile, 0, true);
}
} else if (action.equals(SipManager.ACTION_SIP_CAN_BE_STOPPED)) {
service.cleanStop();
} else if (action.equals(SipManager.ACTION_SIP_REQUEST_RESTART)){
service.restartSipStack();
} else if(action.equals(ACTION_VPN_CONNECTIVITY)) {
onConnectivityChanged(null, isSticky);
}
}
Actually, My bad it was basically ABI(Application Binary Interface) issue that causing the issue in bit 64 devices.
community,
this is my first question, so please tell me if I accidentally don't match some norms or similiar.
I am trying to code an android application that communicates with WiFi direct.
Everything works smooth at this point, but my BroadcastReceiver receives the android.net.wifi.p2p.PEERS_CHANGED action again and again.
public class WifiP2PBroadcastReceiver extends BroadcastReceiver {
private final static String TAG = "WifiP2PBR";
private WifiP2pManager _manager;
private WifiP2pManager.Channel _channel;
private Activity _callbackActivity;
private static ArrayList<WifiBroadcastCallback> _arrayList_callbacks;
public WifiP2PBroadcastReceiver(WifiP2pManager manager, WifiP2pManager.Channel channel, Activity callback) {
_manager = manager;
_channel = channel;
_callbackActivity = callback;
}
/**
* add a callback to the receiver
*
* #param callback
*/
public static void addWifiCallback(WifiBroadcastCallback callback) {
if(!getCallbacksList().contains(callback))
{
getCallbacksList().add(callback);
}
}
public void registerReceiver()
{
Log.d(TAG,"registerReceiver called");
if(_callbackActivity != null) {
_callbackActivity.registerReceiver(this, getIntentFilter());
}
}
public void unregisterReceiver() {
if(_callbackActivity != null) {
_callbackActivity.unregisterReceiver(this);
}
}
#Override
public final void onReceive(Context context, Intent intent) {
Log.d(TAG, "action: "+intent.getAction());
switch(intent.getAction()) {
case WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION:
Log.d(TAG, "state changed action");
break;
case WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION:
Log.d(TAG, "peers changed action");
notifyPeerUpdate();
break;
case WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION:
Log.d(TAG, "wifi p2p connection changed action");
NetworkInfo networkInfo = intent.getParcelableExtra(WifiP2pManager.EXTRA_NETWORK_INFO);
Log.d(TAG,"network info available");
break;
case WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION:
Log.d(TAG, "wifi p2p this device changed action");
notifyDeviceUpdate();
WifiP2pDevice thisDevice = intent.getParcelableExtra(WifiP2pManager.EXTRA_WIFI_P2P_DEVICE);
Log.d(TAG,"this device acquired");
break;
}
}
private void notifyPeerUpdate()
{
for(WifiBroadcastCallback c : getCallbacksList())
{
c.onPeersChanged();
}
}
private void notifyDeviceUpdate()
{
for(WifiBroadcastCallback c : getCallbacksList())
{
c.onDeviceChanged();
}
}
/**
* get array list of callbacks
*
* #return
*/
private static ArrayList<WifiBroadcastCallback> getCallbacksList() {
if(_arrayList_callbacks == null) {
_arrayList_callbacks = new ArrayList<WifiBroadcastCallback>();
}
return _arrayList_callbacks;
}
/**
* interface for callbacks
*/
public interface WifiBroadcastCallback {
void onDeviceChanged();
void onPeersChanged();
}
private IntentFilter getIntentFilter()
{
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION);
intentFilter.addAction(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION);
intentFilter.addAction(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION);
intentFilter.addAction(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION);
return intentFilter;
}
}
this is my BroadcastReceiver code. Everything else works fine and I'm out of ideas, it started out of the nowhere.
That's how it works indeed. Basically, what you should do there, is to call requestPeers with your instance of WifiP2pManager. Then you onPeersAvailable from WifiP2pManager.PeerListListener would be called with the array of peers seen, and there you could then check whether the change is something that you want to report.
reference implementation can be found from my github projects
I want to check Internet connection throughout the run time of my Android application. I tried using services but seems like it is not the best option. Is there any possible way for me to implement a broadcast receiver with in a service? Or do I have to give up the service and use broadcast receivers alone?
I will show you how to create SMS receiver in a service:
public class MyService extends Service {
#Override
public void onCreate() {
BwlLog.begin(TAG);
super.onCreate();
SMSreceiver mSmsReceiver = new SMSreceiver();
IntentFilter filter = new IntentFilter();
filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
filter.addAction(SMS_RECEIVE_ACTION); // SMS
filter.addAction(WAP_PUSH_RECEIVED_ACTION); // MMS
this.registerReceiver(mSmsReceiver, filter);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
return START_STICKY;
}
/**
* This class used to monitor SMS
*/
class SMSreceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if (TextUtils.equals(intent.getAction(), SMS_RECEIVE_ACTION)) {
//handle sms receive
}
}
}
It wouldn't be wise to check for the connectivity every second. Alternatively you can listen to the action (ConnectivityManager.CONNECTIVITY_ACTION) and identify if you are connected to an active network or not.
IntentFilter filter = new IntentFilter();
filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
Additionally you can check the network Type that is currently active(Type_WIFI, Type_MOBILE)
This way, you don't need a service that keeps checking the connectivity every second.
You need not to use Service or BroadCastReceiver for this purpose. Just check Connection status everyTime you need to ping the server.
you can write a method which checks this and returns a boolean(true/false) according to connection status.
Below method does the same.
public static boolean isNetworkAvailable(Context mContext) {
try {
final ConnectivityManager conn_manager = (ConnectivityManager) mContext
.getSystemService(Context.CONNECTIVITY_SERVICE);
final NetworkInfo network_info = conn_manager
.getActiveNetworkInfo();
if (network_info != null && network_info.isConnected()) {
if (network_info.getType() == ConnectivityManager.TYPE_WIFI)
return true;
else if (network_info.getType() == ConnectivityManager.TYPE_MOBILE)
return true;
}
} catch (Exception e) {
// TODO: handle exception
}
return false;
}
First of all I'm a novice to android, so this could probably be a silly issue, nevertheless I've already spent a couple of days trying to get to a solution.
I'm trying to build a wifi module for localization purpouses, so I wrote a BroadcastReceiver in order to handle the wifi scanning and the localization. The application works and does its (quite simple at this stage) job, with anu kind of issues both when I change the orientation of the screen and when I hit the back button on my Desire HD and then open the application again. But when I hit the HOME key, going to the main screen, and then enter again my app the Broadcast Receiver seems not to work anymore, and if I close the application I get an error message.
Here's the code, partially adapted from here.
public class WiFiDemo extends Activity implements OnClickListener {
private static final String TAG = "WiFiDemo";
WifiManager wifi;
BroadcastReceiver receiver;
WifiManager.WifiLock lock;
boolean wifiPrevState;
boolean scanON = false;
String header;
TextView textStatus;
Button buttonScan;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Setup UI
textStatus = (TextView) findViewById(R.id.textStatus);
buttonScan = (Button) findViewById(R.id.buttonScan);
buttonScan.setOnClickListener(this);
// Setup WiFi
if (wifi == null){
wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
}
//checking WiFi status, enabling it if needed and locking it.
wifiPrevState = wifi.isWifiEnabled();
wifi.setWifiEnabled(true);
if (lock == null){
lock = wifi.createWifiLock("lock");
}
lock.acquire();
// Get WiFi status
WifiInfo info = wifi.getConnectionInfo();
header="\n\nWiFi Status: \n" + info.toString() + "\n\nAvailable nets:";
textStatus.append(header);
// Register Broadcast Receiver
if (receiver == null)
receiver = new WiFiScanReceiver(this);
registerReceiver(receiver, new IntentFilter(
WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
Log.d(TAG, "onCreate()");
}
/*
#Override
protected void onPause(){
super.onPause();
wifi.setWifiEnabled(wifiPrevState);
lock.release();
unregisterReceiver(receiver);
Log.d(TAG, "onPause()");
}
#Override
protected void onResume(){
super.onResume();
wifi.setWifiEnabled(true);
lock.acquire();
registerReceiver(receiver, new IntentFilter(
WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
Log.d(TAG, "onResume()");
}
*/
#Override
public void onStop() {
super.onStop();
wifi.setWifiEnabled(wifiPrevState);
lock.release();
unregisterReceiver(receiver);
}
public void onClick(View view) {
Toast.makeText(this, "On Click Clicked. Toast to that!!!",
Toast.LENGTH_LONG).show();
if (view.getId() == R.id.buttonScan) {
Log.d(TAG, "onClick() wifi.startScan()");
scanON = !scanON;
wifi.startScan();
}
}
}
And this is the BroadcastReceiver
public class WiFiScanReceiver extends BroadcastReceiver {
private static final String TAG = "WiFiScanReceiver";
WiFiDemo wifiDemo;
ScanResult storedBest;
public WiFiScanReceiver(WiFiDemo wifiDemo) {
super();
this.wifiDemo = wifiDemo;
storedBest = null;
}
#Override
public void onReceive(Context c, Intent intent) {
List<ScanResult> results = wifiDemo.wifi.getScanResults();
ScanResult bestSignal = null;
wifiDemo.textStatus.setText(wifiDemo.header);
for (ScanResult result : results) {
if (bestSignal == null
|| WifiManager.compareSignalLevel(bestSignal.level, result.level) < 0)
bestSignal = result;
wifiDemo.textStatus.append("\n\n" + result.toString());
}
if ( storedBest == null || ((bestSignal.SSID.compareTo(storedBest.SSID)!=0) && bestSignal.level>-50)){
storedBest = bestSignal;
String locationMessage = String.format("You are near %s's Access Point",
bestSignal.SSID);
Toast.makeText(wifiDemo, locationMessage, Toast.LENGTH_LONG).show();
}
String message = String.format("%s networks found. %s is the strongest. Its level is %s",
results.size(), bestSignal.SSID, bestSignal.level);
if (wifiDemo.scanON) wifiDemo.wifi.startScan();
Log.d(TAG, "onReceive() message: " + message);
}
}
When posting, its best to post the error message that you are getting so we know the problem you are having.
That being said, the reason it probably isn't working is because you unregister your receiver in onStop and you only register your receiver in onCreate. You should typically do these type of calls in life cycle stages that match.
onCreate/onDestroy
onStart/onStop
onResume/onPause.
To fix your problem, try registering your receiver in onStart instead of onCreate.
Your onResume() method is commented out...
Are you sure that's the correct IntentFilter?
I have a Wifi class that has a couple of broadcast receivers that listen out for changes in Wifi connection state, Wifi Rssi levels etc...
I want to be able to pass this data to another "Engine" Object and still keep the data changing dynamically.
I currently create a Wifi object within the "Engine" class and run its methods, the data is then dynamically displayed fine in Log statements in the log cat.
My problem is trying to get the dynamically changing data to the Engine, when I try to get data over it gets the first value and leaves it at that without ever updating.
So I was wondering what my options are on how to do this?
Below is my current code setup if that is any help:
Wifi Class
public Wifi(Context context){
mainWifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
}
public int getCurrentWifiState() {
return currentWifiState;
}
public void setCurrentWifiState(int currentWifiState) {
this.currentWifiState = currentWifiState;
}
public String getConnectedSSID() {
return connectedSSID;
}
public void setConnectedSSID(String connectedSSID) {
this.connectedSSID = connectedSSID;
}
public int getConnectedLevel() {
return connectedLevel;
}
public void setConnectedLevel(int connectedLevel) {
this.connectedLevel = connectedLevel;
}
//method to do a scan and receive info about all access points available
public List<ScanResult> scan(final Context context){
receiverWifi = new WifiReceiver();
mainWifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
context.registerReceiver(receiverWifi, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
mainWifi.startScan();
Log.d("WIFI DEBUG","\nStarting Scan...\n");
wifiList = mainWifi.getScanResults();
return wifiList;
}
class WifiReceiver extends BroadcastReceiver {
public void onReceive(Context c, Intent intent) {
sb = new StringBuilder();
wifiList = mainWifi.getScanResults();
ListIterator<ScanResult> results = wifiList.listIterator();
while (results.hasNext()) {
ScanResult info = results.next();
String wifiInfo = "Name: " + info.SSID + "; capabilities = " + info.capabilities + "; sig str = " + info.level + "dBm";
Log.v("WiFi", wifiInfo);
Log.d("Signal Level", "Signal Level : " + mainWifi.calculateSignalLevel(info.level, 5));
}
}
}
//method to listen for changes in the level of the wifi connection
public void initializeWiFiListener(Context context){
Log.d("WIFI", "executing initializeWiFiListener");
String connectivity_context = Context.WIFI_SERVICE;
final WifiManager wifi = (WifiManager)context.getSystemService(connectivity_context);
if(!wifi.isWifiEnabled()){
if(wifi.getWifiState() != WifiManager.WIFI_STATE_ENABLING){
//wifi.setWifiEnabled(true);
}
}
rssiListener = new BroadcastReceiver(){
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if(WifiManager.RSSI_CHANGED_ACTION.equals(action)){
WifiInfo data = mainWifi.getConnectionInfo();
Log.d("WIFI", "RSSI has changed");
if(mainWifi.getConnectionInfo()!=null){
setConnectedSSID(data.getSSID());
setConnectedLevel(data.getRssi());
Log.d("WIFI", "new RSSI = " + data.getSSID()+ " " + data.getRssi() + "dBm");
}
}
}
};
//leak here - need to de reg receiver
context.registerReceiver(rssiListener, new IntentFilter(WifiManager.RSSI_CHANGED_ACTION));
}
//method to listen for changes in the connection to a wifi access point
public void changeWiFiListener(Context context){
Log.d("WIFI", "executing initializeWiFiListener");
String connectivity_context = Context.WIFI_SERVICE;
final WifiManager wifi = (WifiManager)context.getSystemService(connectivity_context);
if(!wifi.isWifiEnabled()){
if(wifi.getWifiState() != WifiManager.WIFI_STATE_ENABLING){
//wifi.setWifiEnabled(true);
}
}
wifiChangeListener = new BroadcastReceiver(){
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if(WifiManager.WIFI_STATE_CHANGED_ACTION.equals(action)){
Log.d("WIFI", "WIFI has changed");
int wifiState = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, -1);
Log.d("WIFI", "WIFI State = " + wifiState);
setCurrentWifiState(wifiState);
}
}
};
//Leak here - not unregistering receiver
context.registerReceiver(wifiChangeListener, new IntentFilter(WifiManager.WIFI_STATE_CHANGED_ACTION));
}
public WifiReceiver getReceiverWifi() {
return receiverWifi;
}
public void setReceiverWifi(WifiReceiver receiverWifi) {
this.receiverWifi = receiverWifi;
And my Engine Code:
public Engine(Context aContext){
context = aContext;
cm = new CallManager(aContext);
wifiManager = new Wifi(context);
wifiManager.initializeWiFiListener(context);
wifiManager.changeWiFiListener(context);
clc = new CallLogController();
}
public void controlCalls(){
int currentWifiState = wifiManager.getCurrentWifiState();
cm.monitorOutgoingCalls(context, currentWifiState, clc);
}
public void unRegAllRecievers(){
wifiManager.unregRegisters(context);
cm.unRegReciever(context);
}
public void doWifiScan(){
scanTask = new TimerTask() {
public void run() {
handler.post(new Runnable() {
public void run() {
wifiManager.scan(context);
Log.d("TIMER", "Timer set off");
}
});
}};
t.schedule(scanTask, 300, 30000);
}
public void stopScan(){
scanTask.cancel();
t.cancel();
//boolean tf = scanTask.cancel();
//Log.d("TIMER", "Timer True or False? : " + tf);
}
}
So I'm just wondering what would be the best solution to make sure the data from the Wifi class is constantly updated in the engine when it receives changes from the broadcast receiver?
depends if your class, the one that should be notified of the latest state.
If it's a class that is not created in an Activity and is static (singletone or Application based) then you should probably have the Reciver update the singletone class.
If it's Activity based, you need stick Broadcasts, and once the broadcast is recieved remove the sticky broadcast.