Android receive a broadcast in ActionBarActivity - java

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);

Related

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);

How to unregisterReceiver from an activity

I start a service from activity button click that fire a service class and start Broadcastreceiver and it's run in background but I want to unregisterReceiver with a button click from same activity class.it seem not working.I added receiver class to menifest.
Here is my code.
Activity button click for registerreceiver
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent svc = new Intent(this, DemoService.class);
startService(svc);
});
DemoService.class
public class DemoService extends Service {
static final String LOGGING_TAG = "MyDemo";
private static Alarm1 tickReceiver =new Alarm1();
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onStart(Intent intent, int startId){
super.onStart(intent, startId);
Log.v(LOGGING_TAG, "DemoService.onStart()");
}
#Override
public void onCreate(){
super.onCreate();
Log.d(LOGGING_TAG, "DemoService.onCreate()");
registerReceiver(
new Alarm1(),
new IntentFilter(Intent.ACTION_TIME_TICK));
}
}
Activity button click for unregisterReceiver
unreg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DemoService demo=new DemoService();
demo.unreg();
});
And receiver class
public class Alarm1 extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Log.d("tag","working");
}
How can I unregisterReceiver from unreg button click.
If I click in unreg button it show me error java.lang.IllegalArgumentException: Receiver not registered:
create a method for unregistering Receiver in Service class. And call the service with action like.
Intent svc = new Intent(this, DemoService.class);
svc.setAction("com.package.UN_REGISTER");
startService(svc);
and in Service class handle them in onStartCommand ()
like
if(intent.getAction().equals("com.package.UN_REGISTER")
//call your unregister method
Add action in Manifest in your service Tag
<IntentFilter>
<action name = "com.package.UN_REGISTER">
</IntentFilter>
You should use Bound Services for this. Check link for implementation and usage
If you want to correctly register and unregister a BroadcastReceiver. The BroadcastReceiver passed in registerReceiver() and unregisterReceiver() must be the same instance, so is the Context instance be invoked. Because the implement uses Context and BroadcastReceiver instances to uniquely map to a "Register operation".

interface cannot be cast (ClassCastException: AlarmReceiver cannot be cast to AlarmReceiver$OnAlarmOver)

I created a alarm and I hope when alarm is stop can set a String to TextView in MainActivity so I try to use interface but it's get error :
Caused by: java.lang.ClassCastException: AlarmReceiver cannot be cast to AlarmReceiver$OnAlarmOver
AlarmReceiver.java
public class AlarmReceiver extends BroadcastReceiver {
public AlarmReceiver() {
}
#Override
public void onReceive(Context context, Intent intent) {
...
OnAlarmOver onAlarmOver = (OnAlarmOver) context; //<--error
onAlarmOver.OnAlarmOverText("Alarm stop");
}
public interface OnAlarmOver {
public void OnAlarmOverText(String overText);
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity implements AlarmReceiver.OnAlarmOver {
...
public void OnAlarmOverText(String overText){
alarm_text.setText(overText);
}
}
My English is very poor, sorry.
You are trying to cast the context to OnAlarmOver. Of course, this is not going to work. I think you want to capture a broadcast emit somewhere else inside of your app.
1) You need to define your broadcast. Then, in your activity, you should register it. For example:
private BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Bundle bundle = intent.getExtras();
if (bundle != null) {
if(intent.getAction().equals(SearchService.NOTIFICATION)){
}
}
}
};
#Override
protected void onResume() {
super.onResume();
registerReceiver(receiver, new IntentFilter(SearchService.NOTIFICATION));
}
Remember to unregister in the pause method
#Override
protected void onPause() {
super.onPause();
unregisterReceiver(receiver);
}
2) You need to create an Intent and the send the broadcast like this.
private void publishResults(Search result) {
Intent intent = new Intent(NOTIFICATION);
intent.putExtra(RESULT, result);
sendBroadcast(intent);
success = true;
}
To sum up, I don't know why you want to use an interface (listener) for this if it is is provided by Android. Maybe, you should explain a little more what do you want to do. I hope this answer can help you.

IntentService does broadcast but onReceive doesn't receive broadcast

(NOTE that at the end of this Question I have an EDIT in which I have replaced one method with what the Answer said to do in order to fix the problem of onReceive never getting called and added onDestroy to fix a new problem that cropped up after fixing first problem.)
Here's how I attempted to capture the broadcast data, but onReceive never gets called since Log.w never displays anything:
public class MatchesActivity extends Activity implements DatabaseConnector.DatabaseProcessListener
{
public static String SOME_ACTION = "com.dslomer64.servyhelperton.SOME_ACTION";
public static String STRING_EXTRA_NAME = "match";
#Override protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
LocalBroadcastManager.getInstance(this).registerReceiver
(
new BroadcastReceiver()
{
#Override public void onReceive(Context context, Intent intent)
{
String s = txaMatches.getText().toString() + intent.getStringExtra(STRING_EXTRA_NAME) ;
txaMatches.setText(s);
Log.w("MatchesActivity","`````onReceive <" + s + ">");
}
}, new IntentFilter(SOME_ACTION)
);
...
DatabaseConnector dbc = new DatabaseConnector(getApplicationContext(), assets);
dbc.setDbProcesslistener(this); // set way to know matches has been defined
dbc.findDBMatches();
} // end onCreate
} // end MatchesActivity
Database connector:
public DatabaseConnector(Context _context, AssetManager _assets)
{
mContext = _context;
//This method, called in `MatchesActivity` on button press, does start the service:
public void findDBMatches()
{
Intent i= new Intent(mContext, QueryDB.class);
mContext.startService(i);
}
// Here's the service:
public static class QueryDB extends IntentService
{
public QueryDB() { super(QueryDB.class.getSimpleName()); }
public QueryDB(String name) { super(name); }
//Here's the procedure that does all the work (and it does execute):
#Override protected void onHandleIntent(Intent intent)
{ ...
publishProgress(dicWord); // a String
}
//This does execute but it doesn't send `progress` back to `MatchesActivity`,
//which initiated request for service (note: `publishProgress` is so named
//because `QueryDB` used to be an `AsyncTask` and I just didn't change the name):
protected void publishProgress(String progress)
{
Intent intent = new Intent(MatchesActivity.SOME_ACTION);
intent.putExtra(MatchesActivity.STRING_EXTRA_NAME, progress);
this.sendBroadcast(intent); // THIS LINE IS THE PROBLEM, FIXED BELOW
Log.w("DatabaseConnector", "`````publishProgress <" + progress + ">");
}
}
What connection(s) have I failed to make?
EDIT
This is the CORRECTED method found just above:
protected void publishProgress(String progress)
{
Intent intent = new Intent(MatchesActivity.SOME_ACTION);
intent.putExtra(MatchesActivity.STRING_EXTRA_NAME, progress);
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}
}
Here is onDestroy in MatchesActivity (which starts the service), necessary to call when service has finished its work:
#Override protected void onDestroy()
{
super.onDestroy();
LocalBroadcastManager.getInstance(this).unregisterReceiver(mMessageReceiver);
}
Note that onDestroy refers to a new MatchesIntent variable, defined as:
private BroadcastReceiver mMessageReceiver = new BroadcastReceiver()
{
#Override public void onReceive(Context context, Intent intent)
{
String s = intent.getStringExtra(STRING_EXTRA_NAME) ;
txaMatches.append(s + "\n");
}
};
And onCreate in MatchesActivity got simpler because of defining mMessageReceiver:
#Override protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
LocalBroadcastManager.getInstance(this).registerReceiver
(
mMessageReceiver, new IntentFilter(SOME_ACTION)
);
}
What connection(s) have I failed to make?
In your first block of code, you are using LocalBroadcastManager. In your second block of code, you are not.
Replace:
this.sendBroadcast(intent);
with:
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);

Broadcast Receiver not receiving

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))

Categories

Resources