Broadcast Receiver not receiving - java

I know this question comes here fairly often, but I've looked through probably 20 stack overflow questions already and haven't been able to find a solution. I'm fairly certain it's something simple I'm doing wrong but I'm pretty new to Android and this assignment is due in 7 hours or so.
Everything works up until the receiver being called. Here's the call, from a service
Intent intent = new Intent(getApplicationContext(), MainActivity.WatchReceiver.class);
intent.putStringArrayListExtra(CHANGEKEY, changedURLs);
LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(intent);
Now here's the receiver, nested inside the main activity
public class WatchReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Log.d(null, "broadcast received");
markAsChanged(intent.getStringArrayListExtra(WatchService.CHANGEKEY));
}
}
And the main activity's on start function, where I register the receiver
#Override
protected void onStart() {
super.onStart();
// Bind to LocalService
wr = new WatchReceiver();
markedAsChanged = new ArrayList<Integer>();
LocalBroadcastManager.getInstance(getApplicationContext()).registerReceiver(wr, new IntentFilter());
Intent intent = new Intent(this, WatchService.class);
sc = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
wb = (WatchService.WatchBinder) service;
}
#Override
public void onServiceDisconnected(ComponentName name) {
wb = null;
}
};
bindService(intent, sc, Context.BIND_AUTO_CREATE);
}

Explicit Intents do not work with registerReceiver(), whether you are calling registerReceiver() on a Context (for system-level broadcasts) or on an instance of LocalBroadcastManager (for local broadcasts).
Instead:
Define an action string (e.g., final String ACTION="com.dellosa.nick.ITS_HUMP_DAY";)
Use that action string when creating the Intent to broadcast (new Intent(ACTION))
Use that action string when creating the IntentFilter (new IntentFilter(ACTION))

Related

From where value of intent is coming on which I am calling getAction() function? (This is overridden method of BroadcastReceiver class)

I have created a broadcast receiver class Which is working fine. I am confused about from where the value of intent comes in onReceive method.
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if(wifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION.equals(action))
{
int state=intent.getIntExtra(WifiP2pManager.EXTRA_WIFI_STATE,-1);
if(state==WifiP2pManager.WIFI_P2P_STATE_ENABLED){
Toast.makeText(context,"Wifi is ON",Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(context,"Wifi is OFF",Toast.LENGTH_SHORT).show();
}
}
}
Main Activity code where I have made an Intent Filter, where I have added an action.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_find_device);
wifiP2pManager = (WifiP2pManager)
getSystemService(Context.WIFI_P2P_SERVICE);
channel = wifiP2pManager.initialize(this,getMainLooper(),null);
broadcastReceiver = new WiFiDirectBroadcastReceiver(wifiP2pManager, channel, this);
intentFilter = new IntentFilter();
intentFilter.addAction(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION);
}
If your BroadcastReceiver works, then you must have initialized wifiP2pManager and called a function on the object. When tbe state changes an intent is being broadcasted. With the receiver you subscribe to those intents.
You can read in more detail about the WifiP2pManager in the Android documentation Wi-Fi Direct (peer-to-peer or P2P) overview

How to destroy/kill a service?

I have my application running a service for shake detect, however in my MainActivity, I have button for log out user, in which I must log out and terminate the service that detects the shake event.
my method for log out in my MainActivity is:
public void signOutAndFinish(){
//Stop Shakeservice
Intent intent = new Intent(this, ShakeService.class);
stopService(intent);
//Go to login activity
Intent iLoginView = new Intent(this, LoginActivity.class);
startActivity(iLoginView);
}
however if I shake my device after logging out, the service recognizes the shake, it is as if it will not kill it immediately:
Intent intent = new Intent(this, ShakeService.class);
stopService(intent);
The code in the method onDestroy is:
#Override
public void onDestroy() {
super.onDestroy();
}
How can I terminate the service so that when I log out the service dies?
Thanks for your help!
You can send a broadcast back your activity in the onDestroy() method of your service and then do the logout.
Here is some sample code of the above idea:
This for your service:
#Override
public void onDestroy() {
super.onDestroy();
Intent intent = new Intent();
intent.setAction("com.example.broadcast.MY_NOTIFICATION");
intent.putExtra("data","Notice for logout!");
sendBroadcast(intent);
}
And this is for your activity:
private BroadcastReceiver br = new MyBroadcastReceiver();
#Override
public void onCreate() {
IntentFilter filter = new IntentFilter("com.example.broadcast.MY_NOTIFICATION");
registerReceiver(br, filter);
}
#Override
public void onDestroy() {
unregisterReceiver(br);
}
// An inner class at your activity
public class MyBroadcastReceiver extends BroadcastReceiver {
private static final String TAG = "MyBroadcastReceiver";
#Override
public void onReceive(Context context, Intent intent) {
YourActivity.this.finish();
// or do anything you require to finish the logout...
}
}
however if I shake my device after logging out, the service recognizes the shake
Then presumably you did not clean up your Sensor stuff in the service's onDestroy() method.
How can I terminate the service so that when I log out the service dies?
You are doing that now. However, if you set up something in the service, such as listening to events from SensorManager, you need to clean that up, typically in onDestroy() of the service.

How to pass parameters to Broadcast receiver class?

I have created a Broadcast receiver and it is working fine. but I need to pass a handler to that class.
public static class DataReceiver extends BroadcastReceiver {
Handler handler;
DataReceiver(Handler loghandler) {
this.handler = loghandler;
}
#Override
public void onReceive(Context context, Intent intent) {
//things goes here
}
}
Currently I am using like this & It is working if constructor override is not available.
Intent intent = new Intent(this, DataReceiver .class);
but I need to pass the handler too. How can I send the handler? Thanks
I don't really understand what you are trying to accomplish but i think this may help you. You don't need to make a whole new class for your broadcast receiver but you can use it inside your Main Activity like this:
BroadcastReceiver receiveLocationReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// Your custom action
}
};
IntentFilter receiveLocationFilter = new IntentFilter();
receiveLocationFilter.addAction("android.intent.RECEIVE_LOCATION");
Register the receiver in "onStart":
registerReceiver(receiveLocationReceiver, receiveLocationFilter);
Unregister it in "onStop":
unregisterReceiver(receiveLocationReceiver);
Then when you need to send the broadcast all you need is :
Intent sendBroadcastIntent = new Intent("android.intent.RECEIVE_LOCATION");
sendBroadcast(sendBroadcastIntent);

Service containing BroadCastReceiver not functioning correctly

Please see edits before answering!
I have an app which contains a BackgroundService class:
public class BackgroundService extends Service {
#Override
public void onCreate() {
super.onCreate();
IntentFilter filter = new IntentFilter();
filter.addAction("com.spotify.music.playbackstatechanged");
filter.addAction("com.spotify.music.metadatachanged");
filter.addAction("com.spotify.music.queuechanged");
registerReceiver(receiver, filter);
Log.e("Playing:", "APP IS PLAYING");
Notification notification = new Notification();
startForeground(1, notification);
}
private final BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
long timeSentInMs = intent.getLongExtra("timeSent", 0L);
String action = intent.getAction();
if (action.equals(BroadcastTypes.METADATA_CHANGED)) {
String trackId = intent.getStringExtra("id");
String artistName = intent.getStringExtra("artist");
String albumName = intent.getStringExtra("album");
String trackName = intent.getStringExtra("track");
int trackLengthInSec = intent.getIntExtra("length", 0);
// Do something with extracted information...
} else if (action.equals(BroadcastTypes.PLAYBACK_STATE_CHANGED)) {
boolean playing = intent.getBooleanExtra("playing", false);
Log.e("Playing:","TRUE");
}
}
};
#Override
public void onDestroy() {
super.onDestroy();
unregisterReceiver(receiver);
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
static final class BroadcastTypes {
static final String SPOTIFY_PACKAGE = "com.spotify.music";
static final String PLAYBACK_STATE_CHANGED = SPOTIFY_PACKAGE + ".playbackstatechanged";
static final String METADATA_CHANGED = SPOTIFY_PACKAGE + ".metadatachanged";
}
}
and this is declared in my manifest:
<service
android:name=".BackgroundService"
android:enabled="true" >
<intent-filter>
<action android:name="com.spotify.music.playbackstatechanged" />
<action android:name="com.spotify.music.metadatachanged" />
<action android:name="com.spotify.music.queuechanged" />
</intent-filter>
</service>
So essentially my objective is to have my BackgroundService initialized when my app is opened, and to have it continue to run in the Background doing whatever I need it to do. As of now, I am using logs to determine whether my "setup" is working, but when I run my app, I am unable to see an logs even after I tested all actions that should have triggered my BroadCastReceiver. Furthermore, my persistent notification should have changed had my service been running, but it does not...
Edit::
So, I added logs to my BackgroundService's onCreate() and onReceive() methods, however, neither seem to be appearing. Im wondering, do I need to do something in my launcher activity to initialize the service? Furthermore, no notification is shown so I assume the Service is not being started for some reason...
Latest Edit:
So I added the following code to my Main activity to see if it would make a difference:
startService(new Intent(this,BackgroundService.class));
And after debugging my app, I began to see the following error:
java.lang.RuntimeException: Unable to create service com.aurum.mutify.BackgroundService: java.lang.SecurityException: Isolated process not allowed to call registerReceiver
pointing to my BroadCast Receiver class.
Intent services are designed for short tasks. And your intent handling method is empty.
If you need long running task in the background use standard service and call start foreground. This will minimize chance of system destroying your service.
To learn more go here
EDIT
Try overriding onStartCommand method. this method is called when service is started and usually you do all stuff here. Remember that there are 3 options to return.
Edit 2:
try something like this
in on create
PendingIntent pi;
BroadcastReceiver br;
Intent myIntent;
#Override
public void onCreate()
{
super.onCreate();
myIntent = new Intent("something")
if(Build.Version.SDK_INT >= 16) //The flag we used here was only added at API 16
myIntent.setFlags(Intent.FLAG_RECEIVER_FOREGROUND);
//use myIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); if you want to add more than one flag to this intent;
pi = PendingIntent.getBroadcast(context, 1, myIntent, 0);
br = new BroadcastReceiver ()
{
public void onReceive (Context context, Intent i) {
new thread(new Runnable()
{
public void run()
{
//do something
}
}).start();
}
};
And then in on start command
this.registerReceiver(br, new IntentFilter("something"));

Android receive a broadcast in ActionBarActivity

I have got an action bar activity with a LocalBroadcastManager defined exactly like in the answer here, except the only difference is that it is defined in an ActionBarActivity.
For some reason, no matter what I try I can't manage to get to the receiver's onReceive (i.e. successfuly receiving broadcast message).
Service code:
public class GcmIntentService extends IntentService {
#Override
protected void onHandleIntent(Intent intent) {
Intent toDrawerActivity = new Intent(syncActionName);
String syncType = extras.getString("data");
toDrawerActivity.putExtra("syncType", syncType);
System.out.println("sending intent in service");
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}
}
And the activity code:
public class DrawerActivity extends ActionBarActivity {
private BroadcastReceiver dataUpdaterReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
System.out.println("in broadcast receiver");
}
};
protected void onCreate(){
...
...
LocalBroadcastManager.getInstance(this).registerReceiver(dataUpdaterReceiver,
new IntentFilter(GcmIntentService.syncActionName));
}
protected void onDestroy(){
LocalBroadcastManager.getInstance(this).unregisterReceiver(dataUpdaterReceiver);
}
}
What exactly am I doing wrong here?
Your have that problem due to you used the wrong parameter for sendBroadcast() method:
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
It should be:
LocalBroadcastManager.getInstance(this).sendBroadcast(toDrawerActivity);

Categories

Resources