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"));
}
Related
I want to update an Activity which is not the MainActivity.
So I start a second Activity via a onClick method in MainActivity.
Now the Activty "SecondActivity" is at front.
When I started a Thread in the "MainActivity" how can I reference to the "SecondActivity" to update their TextViews and so on?
PseudoCode
public class activity_MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ThreadSome threadSome= new ThreadSome();
threadSome.start()
}
onClick(View View){
Intent intent = new Intent(this, activity_Second.class);
startActivity(intent);
}
}
Inside Thread
public class ThreadSome extends Thread {
#Override
public void run() {
//This is what I don't know, so I just write what I want to do.
// I know the following Code is wrong and not working.
activity_Second.someTextView.setText("Hi");
}
}
Is a WeakReference the best way to do this, or better work with static TextView objects? How would you solve this problem?
Based on your description, I think you want to do something where there will be some ui change in activity stack based on some event performed in the forground activity. There is a good way to use onActivityResult() via startActivityForResult() but if this is not fullfilling your requirement directly then you can try something like below:
/**
UpdateActivity is the activity where some ui update or action will be taken based on event in EventActivity.
**/
public class UpdateActivity extends Activity {
private BroadcastReceiver mReceiver;
public static final String ACTION_UPDATE = "com.my.internal.activity.action";
...
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_update);
......
//Prepared Intent for broadcast receiver
IntentFilter intentFilter = new IntentFilter(ACTION_UPDATE);
//registering our receiver
this.registerReceiver(mReceiver, intentFilter);
.....
}
//This is the receiver section where you need to do the ui update
mReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
//extract our message from intent
String some_msg = intent.getStringExtra("msg_1"); //parameter received if passed in intent when broadcast called.
//log our message value
Log.i("Message", some_msg);
updateActivityUi();
}
};
private void updateActivityUi() {
// you need to write the code for the update which you want to do after an event done in other activity.
}
#Override
protected void onDestroy() {
super.onDestroy();
//unregister our receiver
this.unregisterReceiver(this.mReceiver);
}
}
public class EventActivity extends Activity {
...
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_event);
......
//Sending BroadcastReceiver against the action ACTION_UPDATE and it will be received by UpdateActivity.
if(condition_for_event) {
Intent i = new Intent(UpdateActivity.ACTION_UPDATE).putExtra("msg_1", "Hey! an event performed here.");
this.sendBroadcast(i);
}
.....
}
....
}
Let me know if it solved your issue.
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);
}
myButton is a button that when clicked is supposed to receive a broadcast from a background IntentService. But the broadcast is never received. However if I move the broadcastReceiver outside of myButton.setOnClickListener function, then I begin to receive broadcasts from my background service.
Is there a way to make the broadcastReceiver receive broadcasts within the setOnClickListener function?
public class MainActivity extends Activity {
private BroadcastReceiver broadcastReceiver;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
myButton = (Button)findViewById(R.id.button1);
myButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context arg0, Intent intent) {
Toast.makeText(MainActivity.this, "BROADCAST RECEIVED", Toast.LENGTH_SHORT).show();
stopService(msgIntent);
}
};
}
});
public void onResume()
{
super.onResume();
IntentFilter filter = new IntentFilter(SimpleIntentService.ACTION_RESP);
filter.addCategory(Intent.CATEGORY_DEFAULT);
registerReceiver(broadcastReceiver,filter);
}
public void onPause()
{
unregisterReceiver(broadcastReceiver);
super.onPause();
}
}
I had to take out the broadcastReceiver from onClick method. This works and broadcast is received:
public class MainActivity extends Activity {
private BroadcastReceiver broadcastReceiver;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
myButton = (Button)findViewById(R.id.button1);
myButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
//do extra stuff
}
});
broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context arg0, Intent intent) {
Toast.makeText(MainActivity.this, "BROADCAST RECEIVED", Toast.LENGTH_SHORT).show();
stopService(msgIntent);
}
};
}
}
Do you forget to registerReceiver?
You might also need to assign a IntentFilter when you register a receiver.
The following is some sample codes from my project:
private class LocationInfoReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// do something
}
}
locationInfoReceiver = new LocationInfoReceiver();
// the key you use setAction() method in your Intent Service
IntentFilter locationInfoReceiverFilter = new IntentFilter("your key");
locationInfoReceiverFilter.addCategory(Intent.CATEGORY_DEFAULT);
registerReceiver(locationInfoReceiver, locationInfoReceiverFilter);
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()
I have an Android Activity that needs to catch two different broadcasts. My current approach is to have a single BroadcastReceiver within the Activity and catch both the broadcasts with it:
public class MyActivity extends Activity {
private MyActivity.BroadcastListener mBroadcastListener;
private boolean mIsActivityPaused = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mylayout);
// Create the broadcast listener and register the filters
mIsActivityPaused = false;
mBroadcastListener = new BroadcastListener();
IntentFilter filter = new IntentFilter();
filter.addAction(Params.INTENT_REFRESH);
filter.addAction(Params.INTENT_UPDATE);
registerReceiver(mBroadcastListener, filter);
}
#Override
protected void onResume() {
super.onResume();
mIsActivityPaused = false;
}
#Override
protected void onPause() {
super.onPause();
mIsActivityPaused = true;
}
#Override
protected void onDestroy() {
unregisterReceiver(mBroadcastListener);
super.onDestroy();
}
private void refresh() {
// refresh
}
private void update() {
// update
}
private class BroadcastListener extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Params.INTENT_REFRESH && !mIsActivityPaused)) {
refresh();
} else if (intent.getAction().equals(Params.INTENT_UPDATE)) {
update();
}
}
}
}
I want to execute refresh() only if my Activity is visible on the screen, but I want to catch INTENT_UPDATE and execute update() during the entire lifetime of the Activity, regardless of whether the Activity is visible or not.
I didn't find any way to unregister only one of the two filters that I register in onCreate, so I use a flag to enable or disable the action to be executed when the INTENT_REFRESH broadcast is caught, depending on the state of the Activity.
The question is: is this the correct approach?
Or, would it be better to have two separate BroadcastReceivers as follows:
public class MyActivity extends Activity {
private MyActivity.BroadcastListenerRefresh mBroadcastListenerRefresh;
private MyActivity.BroadcastListenerUpdate mBroadcastListenerUpdate;
private boolean mIsBroadcastListenerRefreshRegistered = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Create the broadcast listeners
mBroadcastListenerRefresh = new BroadcastListenerRefresh();
mBroadcastListenerUpdate = new BroadcastListenerUpdate();
registerReceiver(mBroadcastListenerRefresh, new IntentFilter(Params.INTENT_REFRESH));
registerReceiver(mBroadcastListenerUpdate, new IntentFilter(Params.INTENT_UPDATE));
}
#Override
protected void onResume() {
super.onResume();
if (mBroadcastListenerRefresh != null && !mIsBroadcastListenerRefreshRegistered) {
registerReceiver(mBroadcastListenerRefresh, new IntentFilter(Params.INTENT_REFRESH));
mIsBroadcastListenerRefreshRegistered = true;
}
}
#Override
protected void onPause() {
super.onPause();
if (mBroadcastListenerRefresh != null && mIsBroadcastListenerRefreshRegistered) {
unregisterReceiver(mBroadcastListenerRefresh);
mIsBroadcastListenerRefreshRegistered = false;
}
}
#Override
protected void onDestroy() {
unregisterReceiver(mBroadcastListenerRefresh);
unregisterReceiver(mBroadcastListenerUpdate);
super.onDestroy();
}
private void refresh() {
// refresh
}
private void update() {
// update
}
private class BroadcastListenerRefresh extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Params.INTENT_REFRESH)) {
refresh();
}
}
}
private class BroadcastListenerUpdate extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Params.INTENT_UPDATE)) {
update();
}
}
}
}
And which one has better performance?
instead, you may provide two different intent filters:
filter for refresh only
IntentFilter filterRefresh = new IntentFilter(Params.INTENT_REFRESH);
filter for refresh and update
IntentFilter filterRefreshUpdate = new IntentFilter();
filterRefreshUpdate.addAction(Params.INTENT_REFRESH);
filterRefreshUpdate.addAction(Params.INTENT_UPDATE);
now you may switch between intent filters by registering and un-registering the desired one but your receiver's implementation would be same
For every action , create IntentFilter and register it.
#Override
protected void onResume() {
super.onResume();
BroadcastListener receiver = new BroadcastListener();
// Register the filter for listening broadcast.
IntentFilter filterRefresh = new IntentFilter(Params.INTENT_REFRESH);
IntentFilter filterUpdate = new IntentFilter(Params.INTENT_UPDATE);
registerReceiver(receiver, filterRefresh);
registerReceiver(receiver, filterUpdate);
}
private class BroadcastListener extends BroadcastReceiver {
public void onReceive(Context ctx, Intent intent) {
if (intent.getAction().equals(Params.INTENT_UPDATE)) {
update();
} else if(intent.getAction().equals(Params.INTENT_REFRESH)) {
refresh();
}
}
}
Using KOTLIN you can do it inline:
broadcastReceiver = NukeBroadcastReceiver()
registerReceiver(broadcastReceiver, IntentFilter().apply {
addAction(ACTION_DESTROY_EVERYTHING)
addAction(ACTION_RESTART_WORLD)
})