LocalBroadcastManager not receiving broadcasts in a Activity - android

I am using a LocalBroadcastManager to make broadcast to my activtiy and services using APPLICATION CONTEXT , like this:
public class CommonForApp extends Application{
public void broadcastUpdateUICommand(String[] updateFlags,
String[] flagValues) {
Intent intent = new Intent(UPDATE_UI_BROADCAST);
for (int i = 0; i < updateFlags.length; i++) {
intent.putExtra(updateFlags[i], flagValues[i]);
}
mLocalBroadcastManager = LocalBroadcastManager.getInstance(mContext);
mLocalBroadcastManager.sendBroadcast(intent);
}}
Now Using a Listener in my Service, I am calling broadcastUpdateUICommand() ,like this:
public class mService extends Service {
public BuildNowPLaylistListListener buildCursorListener = new BuildNowPLaylistListListener() {
#Override
public void onServiceListReady() {
mApp.broadcastUpdateUICommand(
new String[] { CommonForApp.INIT_DRAWER},
new String[] {""});
}}}
And i am receiving the broadcast in my Activity, like this:
public class mActivity extends Activity{
BroadcastReceiver mReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
mtoast.showtext("in onreceive"); //toast to check
if (intent.hasExtra(CommonForApp.INIT_DRAWER))
initialiseDrawer();
}};
}
mApp is instance of Application.
CommonForApp is my Application Class.
But in my activity i am not receving any broadcast(the broadcast manager is initialised using application context) .
Can Anyone suggest me why i am not receiving broadcast in my activity? ..
.Thanks in advance !

in activity:
protected BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, final Intent intent) {
runOnUiThread(new Runnable() {
#Override
public void run() {
if(intent.hasExtra("type")){
// Do some action
}
}
});
}
};
#Override
public void onCreate(Bundle savedInstanceState, PersistableBundle persistentState) {
super.onCreate(savedInstanceState, persistentState);
LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver,
new IntentFilter("data-loaded"));
}
protected void onDestroy() {
super.onDestroy();
LocalBroadcastManager.getInstance(this).unregisterReceiver(mMessageReceiver);
}
then you send broadcast:
public static void sendBroadcastMessageDataLoaded(Context context, String dataType){
Intent intent = new Intent("data-loaded");
intent.putExtra("type", dataType);
LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
}

Related

BroadcastReceiver is receiving like 1 of 10 intents

On button click I am opening activity(ActionListActivity) and sending intent to IntentService (later this service sends broadCast intent to ActionListActivity). But I am usually receiving only the first intent after launch. Is it real that intent is sent before the receiver is registred?
I want to get data providet by the intentService, and update my UI using it.
Scheme Activity->IntentService->BroadCastReceiver inside ActionListActivity
Activity:
private void selectDrawerItem(MenuItem menuItem)
{
switch (menuItem.getItemId()) {
case R.id.actions:{
Intent myIntent = new Intent(this, ActionListActivity.class);
this.startActivity(myIntent);
ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.show();
Intent dataIntent = new Intent(this, DatabaseWorkIntentService.class);
dataIntent.putExtra(Utils.INTENT_SERVICE_INVOKE, Utils.READ_ACTIONS_DATA);
startService(dataIntent);
progressDialog.dismiss();
}
}
}
IntentService:
private void readActionData(){
Log.e("read actions data","data");
List<Action> actionList;
actionList = Action.listAll(Action.class);
Intent broadcastIntent = new Intent();
broadcastIntent.setAction(Utils.READ_ACTIONS_DATA);
broadcastIntent.putParcelableArrayListExtra(Utils.READ_ACTIONS_DATA, (ArrayList<? extends Parcelable>) actionList);
sendBroadcast(broadcastIntent);
}
ActionListActivity:
public class ActionListActivity extends BaseActivity {
boolean mIsReceiverRegistered = false;
DataBroadcastReceiver receiver;
TextView someTv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.action_list_activity);
this.initToolbarAndDrawerWithReadableName(getString(R.string.our_actions));
someTv = (TextView)findViewById(R.id.someTv);
}
public void someTvTest(Action action){
someTv.append(action.getName());
Log.e("data",action.getName());
}
#Override
protected void onPause() {
super.onPause();
if (mIsReceiverRegistered) {
unregisterReceiver(receiver);
receiver = null;
mIsReceiverRegistered = false;
}
}
#Override
protected void onResume() {
super.onResume();
if (!mIsReceiverRegistered) {
if (receiver == null)
receiver = new DataBroadcastReceiver();
IntentFilter filter = new IntentFilter();
filter.addAction(Utils.READ_ACTIONS_DATA);
receiver.setMainActivityHandler(this);
registerReceiver(receiver, filter);
mIsReceiverRegistered = true;
}
}
}
class DataBroadcastReceiver extends BroadcastReceiver{
ActionListActivity activity = null;
ArrayList<Action> list;
public void setMainActivityHandler(ActionListActivity main){
activity = main;
}
#Override
public void onReceive(Context context, Intent intent) {
Log.e("reciever","reciev");
list = intent.getParcelableArrayListExtra(Utils.READ_ACTIONS_DATA);
for (Action action:list){
if(activity!=null) {
activity.someTvTest(action);
}
}
}
}
You start activity and service async.
You need to start service inside ActionListActivity and wait for response.

Calling a function from another class? Android

Store Activity:
public void unlockcup2(){
}
Main Activity:
public void unlock2(){
x = (x-100);
ImageView img5 = (ImageView) findViewById(R.id.bluecake);
img5.setVisibility(View.VISIBLE);
}
Soo, I want to make it so when my button in Store activity(Witch calls unlockcup2()) Call unlock2 in my MainActivity . How do I do this?
localbroadcastmanager can do this job. Send a broadcast in the StoreActivity and receive it in the MainActivity and call unlock2()
MainActivity (Receiver)
private BroadcastReceiver mReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// in this case, there's only one type of action, so no need to check action
unlock2();
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
...
LocalBroadcastManager.getInstance(this).registerReceiver(mReceiver,
new IntentFilter("custom-action-name"));
}
#Override
protected void onDestroy() {
...
LocalBroadcastManager.getInstance(this).unregisterReceiver(mReceiver);
}
StoreActivity (Sender)
public void unlockcup2() {
...
LocalBroadcastManager.getInstance(this)
.sendBroadcast(new Intent("custom-action-name"));
}

Sending Intent from BroadcastReceiver class to currently running activity

I have a class which extends BroadcastReceiver. On receiving a SMS, I would like to pass information to my main activity class to display the text in a box (Append, if already text is present).
public class SmsReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent)
{
Intent i = new Intent(context, MainActivity.class);
i.putExtra("updatedString","Hello");
context.startActivity(i);
}
}
MainActivity.java
public class MainActivity extends Activity{
private TextView results;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Bundle extras = getIntent().getExtras();
if(extras!=null){
results = (TextView) findViewById(R.id.results);
results.setVisibility(View.VISIBLE);
results.append(extras.getString("updatedString"));
}
}
I have only one activity class (MainActivity.java). However When i do this I get an exception Unable to pause Activity.
You have three ways:
1) You can define your broadcast inside your MainActivity like this:
in onCreate()
registerReceiver(smsReceiver, new IntentFilter(SMS_RECIEVED));
and define smsReciver in MainActivity
private BroadcastReceiver smsReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
//you can update textBox here
handler.postDelayed(sendUpdatesToUI, 10);
}
};
define a runnable to update UI
private Runnable sendUpdatesToUI = new Runnable() {
public void run() {
update();
}
};
and update method
private void update(String text) {
textView.setText(textView.getText().toString() + text);
}
2) Register a receiver between your Activity and BroadCastReceiver
3) Start your Activity with new Intent to update current open Activity
Intent intent = new Intent(context, MainActivity.class);
intent.putExtra("Key", "text");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
UPDATE :
explain method 2
MainActivity.class
in onResume()
registerReceiver(broadcastReceiver, new IntentFilter(SmsReceiver.BROADCAST_ACTION));
in onDestroy()
unregisterReceiver(broadcastReceiver);
local broadCast (broadcastReceiver, in MainActivity.class)
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
updateUI(intent);
}
};
private void updateUI(Intent intent) {
String text = intent.getStringExtra("key");
textView.setText(textView.getText().toString() + text);
}
SmsReceiver.class
global attribute
public static final String BROADCAST_ACTION = "your.package.name.displayevent";
private final Handler handler = new Handler();
Intent intent;
Context context;
in onReceive()
handler.removeCallbacks(sendUpdatesToUI);
handler.postDelayed(sendUpdatesToUI, 10);
this.context = context;//you can retrieve context from onReceive argument
this.intent = new Intent(BROADCAST_ACTION);
define two method
private Runnable sendUpdatesToUI = new Runnable() {
public void run() {
display();
}
};
private void display() {
intent.putExtra("key", text);
context.sendBroadcast(intent);
}
Modify your code as below.
public class SmsReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent)
{
Intent i = new Intent(context, MainActivity.class);
i.putExtra("updatedString","Hello"); i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_SINGLE_TOP);
context.startActivity(i);
}
}
public class MainActivity extends Activity{
private TextView results;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Bundle extras = getIntent().getExtras();
if(extras!=null){
results = (TextView) findViewById(R.id.results);
results.setVisibility(View.VISIBLE);
results.append(extras.getString("updatedString"));
}
#Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
//handle your intent here.Note this will be called even when activity first created.so becareful to handle intents correctly.
}
}

LocalBroadcastManager not working as expected

In my Application I have to notify my Activity from IntentService class .
For that purpose I am using LocalBroadcastManager. But I am not receiving anything in the onReceive of my Broadcast Receiver. Here is what I have written.
In my BaseActivity I have registered my receiver.
public class BaseActivity extends FragmentActivity implements App {
#Override
protected void onCreate(Bundle arg0) {
super.onCreate(arg0);
}
#Override
protected void onResume() {
super.onResume();
LocalBroadcastManager.getInstance(this).registerReceiver(
mMessageReceiver, new IntentFilter(custom-event-name));
}
#Override
protected void onPause() {
super.onPause();
LocalBroadcastManager.getInstance(this).unregisterReceiver(
mMessageReceiver);
}
// Our handler for received Intents. This will be called whenever an Intent
// with an action named "custom-event-name" is broadcasted.
BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Bundle bundle = intent.getExtras();
System.out.println("Overlay Message" +bundle.getString("message"));
}
};
}
I am sending a local broadcast from my RegisterAlarmIntentService class.
public class RegisterAlramIntentService extends WakefulIntentService implements
APIConstants {
public RegisterAlramIntentService() {
super("AlarmService");
}
#Override
public String getTag() {
return "AlarmService";
}
#Override
protected void onHandleIntent(Intent intent) {
System.out.println("Working till here fine In RegisterAlarm");
Bundle bundle = intent.getExtras();
Intent localIntent = new Intent(custom-event-name);
localIntent.putExtras(bundle );
LocalBroadcastManager.getInstance(this).sendBroadcast(
localIntent);
}
}
onHandleIntent() method is called. But nothing is received in onReceive() of my receiver.
Please Help. Thanks in advance!!
Try
public class RegisterAlramIntentService extends WakefulIntentService implements
APIConstants {
Intent localIntent;
public RegisterAlramIntentService() {
super("AlarmService");
localIntent = new Intent(custom-event-name);
}
#Override
public String getTag() {
return "AlarmService";
}
#Override
protected void onHandleIntent(Intent intent) {
System.out.println("Working till here fine In RegisterAlarm");
Bundle bundle = intent.getExtras();
Thread.sleep(5000); // For Testing only because it is in whole new thread (which may not wait for your reciever to setup)
localIntent.putExtras(bundle );
LocalBroadcastManager.getInstance(this).sendBroadcast(
localIntent);
}
}
Also in manifest :
<service android:name="com.commonsware.android.localcast.RegisterAlramIntentService"/>
See this

LocalBroadcastManager Broadcasting not being receieved

I've tried the examples from many different answers to similar questions, but nothing works. When I press the back button, I get "Broadcasting message" in the log but not "Broadcast received". Why?
public class MainActivity extends ActionBarActivity
implements ContactsFragment.ContactListener {
private IntentFilter filter;
private BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Log.d(TAG, "Broadcast received");
}
};
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
...
filter = new IntentFilter(Constants.BROADCAST_ACTION);
LocalBroadcastManager.getInstance(this).registerReceiver(receiver, filter);
}
#Override
public void onBackPressed() {
Log.d("sender", "Broadcasting message");
Intent intent = new Intent(Constants.BROADCAST_ACTION);
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
if (!pane.isOpen()) {
pane.openPane();
} else {
finish();
}
}
#Override
public void onPause() {
LocalBroadcastManager.getInstance(this).unregisterReceiver(receiver);
super.onPause();
}
}

Categories

Resources