I want to detect address by reverse geocoding, so to achieve that I have created a class named FetchAddressIntentService that extends IntentService and also have done all the steps as on https://developer.android.com/training/location/display-address.html
When startService(intent) inside startIntentService() is called, exception(below) is thrown
java.lang.RuntimeException: Unable to instantiate service PACKAGENAME.MainActivity$FetchAddressIntentService: java.lang.InstantiationException: java.lang.Class PACKAGENAME.MainActivity$FetchAddressIntentService has no zero argument constructor
Defining intent service in my AndroidManifest.xml(below)
<service
android:name=".MainActivity$FetchAddressIntentService"
android:exported="false"/>
</application>
My startIntentService method(below)
void startIntentService(){
Intent intent = new Intent(this,FetchAddressIntentService.class);
intent.putExtra(FetchAddressIntentService.Constants.RECEIVER,myResultReciever);
intent.putExtra(FetchAddressIntentService.Constants.LOCATION_DATA_EXTRA,lastDetectedLocation);
startService(intent);
}
My FetchAddressIntentService class(below)
public class FetchAddressIntentService extends IntentService{
ResultReceiver myReciever;
public FetchAddressIntentService(){
super("Fetching address");
}
#Override
protected void onHandleIntent(#Nullable Intent intent) {
Geocoder geocoder = new Geocoder(this, Locale.getDefault());
String errorMessage = "";
//Get the location passed to this serviec thorugh an extra
Location location = intent.getParcelableExtra(Constants.LOCATION_DATA_EXTRA);
List<Address> address = null;
try{
address = geocoder.getFromLocation(location.getLatitude(),location.getLongitude(),1);
}
catch(Exception e){
Toast.makeText(this,e.getMessage(), Toast.LENGTH_LONG).show();
}
//Handle the case when there is no location found
if(address == null || address.size() == 0){
Toast.makeText(this, "No address found", Toast.LENGTH_LONG).show();
deliverResulttoReciever(Constants.FAILURE_RESULT,"No address Found");
}
else{
Address currentAddress = address.get(0);
ArrayList<String> addressFragment = new ArrayList<String>();
//Fetch the address lines using getAddressLine
//join them and send them to the thread
for(int i = 0;i<=currentAddress.getMaxAddressLineIndex();i++)
{
addressFragment.add(currentAddress.getAddressLine(i));
}
deliverResulttoReciever(Constants.SUCCESS_RESULT, TextUtils.join(System.getProperty("line.saparator"),addressFragment));
}
}
private void deliverResulttoReciever(int resultCode, String message) {
Bundle bundle = new Bundle();
bundle.putString(Constants.RESULT_DATA_KEY,message);
myReciever.send(resultCode,bundle);
}
public final class Constants {
public static final int SUCCESS_RESULT = 0;
public static final int FAILURE_RESULT = 1;
public static final String PACKAGE_NAME =
"com.google.android.gms.location.sample.locationaddress";
public static final String RECEIVER = PACKAGE_NAME + ".RECEIVER";
public static final String RESULT_DATA_KEY = PACKAGE_NAME +
".RESULT_DATA_KEY";
public static final String LOCATION_DATA_EXTRA = PACKAGE_NAME +
".LOCATION_DATA_EXTRA";
}
}
Try this :
change your service class to static:
public static class FetchAddressIntentService extends IntentService {
public FetchAddressIntentService(){
super("Fetching address");
}
For more information Read this
Related
I would like to update a view from within an open activity when the device receives a push notification.
When a push notification is received the updateBalance function is executed,
a mysql database is queried and an amount is returned.
public class MyFirebaseMessagingService extends FirebaseMessagingService {
private void updateBalance(String messageBody) {
h1 = new Handler(Looper.getMainLooper()) {
#Override
public void handleMessage(Message msg) {
bb = msg.getData();
String str = bb.getString("result");
Log.d(TAG,str);
Message msg=handler.obtainMessage()
}
};
t = new Thread(new MyRunnable(h1));
t.start();
try {
t.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
I have another class
public class MyRunnable implements Runnable {
private Handler h2;
public MyRunnable(Handler h) {
this.h2 = h;
}
#Override
public void run() {
String name = "w12";
BalanceActivity NB = new BalanceActivity(name);
Message m = Message.obtain();
Bundle b = new Bundle();
b.putString("result", "10");
m.setData(b);
h2.sendMessage(m);
}
}
I have a MainActivity that I would like to update after the amount is returned. How would I do this possibly with another Handler and Runnable.
public class MainActivity extends Activity {
TextView TV = (TextView) findViewById(package.name.R.id.Balance);
}
Try to check your activity is currently in foreground. if yes then create method where you can update your view.
public static boolean isServiceRunning(Context context) {
Log.i(TAG, "Checking if service is running");
ActivityManager activityManager = (ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE);
List<RunningServiceInfo> services = activityManager.getRunningServices(Integer.MAX_VALUE);
boolean isServiceFound = false;
for (int i = 0; i < services.size(); i++) {
if (Constants.PACKAGE.equals(services.get(i).service.getPackageName())){
if (Constants.BACKGROUND_SERVICE_CLASS.equals(services.get(i).service.getClassName())){
isServiceFound = true;
}
}
}
Log.i(TAG, "Service was" + (isServiceFound ? "" : " not") + " running");
return isServiceFound;
}
Make use of Broadcast Receivers. Register local broadcast receiver in activity. Broadcast data when notification received.
I have written an activity that create and start IntentService,the IntenteService send BroadCast messege to the Activity which received it successfully, now I want to send back data from the Activity to the IntentService, I tried by implementing i tried to implimente BroadCastReciver, however, it didn't work, any tips ? Thanks in advance.
public class ListenActivity extends AppCompatActivity {
/*** Attributes ***/
private Intent intentListeningService;
private Intent intentVictim;
//BroadcastReceiver
private BroadcastReceiver_addVictim broadcastReceiver_addVictim;
//IntentFilters
private IntentFilter intentFilter_addVictim;
private SwipeRefreshLayout mSwipeRefreshLayout;
// for send to Service
public static final String ACTION_Refresh = "com.bmm.bmmratvandroid.ListenActivity.Refresh";
public static final String EXTRA_KEY_r = "EXTRA_r";
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_listen);
/*****************************************************
* initialization get info from precedent activity *
***************************************************/
Intent i = getIntent();
serverPort = i.getIntExtra("port",6000);
/****************************
* start service listening *
***************************/
intentListeningService = new Intent(this, ListeningService.class);
intentListeningService.putExtra(ListeningService.EXTRA_KEY_PORT, serverPort);
Toast.makeText(getApplicationContext(), "Starting Service ..", Toast.LENGTH_LONG).show();
startService(intentListeningService);
/********************************
* Create BroadcastReceivers *
*******************************/
broadcastReceiver_addVictim = new BroadcastReceiver_addVictim();
/*******************************
* register BroadcastReceivers *
*******************************/
intentFilter_addVictim = new IntentFilter(ListeningService.ACTION_MyUpdate);
intentFilter_addVictim.addCategory(Intent.CATEGORY_DEFAULT);
registerReceiver(broadcastReceiver_addVictim, intentFilter_addVictim);
// here shoud send message to Service what didn't work
Intent intentRefresh = new Intent();
intentRefresh.setAction(ACTION_Refresh);
intentRefresh.addCategory(Intent.CATEGORY_DEFAULT);
intentRefresh.putExtra(EXTRA_KEY_r, "REFRESH");
sendBroadcast(intentRefresh);
} // fin onCreate(Bundle savedInstanceState)
/*<<<<<<<<<<<<<<<<<<<<<<<<<<<<
< BroadcastReceiver Classes <
<<<<<<<<<<<<<<<<<<<<<<<<<<<<*/
public class BroadcastReceiver_addVictim extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
String ip =null;
ip = intent.getStringExtra(ListeningService.EXTRA_KEY_addVictim);
// Here I recive message from the IntentService
// process(ip)
}
}} // fin ListenActivity
public class ListeningService extends IntentService {
/*** Attributes ***/
public static final String ACTION_MyIntentService = "com.bmm.bmmratvandroid.ListeningService.RESPONSE";
public static final String ACTION_MyUpdate = "com.bmm.bmmratvandroid.ListeningService.UPDATE";
public static final String EXTRA_KEY_PORT = "EXTRA_PORT";
public static final String EXTRA_KEY_OUT = "EXTRA_OUT";
public static final String EXTRA_KEY_addVictim = "EXTRA_addVictim";
public static final String EXTRA_KEY_deleteVictim = "EXTRA_deleteVictim";
int serverPort;
private String serviceMsg;
private ServerSocket serverSocket;
private Hashtable<String,Socket> sockets;
private int timeOut;
//BroadcastReceiver
private BroadcastReceiver_reponse broadcastReceiver_r;
//IntentFilters
private IntentFilter intentFilter_r;
/*****************
* Constructeur *
* ***************/
public ListeningService() {
super("com.bmm.bmmratvandroid.ListeningService");
sockets = new Hashtable<String,Socket>();
timeOut = 3000;
}
/************************
* Communication method *
************************/
#Override
protected void onHandleIntent(#Nullable Intent intent) {
serverPort = intent.getIntExtra(EXTRA_KEY_PORT,6000); // get port
/********************************
* Create BroadcastReceivers *
*******************************/
broadcastReceiver_r = new BroadcastReceiver_reponse();
/*******************************
* register BroadcastReceivers *
*******************************/
intentFilter_r = new IntentFilter(ListenActivity.ACTION_Refresh);
intentFilter_r.addCategory(Intent.CATEGORY_DEFAULT);
registerReceiver(broadcastReceiver_r, intentFilter_r);
}
//*-*-*-*-*-*-*-*-*-*-*-**-*-*-*//
//\\ Calling ListenActivity //\\
//*-*-*-*-*-*-*-*-*-*-*-*-*-*-*//
private void addVictim(String ip) {
Intent intentUpdate = new Intent();
intentUpdate.setAction(ACTION_MyUpdate);
intentUpdate.addCategory(Intent.CATEGORY_DEFAULT);
intentUpdate.putExtra(EXTRA_KEY_addVictim, ip);
sendBroadcast(intentUpdate);
}
//###############################
// methode manipulating sokets #
//###############################
/*<<<<<<<<<<<<<<<<<<<<<<<<<<<<
< BroadcastReceiver Classes <
<<<<<<<<<<<<<<<<<<<<<<<<<<<<*/
public class BroadcastReceiver_reponse extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// HERE I SHOUD RECIVE THE MESSAGE !?
//???????????????????????????????????
intent.getStringExtra(ListenActivity.EXTRA_KEY_r);
}
}}
I am making an inhouse navigation application with google glass. I am sending orientation data from the google glass to the android phone true WIFI (SOCKETS). My code is running fine and ok, but after about 25 seconds the receiving thread (on the phone) stops for 5 seconds and then continues, this is very annoying.
I tested this by closing the connection (when i see the thread becoming unresponsive) and it takes 5 seconds for the debugger to hit the breakpoint that i set in the application (obviously this is the thread that is causing the problem)
The weird thing is that the UI thread is still responsive i can move every object in the activity, it is just the specific thread containing the connection (Socket) that is getting blocked. I will post the code (i suspect memory leak) so that maybe someone can give me a indication why this could be happening, any advice is welcome.
CHANGED CODE AFTER COMMENT:
public class GlassOrientationSocket implements Runnable {
private final static int PORT = 6604;
private static Socket mClientSocket;
private static String mResult;
private static Handler handler = null;
private static boolean threadIsRunning;
private static BufferedReader inputReader;
public GlassOrientationSocket(Handler handler) {
this.handler = handler;
this.threadIsRunning = true;
}
public void terminateThread() {this.threadIsRunning = false;}
#SuppressWarnings("deprecation")
#Override
public void run() {
//Replace this with ip-address of android server (aka Google glass) // put ip on NFC TAG for easier configuration
String ServerIP = SECRET;
//port should be same as ServerSocketActivity
try {
mClientSocket = new Socket(serverIP, PORT);
inputReader = new BufferedReader(new InputStreamReader(mClientSocket.getInputStream()));
int angleCutter;
int orientationCutter;
float[] results = new float[2];
while(threadIsRunning)
{
if (((mResult = inputReader.readLine()) != null)) {
angleCutter = mResult.indexOf("|", 0);
orientationCutter = mResult.indexOf("|", angleCutter + 1);
results[0] = Float.valueOf(mResult.substring(0, angleCutter));
results[1] = Float.valueOf(mResult.substring(angleCutter + 1, orientationCutter));
Message msg = new Message();
msg.arg1 = 1;
msg.obj = results;
handler.sendMessage(msg);
} else {
if (mClientSocket != null) mClientSocket.close();
Message msg = new Message();
msg.arg1 = 2;
handler.sendMessage(msg);
threadIsRunning = false;
}
}
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}}
////
public class CompassMonitor {
static protected ArrayList<CompassListener> listeners=new ArrayList<CompassListener>();
static protected GlassOrientationSocket monitor=null;
private static Handler msgHandler = new Handler();
private static CompassListener orientationListener;
private static float[] dataReturned = new float[2];
static public synchronized void registerListener(Context context,CompassListener listener){
if(listeners.size()==0){
orientationListener = listener;
monitor=new GlassOrientationSocket(msgHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
switch (msg.arg1) {
case 1:
dataReturned = (float[])msg.obj;
notifyListeners(dataReturned[0],dataReturned[1],"Useless Parameter");
break;
case 2:
unregisterListener(orientationListener);
monitor.terminateThread();
}
}
});
Thread t = new Thread(monitor);
t.start();
}
listeners.add(listener);
}
static synchronized public void unregisterListener(CompassListener listener){
if (listeners != null && listener != null)
listeners.remove(listener);
}
static synchronized protected void notifyListeners(float azimuth,float angle, String direction){
for(CompassListener l:listeners){
try{
l.onCompassChanged(azimuth,angle,direction);
}catch(Exception ex){}
}
}}
I'm trying to pass an array list containing Wi-Fi informations from a class that exdends from BroadcastReceiver to another class .I can pass a normal vriable between two classes with the getter. But i'm getting an empty array, because the onReceive methode is not executed .I would like to execute the onReceive methode in another class(but i can't instantiate it ) or to get the array created in the onReceive methode in another class with a getter (but i cant get the list).Please how can i get this array in the second class.
This is the WifiData class
public class WifiData extends BroadcastReceiver{
List<String[]> wifiValues = new ArrayList<String[]>();
WifiManager wifi;
Button enab;
String resultsString ;
String[] myStringArray;
int aa = 10;
int a=10 ;
List<String[]> getWifi (){
return wifiValues ;
}
#Override
public void onReceive(Context context, Intent intent) {
if(intent.getAction().equals(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)){
List<ScanResult> results = wifi.getScanResults();
resultsString = results.toString() ;
for(int i=0;i<results.size();i++){
Log.i("Wifi SSID",results.get(i).level+"");
wifiValues.add(new String[] { results.get(i).level +"" });
}
}
}
}
This is SalesStackedBarChart class that have to get the wifi infomation and create a chart :
public class SalesStackedBarChart extends AbstractDemoChart {
public Intent execute(Context context) {
WifiData wi = new WifiData ();
// values.add(new double[] {wi.getWifi() });
Log.i("aaaa",wi.getWifi()+"");
}
}
Thank you.
You are trying to show the data in graph using AChartEngine right?
Create a new activity and put the chart in that layout. Read here how to use the AChartEngine.
Now when you are passing the data from the first class(activity) to the second class(activity), you can pass the data using the intent. Add extra to the Intent using intent.putExtras().First create a bundle. In that bundle put the data using appropriate method like putSerializableExtra() or putParcelableExtra() and in the second class(activity) call getIntent and catch that intent in a temp variable.
From that you can retrieve the data using intent.getExtras().getSerializableExtra() etc. And you can load the data into AChartEngine data to be displayed as a graph.
This is a working solution :
Starting with WifiActivity activity ,wich will determin wifi scan list ,and send it to the TruitonAChartEngineActivity class.
WifiActivity activity
public class WifiActivity extends Activity {
/** Called when the activity is first created. */
WifiManager wifi;
Button enab;
String resultsString ;
String[] myStringArray;
int aa = 10;
//tableau pris à partir de http://www.radio-electronics.com/info/wireless/wi-fi/80211-channels-number-frequencies-bandwidth.php
int [ ] [ ] Center_Frequency_2 = { { 1,2,3,4,5,6,7,8,9,10,11,12,13,14 },
{ 2412, 2417, 2422, 2427, 2432,2437,2442,2447,2452 ,2457,2462,2467,2472,2484},
};
public class Receiver extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent) {
if(intent.getAction().equals(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)){
final List<ScanResult> results = wifi.getScanResults();
resultsString = results.toString() ;
Log.i("resultsString*****************",resultsString);
final String [ ] [ ] chanelRssi = new String [results.size()][2];
String[] tabResults = new String[results.size()];
for(int i=0;i<results.size();i++){
if (results.get(i).frequency /1000 == 2) {
for (int j =0;j<14;j++)
{ if (Center_Frequency_2[1][j] == results.get(i).frequency)
tabResults[i]=results.get(i).SSID +" (" + results.get(i).BSSID + ") \n"+ results.get(i).frequency +"\n"+ results.get(i).level +"\n"+ results.get(i).capabilities +"\n"+"canal "+Center_Frequency_2[0][j] ;
chanelRssi[i][0]=Center_Frequency_2[0][j]+"";
chanelRssi[i][1]=results.get(i).level +"";
}
}
}
Button send = (Button) findViewById(R.id.barChartButton);
send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.i("click","click");
Toast.makeText(getApplicationContext(),
"Position :"+resultsString , Toast.LENGTH_LONG)
.show();
Intent intent1 = new Intent (getApplicationContext(),TruitonAChartEngineActivity.class);
Bundle bundleObject = new Bundle();
bundleObject.putSerializable("key", (Serializable) results);
intent1.putExtras(bundleObject);
startActivityForResult(intent1,0);
/* Intent intent1 = new Intent (getApplicationContext(),TruitonAChartEngineActivity.class);
startActivityForResult(intent1,0);*/
}
});
}
}
private void startActivities(Intent intent, int i) {
// TODO Auto-generated method stub
}
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_wifi);
ConnectivityManager cxMgr = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
wifi = (WifiManager)getSystemService(Context.WIFI_SERVICE);
Receiver receiver = new Receiver();
registerReceiver(receiver,new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
registerReceiver(receiver,new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
}
}
And the TruitonAChartEngineActivity class
public class TruitonAChartEngineActivity extends ActionBarActivity {
private static final int SERIES_NR = 2;
String message1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_truiton_achart_engine);
XYMultipleSeriesRenderer renderer = getTruitonBarRenderer();
myChartSettings(renderer);
Bundle v = getIntent().getExtras();
ArrayList<ScanResult> classObject = (ArrayList<ScanResult>) v.getSerializable("key");
// message1 = v.getString("message1");
/* Toast.makeText(getApplicationContext(),
"Position :" , Toast.LENGTH_LONG)
.show();*/
/* Toast.makeText(getApplicationContext(),
"Position classObject :"+classObject , Toast.LENGTH_LONG)
.show();*/
for(int index = 0; index < classObject.size(); index++){
String Object = classObject.get(index).level+"";
Toast.makeText(getApplicationContext(), "Id is :"+Object, Toast.LENGTH_SHORT).show();
}
Intent intent = ChartFactory.getBarChartIntent(this, getTruitonBarDataset(), renderer, Type.DEFAULT);
startActivity(intent);
}}
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.