Android wait for WiFi scan to finish - android

i'm trying to wait for the wifi scan to finish in the broadcast receiver!.
I have 1 Activty (ChooseActivity extends Activity) and 1 class (Scan).
In my Activity i call Scan class to scan wifi and return boolean (true) when finish, here is the code.
My purpose is to separate the scan of my activity because i call scan class in several places.
public class ChooseActivity extends Activity implements OnClickListener{
private int idMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_choose);
idMap = this.getIntent().getExtras().getInt("ID_MAP");
((Button)this.findViewById(R.id.scan_button)).setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch(v.getId()){
case R.id.scan_button:
Scan scan = new Scan();
Toast.makeText(getApplicationContext(), " "+scan.scanHotspots(idMap), Toast.LENGTH_SHORT).show();
break;
}
}
}
And here is my Scan class
public boolean scanHotspots(int idMap){
wifiManager = (WifiManager)context.getSystemService(Context.WIFI_SERVICE);
wifiManager.startScan();
receiver = new Receiver();
IntentFilter intentFilter = new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
context.registerReceiver(receiver, intentFilter);
//HERE I WANT STOP EXECUTION TO WAIT test VAIRABLE CHANGE STATUS
return test;
}
public class Receiver extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
if(intent.getAction().equals(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION))
{
test=true;
}
}
}
}
Thank you in advance.

Related

How to know when the services has ended

I want know when the service has ended, so I use BroadcastReceiver.
My service name is CheckNuevosAvisosIntentServices and I launch it in main.java (onCreate method) as:
Intent msgIntent = new Intent(Main.this, CheckNuevosAvisosIntentService.class);
msgIntent.putExtra("iteraciones", 1);
startService(msgIntent);
My manifest inside application tag.
<!-- Services -->
<service android:name="com.kirolm.instalacionesdep.services.CheckNuevosAvisosIntentService" />
In another fragment (HomeFragment) I use isMyServiceRunning method and BroadcastReceiver class:
private boolean isMyServiceRunning() {
ActivityManager manager = (ActivityManager) getActivity().getSystemService(Context.ACTIVITY_SERVICE);
for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (CheckNuevosAvisosIntentService.class.getName().equals(service.service.getClassName())) {
return true;
}
}
return false;
}
My Broadcast code is this:
public class ProgressReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if(intent.getAction().equals(CheckNuevosAvisosIntentService.ACTION_PROGRESO)) {
Log.e("Testing", "The service is running...");
}
else if(intent.getAction().equals(CheckNuevosAvisosIntentService.ACTION_FIN) && isAdded()) {
Log.e("Testing", "The service has been ended");
}
}
}
and in creathe method (HomeFragment) I implements this:
if(!isMyServiceRunning()){
Log.e("Testing", "HomeFragment: The service is running");
}else{
Log.e("Testing", "HomeFragment: The servie stop");
}
CheckNuevosAvisosIntentServicescode:
public class CheckNuevosAvisosIntentService extends IntentService{
public static final String ACTION_PROGRESO = "com.kirolm.instalacionesdep.services.action.PROGRESO";
public static final String ACTION_FIN = "com.kirolm.instalacionesdep.services.action.FIN";
public CheckNuevosAvisosIntentService() {
super("CheckNuevosAvisosIntentService");
// TODO Auto-generated constructor stub
}
#Override
protected void onHandleIntent(Intent intent) {
// TODO Auto-generated method stub
int iter = intent.getIntExtra("iteraciones", 0);
for(int i=1; i<=iter; i++) {
Intent bcIntent = new Intent();
bcIntent.setAction(ACTION_PROGRESO);
bcIntent.putExtra("progreso", i*10);
sendBroadcast(bcIntent);
}
buscaNuevasNoticasRss();
Intent bcIntent = new Intent();
bcIntent.setAction(ACTION_FIN);
sendBroadcast(bcIntent);
}
private void buscaNuevasNoticasRss() {
// TODO Auto-generated method stub
//This method checks. When this method finish I want finish my services.
}
}
When buscaNuevasNoticiasRssfinish, I want finish my services.
I receive when the service is running but I don't receive when the service stop.
Edited: HomeFragment (onCreat method)
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
ProgressReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
Log.e("Testing", "HomeFragment. BoradcastReceiver. Dentro de onReceive");
if(intent.getAction().equals(CheckNuevosAvisosIntentService.ACTION_PROGRESO)) {
Log.e("Testing", "HomeFragment. BoradcastReceiver. The service is running...");
}
else if(intent.getAction().equals(CheckNuevosAvisosIntentService.ACTION_FIN) && isAdded()) {
Log.e("Testing", "HomeFragment. BoradcastReceiver. The service has been ended");
}
}
};
}
Override the onDestroy() method of your IntentService and send a broadcast to your receiver saying the service is destryed.
public class CheckNuevosAvisosIntentService extends IntentService{
//Your code
.......
.......
#Override
public void onDestroy() {
super.onDestroy();
sendBroadcast(new Intent(CheckNuevosAvisosIntentService.ACTION_FIN));
}
}
And create a BroadcastReceiver as an inner class of HomeFragment.
private class HomeFramgnet extends Fragment {
private ProgressReceiver progressReceiver;
Override
public void onCreate(Bundle savedInstanceState) {
progressReceiver = new ProgressReceiver();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(CheckNuevosAvisosIntentService.ACTION_PROGRESO);
intentFilter.addAction(CheckNuevosAvisosIntentService.ACTION_FIN);
registerReceiver(progressReceiver, intentFilter);
}
#Override
public void onDestroy() {
super.onDestroy();
unregisterReceiver(progressReceiver);;
}
class ProgressReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
Log.e("Testing", "HomeFragment. BoradcastReceiver. Dentro de onReceive");
if (intent.getAction().equals(CheckNuevosAvisosIntentService.ACTION_PROGRESO)) {
Log.e("Testing", "HomeFragment. BoradcastReceiver. The service is running...");
} else if (intent.getAction().equals(CheckNuevosAvisosIntentService.ACTION_FIN) && isAdded()) {
Log.e("Testing", "HomeFragment. BoradcastReceiver. The service has been ended");
}
}
}
}

Android update UI of different activity after async task

Where I start an async task in activity A, and immediately start activity B. On completion of background task in activity A, I want to update UI of activity B. Here is the prototype of the code:
public class ActivityA extends Activity{
public void onCreate() {
// Starting asynctask here
BackgroundAsyncTask mBackgroundObject=new BacgroundAsyncTask(getActivity.getApplicationContext());
mBackgroundObject.execute();
// Start Activity B
}
public class BackGroundAsyncTask extends AsyncTask< ... > {
Context context;
public BackGroundAsyncTask(Context mCOntext){
context = mContext;
}
doInBackground(){
// Background Task
}
onPostExecute(){
ActivityB.UpdateUI(context);
}
}
}
public class ActivityB extends Activity {
public void onCreate(){}
public static void UpdateUI(Context mContext) {
// **Here I want to update the UI of Activity B , but it is not happening, looks like it is because context is of activity A**
}
}
Any help in implementation of call back listeners or any other implementation would be of really great help. The issue I'm facing is that I don't get any exception but the UI of activity B doesn't get updated.
create callback from async task
after get result from async task send updated data from activity A to Activity B vai broadcast intent
Register local BroadcastReceiver in Activity B
in onReceive() method of broadcast listener you can get all upadated data vai intent the update your UI
or
Directly send broadcast from onPostExecute() method
I put a small demo here, it's same as the above.
public class TestA extends Activity{
private final String ACTION_NAME = "bc";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
new Thread(){
#Override
public void run() {
// TODO Auto-generated method stub
super.run();
try {
sleep(5000);
Intent mIntent = new Intent(ACTION_NAME);
mIntent.putExtra("yaner", "发送广播,相当于在这里传送数据");
//发送广播
sendBroadcast(mIntent);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}.start();
startActivity(new Intent(this, TestB.class));
}
}
public class TestB extends Activity{
private final String ACTION_NAME = "bc";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
//注册广播
registerBoradcastReceiver();
}
private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver(){
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if(action.equals(ACTION_NAME)){
Log.d("aaa", "TestB onReceive:"+intent.getStringExtra("yaner"));
}
}
};
public void registerBoradcastReceiver(){
IntentFilter myIntentFilter = new IntentFilter();
myIntentFilter.addAction(ACTION_NAME);
//注册广播
registerReceiver(mBroadcastReceiver, myIntentFilter);
}
}

Broadcast Receiver "on recieve" method not been called?

I Have three activities
On activity A i register the broadcast receiver ,then i go to activity B from there i go to activity C.
and finally onBackPressed of activity c ,i send the broadcast
but onReceive is not called
My first Activity
private MyBroadCastReceiver myRecevier = new MyBroadCastReceiver();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Submit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent frag=new Intent(MainActivity.this,Activity2.class);
//frag.putExtra("Limit", foo);
startActivity(frag);
// }
}
});
}
#Override
protected void onResume() {
super.onResume();
//Register the activity to the broadcast receiver
registerReceiver(myRecevier, new IntentFilter(MyBroadCastReceiver.ACTION));
}
#Override
protected void onPause() {
super.onPause();
//Unregister the activity from the broadcast receiver. Good practice ;)
unregisterReceiver(myRecevier);
}
public class MyBroadCastReceiver extends BroadcastReceiver{
public static final String ACTION = "com.uberrueco.mybroadcastreceiver.receivers";
#Override
public void onReceive(Context context, Intent intent) {
Log.d("MyBroadCastReceiver", "received");
Toast.makeText(context,"Received "+intent.getStringExtra("editText"), Toast.LENGTH_LONG).show();
}
}
}
Second activity has nothing but an intent to activity 3
Third Activity
public class Activity3 extends Activity {
EditText etReceivedBroadcast;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity3);
etReceivedBroadcast = (EditText) findViewById(R.id.etReceivedBroadcast);
}
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
super.onBackPressed();
Intent intent = new Intent(this, MyIntentService.class);
intent.putExtra("editText", etReceivedBroadcast.getText().toString());
startService(intent);
}
}
and finally my IntentService class
public class MyIntentService extends IntentService{
public MyIntentService(){
super("MyIntentService");
}
public MyIntentService(String name) {
super(name);
}
#Override
protected void onHandleIntent(Intent intent) {
Log.d("MyIntentService", "handling intent...");
//Intent created for broadcasting
Intent intentBroadCast = new Intent();
//Filter the broadcast to the action desired
intentBroadCast.setAction(MyBroadCastReceiver.ACTION);
intentBroadCast.putExtra("editText", intent.getStringExtra("editText"));
//Send the broadcast :D
sendBroadcast(intentBroadCast);
}
}
You are calling unregisterReceiver in onPause of MainActivity . So you are not recieving the broadcast.
Move register to onCreate and unregister to onDestroy of your MainActivity.
if your onHandleIntent() was called then you should try like.
Intent intentBroadCast = new Intent(MyBroadCastReceiver.ACTION);
intentBroadCast.putExtra("editText", intent.getStringExtra("editText"));
//Send the broadcast :D
sendBroadcast(intentBroadCast);
make changes like below code
private MyBroadCastReceiver myRecevier = new MyBroadCastReceiver();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Register the activity to the broadcast receiver
this.registerReceiver(myRecevier, new IntentFilter(MyBroadCastReceiver.ACTION));
Submit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent frag=new Intent(MainActivity.this,Activity2.class);
//frag.putExtra("Limit", foo);
startActivity(frag);
// }
}
});
}
#Override
protected void onResume() {
super.onResume();
}
#Override
protected void onDestroy() {
super.onDestroy();
//Unregister the activity from the broadcast receiver. Good practice ;)
this.unregisterReceiver(myRecevier);
}
#Override
protected void onPause() {
super.onPause();
//Unregister the activity from the broadcast receiver. Good practice ;)
unregisterReceiver(myRecevier);
}
public class MyBroadCastReceiver extends BroadcastReceiver{
public static final String ACTION = "com.uberrueco.mybroadcastreceiver.receivers";
#Override
public void onReceive(Context context, Intent intent) {
Log.d("MyBroadCastReceiver", "received");
Toast.makeText(context,"Received "+intent.getStringExtra("editText"), Toast.LENGTH_LONG).show();
}
}
}
u need to use like this this.unregisterReceiver() and this.registerReceiver()

No response after broadcast receiver from service

I am trying to send a string from service using broadcast receiver.
On reaching a location I want to send broadcast receiver but broadcast receiver is not able to send anything and nor I am getting any error in Logcat.Also I am not able to receive any error in both activity or service.
Following is my code in service class:-
public class MyLocationListener implements LocationListener{
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
inte.setAction("hello");
inte.putExtra("StringFromService", genre);
inte.addCategory(Intent.CATEGORY_DEFAULT);
sendBroadcast(inte);
}
Receiver inside another class:-
public class XYZ extends ListActivity {
public BroadcastReceiver myBR= new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
String x= intent.getAction();
Log.d("INside BroadcastReceiver", "inside" + x);
if(x.equals("hello")){
Toast.makeText(XYZ.this,"hello", Toast.LENGTH_LONG).show();
}
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.xyz);
registerReceiver(myBR, new IntentFilter("hello"));
}
}
To trigger a broadcast, you have to register the receiver in the onResume() method like this:
registerReceiver(myBR, new IntentFilter("hello"));
and unregister the broadcast in the onPause() method
unregisterReceiver(myBR);

android Activity and a service with sms contentobserver

My app requirements
The application will have an activity and a service.
The service has a sms contentobserver.
After application installation the Service should run all the time irrespective of
application active or not
The registration and unregistration of contentobserver inside the service should
be controlled from the activity.
On uninstallation of the application the service should be destroyed.
I tried some code. In oncreate of the service i have done resgitartion of content observer
and ondestroy i unregistered it. I have used start and stop service from the activity.
But even after stop service the onchange method of the content observer is still getting called.
please let me know some sample code and the manifest definition of this service.
public class MyActivity extends ListActivity implements OnInitListener {
#Override
protected void onDestroy() {
super.onDestroy(); // let it be here as per the android TTS samples
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Intent sintent = new Intent(MyActivity.this,MyService.class);
MyActivity.this.startService(sintent);
}
private boolean SSMyservice() {
// TODO Auto-generated method stub
//stop service
Intent sintent = new Intent(MyActivity.this,MyService.class);
MyActivity.this.stopService(sintent);
//do some work
//start service again
MyActivity.this.startService(sintent); //start service again
return true;
} //importdata
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.TTSread:
return true;
case R.id.SSS:
SSMyservice();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Log.v(TAG,"option menu created");
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.layout.omenu, menu);
return true;
}
}
------------end MyActivity---------------------
----------------------------------
public class MyService extends Service {
protected SmsObserver smsSentObserver=null;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate()
{
registersmsevent();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
super.onStartCommand(intent, flags, startId);
return Service.START_STICKY;
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
unregistersmsevent();
}
public void registersmsevent() {
// TODO Auto-generated method stub
if(smsSentObserver == null)
{
final Uri SMS_STATUS_URI = Uri.parse("content://sms");
smsSentObserver = new SmsObserver(new Handler());
MyService.this.getContentResolver().registerContentObserver(SMS_STATUS_URI, true, smsSentObserver);
}
}
public void unregistersmsevent() {
if(smsSentObserver != null)
{
MyService.this.getContentResolver().unregisterContentObserver(smsSentObserver);
smsSentObserver = null;
}
}
public class SmsObserver extends ContentObserver {
Handler handler;
public SmsObserver(Handler handler) {
super(handler);
// TODO Auto-generated constructor stub
this.handler = handler;
}
#Override
public boolean deliverSelfNotifications() {
return true;
}
#Override
public void onChange(boolean selfChange) {
//my code........
super.onChange(selfChange);
}
}//End of class SmsObserver
}//end of service
I could fix the issue. This was a timing issue. Stopping service takes sometime.

Categories

Resources