I have built BroadcastReceiver in my MainActivity to catch system broadcast(internet connection and wifi scan result). The internet connection broadcast is being caught but I am facing problem to catch the broadcast of the wifi scan result. no error is being thrown. I do not know what shall I add additional to get it work. I appreciate any help.
MainActivity:
public class MainActivity extends ActionBarActivity {
BroadcastReceiverListener receiver;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
receiver = new BroadcastReceiverListener();
}
private class BroadcastReceiverListener extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
//This if statement is being arrived
if (intent.getAction().equals(
android.net.wifi.WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)) {
//This code works without BroadcastReceiver.
}
else if (intent.getAction().equals(
android.net.ConnectivityManager.CONNECTIVITY_ACTION)) {
// I am getting here broadcast for the internet connection
}
}
};
protected void onResume() {
IntentFilter wifi = new IntentFilter();
wifi.addAction(android.net.wifi.WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
registerReceiver(receiver, wifi);
IntentFilter conn = new IntentFilter();
conn.addAction(android.net.ConnectivityManager.CONNECTIVITY_ACTION);
registerReceiver(receiver, conn);
super.onResume();
}
#Override
protected void onDestroy() {
unregisterReceiver(receiver);
super.onDestroy();
}
}
There's no need to create two IntentFilters, just create the one and use addAction() to add multiple actions:
IntentFilter wifi = new IntentFilter();
wifi.addAction(android.net.wifi.WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
wifi.addAction(android.net.ConnectivityManager.CONNECTIVITY_ACTION);
registerReceiver(receiver, wifi);
See here:
Android - Registering a broadcast receiver for two intents?
Related
I have a variable in FetchAddressIntentService class name addressText which holding zip code using reverse geocode. what i want is to send the addressText data to my MainActivity.
You have to register your main activity to the broadcast and then send the broadcast from the service.
In your main activity:
private BroadcastReceiver receiver;
#Override
public void onCreate(Bundle savedInstanceState){
IntentFilter filter = new IntentFilter();
filter.addAction("BROADCAST_ZIP_CODE");
receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
//get data from the intent and display it
String zipCode = intent.getStringExtra("ZIP_CODE");
//do something with the zipCode
}
};
registerReceiver(receiver, filter);
}
#Override
protected void onDestroy() {
if (receiver != null) {
unregisterReceiver(receiver);
receiver = null;
}
super.onDestroy();
}
In your service:
public class ZipCodeService extends Service {
#Override
public void onCreate() {
String zipCode = "your_zip_code";
Intent intent = new Intent();
intent.setAction("BROADCAST_ZIP_CODE");
intent.putExtra("ZIP_CODE",zipCode);
sendBroadcast(intent);
}
}
You can achieve this in two ways.
Using a Bound Service and registering your Activity as a listener object with your Service by having your Activity implement a listener interface. Docs here.
Sending a Local Broadcast from the Service to your Activity. (See JackD's answer)
Depending on how you've architected your application you may prefer one solution more than the other. The Android docs will help which is best.
I have created the one receiver inside an Activity for when internet is connected auto calling web service.
Code like
//Create receiver for while network will come auto call webservice
private BroadcastReceiver mConnReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
boolean noConnectivity = intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);
if (!noConnectivity) {
bar.setVisibility(View.VISIBLE);
callAuthorizeWebservice();
} else {
bar.setVisibility(View.INVISIBLE);
Toast.makeText(SplashScreenActivity.this, "Check Your Internet connection", Toast.LENGTH_LONG).show();
}
}
};
#Override
protected void onStop() {
super.onStop();
unregisterReceiver(mConnReceiver);
}
#Override
protected void onStart() {
super.onStart();
this.registerReceiver(this.mConnReceiver,
new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
}
When I open that Activity the onReceive() is method called everytime.
How to avoid calling it the first time (when opening that Activity)?
The broadcast is sent when you register for the first time(cf sticky broadcast), a solution is to use isInitialStickyBroadcast in the onReceive callback of your BroadcastReceiver to know if you are actually proceeding a sticky broadcast and act accordingly (BroadcastReceiver : isInitialStickyBroadcast)
I need to send broadcast intent for specific receiver.
I use this function for it:
void sendTestBroadcast(Class<? extends BroadcastReceiver> clazz) {
Intent intent = new Intent(context, clazz);
intent.setAction(MY_ACTION);
context.sendBroadcast(intent);
}
Then I handle results in my Activity:
#Override
protected void onStart() {
super.onStart();
mReceiver = new Receiver();
registerReceiver(mReceiver, new IntentFilter(MY_ACTION));
}
#Override
protected void onStop() {
super.onStop();
unregisterReceiver(mReceiver);
mReceiver = null;
}
Receiver is private and non-static class. I pass Receiver.class to my receiver sender as an argument. I also tried to use ComponentName to set destanation target, but it's still not working. I even tried to do Receiver class static -- same result.
What am I doing wrong?
I am trying to update the UI (Activity) after some action has been performed in the service. This is very simple example but it doesn't seem to work for me. What am I missing here?
ExampleService:
public class ExampleService extends IntentService{
#Override
protected void onHandleIntent(Intent intent) {
notifyActivity();
}
private void notifyActivity() {
Intent broadcast = new Intent(this, ExampleActivity.class);
sendBroadcast(broadcast);
}
}
ExampleActivity:
public class ExampleActivity extends ListActivity {
private BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(getApplicationContext(), "received", Toast.LENGTH_SHORT).show();
}
};
#Override
protected void onPause() {
super.onPause();
unregisterReceiver(receiver);
}
#Override
public void onResume() {
super.onResume();
IntentFilter filter = new IntentFilter();
registerReceiver(receiver, filter);
}
}
You cannot send a broadcast to an anonymous dynamic receiver that way. You will need to define an action string in the Intent and use that action string in the IntentFilter.
You might consider using LocalBroadcastManager for this scenario, for better performance. Here is a sample project demonstrating this.
I want to dynamically register and unregister my receiver class with the broadcast:
"android.net.wifi.STATE_CHANGE"
This works very well if I do this in the manifest. But this makes it static. I want to do it dynamically in the activity class. What is its correspondent command in the activity class?
This is what my code is...
and I am getting a problem because of registering and unregistering(multiple times) my receiver(which is starting a service).
public class startScreen extends Activity {
/** Called when the activity is first created. */
private BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Intent serviceIntent = new Intent();
serviceIntent.setAction("com.example.MyService");
context.startService(serviceIntent);
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.initial);
final IntentFilter filter = new IntentFilter();
filter.addAction("android.net.wifi.STATE_CHANGE");
Button button = (Button) findViewById(R.id.button1);
final ToggleButton toggleButton = (ToggleButton) findViewById(R.id.toggleButton1);
try {
...some code...
if (bool == true) {
toggleButton.setChecked(true);
this.registerReceiver(receiver, filter);
} else
toggleButton.setChecked(false);
} catch (Exception e) {
Log.e("Error", "Database", e);
} finally {
...
}
toggleButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if ((toggleButton.isChecked())) {
getBaseContext().registerReceiver(receiver, filter);
} else {
if (receiver != null) {
getBaseContext().unregisterReceiver(receiver);
receiver = null;
}
}
}
});
}
#Override
protected void onResume() {
super.onResume();
if (bool == true) {
if (receiver == null)
this.registerReceiver(receiver, filter);
}
}
#Override
protected void onPause() {
super.onPause();
if (receiver != null) {
this.unregisterReceiver(receiver);
receiver = null;
}
}
}
The LocalBroadcastManager class is used to register for and send broadcasts of Intents to local objects within your process. This is faster and more secure as your events don't leave your application.
The following example shows an activity which registers for a customer event called my-event.
#Override
public void onResume() {
super.onResume();
// Register mMessageReceiver to receive messages.
LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver,
new IntentFilter("my-event"));
}
// handler for received Intents for the "my-event" event
private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// Extract data included in the Intent
String message = intent.getStringExtra("message");
Log.d("receiver", "Got message: " + message);
}
};
#Override
protected void onPause() {
// Unregister since the activity is not visible
LocalBroadcastManager.getInstance(this).unregisterReceiver(mMessageReceiver);
super.onPause();
}
// This method is assigned to button in the layout
// via the onClick property
public void onClick(View view) {
sendMessage();
}
// Send an Intent with an action named "my-event".
private void sendMessage() {
Intent intent = new Intent("my-event");
// add data
intent.putExtra("message", "data");
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}
use the below methods to register/unregister your receiver:
registerReceiver(BroadcastReceiver receiver, new IntentFilter("android.net.wifi.STATE_CHANGE"));
unregisterReceiver(BroadcastReceiver receiver);
For reference have a look at this
Don't add dynamic broadcast receiver in onReceive on broadcast file. Add it on first activity or main activity of your application. If you needed it only when your application is open. But if you need it always received response just added it on manifest file
Register dynamic broadcast receiver on main activity
MyReceiver reciver;
#Override
protected void onResume() {
super.onResume();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("android.net.wifi.WIFI_STATE_CHANGED");
intentFilter.addAction("android.net.wifi.STATE_CHANGE");
reciver = new MyReceiver();
registerReceiver(reciver, intentFilter);
}
Unregister that broadcast receiver on activity stop or closed
#Override
protected void onStop() {
super.onStop();
unregisterReceiver(reciver);
}
Perhaps I'm a bit too late, but the problem lies on the fact that you are setting the receiver = null in your onPause method, and then never setting it again. You are also trying to register it in your onResume method but only if it is null, which makes no sense too.
You should change the logic where you set/test the null value of the receiver, to instead just use a boolean variable to keep track of the receiver status (if it's registered or not).
public void registerBroadcastReceiver(View view) {
this.registerReceiver(broadCastReceiver, new IntentFilter(
"android.intent.action.TIME_TICK"));
}
public void unregisterBroadcastReceiver(View view) {
this.unregisterReceiver(broadCastReceiver);
}