I have 2 activities . Activity 1 has Information. Activity 2 has a form to update Information in Activity 1 .
How can i return yo Activity 1 and show updated information ?
When i move from activity to another should i use finish () ?
Starting another activity doesn't have to be one-way. You can also start another activity and receive a result back. To receive a result, call startActivityForResult() (instead of startActivity()).
For example, your app can start a camera app and receive the captured photo as a result. Or, you might start the People app in order for the user to select a contact and you'll receive the contact details as a result.
Of course, the activity that responds must be designed to return a result. When it does, it sends the result as another Intent object. Your activity receives it in the onActivityResult() callback.
This the detailed link of about startActivityForResult
Use this pattern.. dont have to override back pressed it will automatically use the super method.. So, in activity 1 use this field var..
BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// update the info and UI here
}
};
onResume() of activity 1
LocalBroadcastManager.getInstance(mContext).registerReceiver(mBroadcastReceiver ,new IntentFilter("info"));
and in Activity 2
Intent intent= new Intent("info");
intent.putExtras("infoss",*yourInfo*);
LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
Note The activity 1 will be automatically updated with correct info .. you dont need to use onBackPressed() logic for this
In your first activity
In the second Activity when your work is done and you want to send data from the second activity to the first activity
receive data in the first activity
Related
I would like to pass data between activities. When I use one activity (Details), everything works fine, but when I add a second activity (MapsActivity), the application ignores (Details) and transfers data only to MapsActivity. How can I fix it? Thanks in advance
holder.itemView.setOnClickListener(v -> {
Intent mIntent = new Intent(context, Details.class);
Intent mapIntent= new Intent(context,MapsActivity.class);
mIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mapIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mIntent.putExtra("Country_CurrencyCode", pozycja.getCurrencies().get(0).getCode());
mIntent.putExtra("Country_CurrencyName", pozycja.getCurrencies().get(0).getName());
mIntent.putExtra("Country_CurrencySymbol", pozycja.getCurrencies().get(0).getSymbol());
context.startActivity(mIntent);
mapIntent.putExtra("Country_Lat",pozycja.getLatlng().get(0));
mapIntent.putExtra("Country_Lng",pozycja.getLatlng().get(1));
context.startActivity(mapIntent);
This is a behavior I did not expect but after testing your code, I found these:
You start 1st the Details activity and 2nd the MapsActivity.
The result is that you see on the screen the 2nd activity: MapsActivity.
For this activity you can check that it's got all the extra values that you passed.
What is happening is that although you have also started the 1st activity: Details, its onCreate() has not yet been invoked, but it will be invoked as soon as you close the 2nd activity MapsActivity and then you will see that its extras are there as you put them. So the 1st activity gets the extras fine but until its onCreate() is called you can't access them.
So a workaround:
Start only Details activity but pass to it not only its own extras but MapsActivity's extras also. In Details's onCreate() start MapsActivity with
its own extras.
I have an application that uses Urban Airship for push notification. When a notification arrives and the user clicks on it, activity A in my application should open and do something.
I've installed the BroadcastReceiver as is shown in the docs, and it's almost working.
When my app is in the foreground I don't let the user see the notification at all, and just handle it automatically.
When my app is not running at all, the activity opens up just fine.
When my app is in the background (which always happens when A is the top activity), a second instance of Activity A is created.
This is, of course, a problem. I don't want two A activities, I just want one of them. Here's the relevant BroadcastReceiver code:
#Override
public void onReceive(Context ctx, Intent intent)
{
Log.i(tag, "Push notification received: " + intent.toString());
String action = intent.getAction();
int notificationId = intent.getIntExtra(PushManager.EXTRA_NOTIFICATION_ID, -1);
if(action.equals(PushManager.ACTION_NOTIFICATION_OPENED))
{
Intent intentActivity = new Intent(ctx, ActivityA.class);
intentActivity.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
UAirship.shared().getApplicationContext().startActivity((intentActivity);
}
}
UPDATE:
I tried to bypass this bug by calling System.exit(0) when the user presses Back on Activity A. The process ended, but then it was restarted immediately! My BroadcastReceiver is not called again in the second instance. What's happening?
UPDATE 2:
#codeMagic asked for more information about the app and activity A.
This app lets its user review certain items and comment on them. Activity A is started when the app is launched. If the user's session isn't valid any more, a Login activity is started. Once the user logs in, activity A becomes active again. A only has a "No items to review" message and a "Try now" button.
When the user logs in, the server starts sending push notifications whenever a new item is available for review. When the app gets the notification, activity A accesses the server and gets the next item to review. The item is shown in activity B. Once the review is submitted to the server, activity B finishes and activity A is again the top activity.
The server knows when a user is reviewing an item (because activity A fetched it), and doesn't send push notifications until the review is submitted - meaning a notification can't come if the user isn't logged in or if the user is viewing activity B.
While I agree there is a subtle race condition here, it is not causing the problem I'm seeing - in testing I am 100% positive there's no race condition - the push notification is only sent after Activity A becomes active again.
The solution was to add a launchMode='singleTask' to the activity in AndroidManifest.xml . As a result, instead of a new activity, onNewIntent of the same activity instance is called.
You can use one of several Intent Flags. FLAG_ACTIVITY_REORDER_TO_FRONT being one of them. This will bring the Activity to the front of the stack if it is already in the stack and if not then it will create a new instance. I believe you will still need FLAG_ACTIVITY_NEW_TASK if you aren't calling it from an Activity
Intent.FLAG_ACTIVITY_CLEAR_TOP should also work. But this will clear any other Activities on the stack. It just depends on what other functionality you need. Look through the Intent Flags and see which of these will work best for you
There are multiple scenarios when this could happen. One of them can be handled this way. Please see my answer here: https://stackoverflow.com/a/44117025/2959575
Ok, two notes on this :
You can register a broadcast receiver via the manifest so it is independent of any parts of your app. and use a Singleton pattern (keep a static reference to your activity somewhere in your app) that way you can check if their is an activity viewing or not and process accordingly.
// your activity A
#Override
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
myActivityReference = this;
}
public void onPause() {
super.onPause();
if (isFinishing()) {
myActivityReference = null;
}
}
or you can keep everything as it is and use activity lunching modes flags in your manifest such as singleTop, singleInstance ... etc. take a look here android activity lunch modes
So, I've got a question !
I have got an activity called X. When the user click on a button, the activity Y is displayed.
I want that this activity can be closed after have received an event sent by activity X.
Do you know how can I do this ?
Send a BroadcastMessage from X. In y register a BroadcastReceiver with same IntentFilter. So from x you can send a predefined exit message which will be catched by y activity's onReceive method. There you can end the activity Y.
For Example:
in Y activity
private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Bundle extras = intent.getExtras();
if (extras != null) {
if (extras.containsKey("exit")) {
finish();
}
}
}
dont forget to register the receiver
registerReceiver(
mMessageReceiver,
new IntentFilter(Constants.YOUR_INTENT_FILTER));
and unregister
unregisterReceiver( mMessageReceiver);
IN X activity:
send the broadcastmessage using `sendBroadcast(Intent i)`
For this kind of internal messaging I prefer LocalBoradcastManager
Unfortunately you can not have two activities "running" at the same time. Activity X goes through its end of lifecycle when you start Activity Y.
See: http://developer.android.com/guide/components/activities.html
Each time a new activity starts, the previous activity is stopped, but the system preserves the activity in a stack (the "back stack"). When a new activity starts, it is pushed onto the back stack and takes user focus. The back stack abides to the basic "last in, first out" stack mechanism, so, when the user is done with the current activity and presses the Back button, it is popped from the stack (and destroyed) and the previous activity resumes. (The back stack is discussed more in the Tasks and Back Stack document.)
When you receive BroadcastMessage from ActivityX then you can set value of one Global boolean
you should check that value of bolean at the time of use of Activity Y(it may in onCreate )
in Activity Y
if you get this boolean value true(or whatever you set at the time of call BroadcastMessage ) then simply call finish()
The thing is android not running two activity at the same time , so
without having activity you can not finish it remotely
I am calling a activity from my service when an incoming call ends as given below
Intent callIntent1 = new Intent(Intent.ACTION_CALL);
callIntent1.addCategory(Intent.CATEGORY_HOME);
callIntent1.addCategory(Intent.CATEGORY_LAUNCHER);
callIntent1.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
callIntent1.setClass(context, com.example.test.MyActivity.class);
Log.d("TAG", "MyActivity");
startActivity(callIntent1);
but my activity starts for a blink and closes and I see the home screen ,my log shows the call given to MyActivity ,I cannot find the reason for this
I think it is because you are not using your intent categories the right way. If you are explicitly calling the startActivity method, you don't need to add a category to your intent. They are meant to be used with intent filters I guess. If you want to detect something, eg a call, a text etc, add an intent filter to your activity.
Edit: see here
How do you get an activity to behave differently (invoke different methods), depending on where it was launched from?
I have an activity which is launched either when a user chooses a song, or when a user presses a 'now playing' button.
Ideally, if a song is selected from activity a, then activity b binds to the service, and tells the service to play the selected song.
If the 'now playing' button is selected from activity a, then activity b binds to the service, but doesn't tell it to start playing the song.
I've gathered that this is achievable somehow via either intents, broadcasts, or just a bunch of if statements, but I'm not sure how best to implement this. Thanks for your help.
You can add a flag (or any other extra details) to indicate whether you want the song started or not in the intent send to activity B.
So in Activity A:
Intent startBIntent = new Intent(this, ActivityB.class);
Bundle extraDetails = new Bundle();
extraDetails.putBoolean("isPlaySong", true);
startBIntent.putExtras(extraDetails);
startActivity(startBIntent);
Then in onCreate() of Activity B, retrieve the details with:
Boolean isPlaySong = getIntent().getExtras().getBoolean("isPlaySong");
You can add launcher component name(or other specific string that is unique) as extras to intent that starts Activity.Then in your Activity get it's intent (use getIntent() ) and retrieve it's extras.Then use Switch-Case to decide what would to do.