Is it safe to reuse an intent? - android

The Android docs define an Intent as "a bundle of information containing an abstract description of an operation to perform". This suggests that you should be able to reuse a single Intent object multiple times if needed, but I haven't seen any examples showing this is the case/ is safe to do. Is there any reason to NOT do the following:
private final Intent enableBluetoothIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
...
protected void onCreate(Bundle savedInstanceState) {
enabledBluetoothIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 0);
...
}
and then call startActivityForResult(enableDiscoverableIntent, REQUEST_ENABLE_BT_DISCOVERY) in multiple places in the code? What happens if the same intent is started twice?

It is completely safe when you want to use it to do the exact same thing, since an Intent is no more than a bunch of data and instructions. If you want to use the same Intent object for different purposes (for example you have a bunch of tabs and try to set the tabs reusing the same intent but changing the activity they'll launch) you have to be more careful, and I'd recommend re-creating a new Intent object for each.

Related

Pass Value from First Activity to Third Activity via AsyncTask

I have an Online Ordering System from where users can complete the order in, at least, three steps. Each step below is a separate activity:
Make selection of a Plan
Select the Starting Date
Select Contents based on selected Plan in Step 1.
Now what I have done in step 1 is, once user clicks on a Plan and Order, below code runs onClick.
Intent intent = new Intent(context, SelectDate.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Bundle extras = new Bundle();
extras.putString("pass_selected_meal_plan_id",mp_id_pass);
extras.putString("pass_selected_meal_name",mp_name_display);
intent.putExtras(extras);
context.startActivity(intent);
Toast.makeText(context, mp_name_display+" Selected",
Toast.LENGTH_SHORT).show();
No in the second Activity, I am asking the user to select the order starting date. That is also simple enough and have no issues in it. But the issue begins when I am trying to switch to the third activity.
Since my third activity content is depending on the Plan selection made in the first activity, therefore I have to transfer the selected ID to the third activity. I have it in Extra Bundle in second activity as "pass_selected_meal_plan_id".
The way I am loading the third activity is also crucial. There are two possible ways to start the third activity. First is very simple by putting onClick on the next button. I assume that it will be very simple to transfer the required selection as well. But in this case, as far as I know being a beginner in Android App Development, I will have to give a button to click and load content based on the selected Plan.
The second way is what I want to use. I am running an AsyncTask in the second activity onClick Next. It is working perfectly fine. The only this is I am unable to getExtras in onPostExecute from the previous Activity, i.e. first activity.
I am open to even using Global Variables, but don't really know how to do. Knowing what Global Variables are, I am not too keen to use them instead.
Here is my onPostExecute code:
#Override
protected void onPostExecute(String result) {
Intent intent = new Intent(ctx, SelectMeals.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Bundle extras = new Bundle();
//Instead of "1" I want the value from previous Activity, which already available in Extras from previous Activity
extras.putString("pass_selected_meal_plan_id", "1");
//This is the second value I want to be transferred from first activity to the third activity
extras.putString("pass_selected_meal_name","Test");
intent.putExtras(extras);
ctx.startActivity(intent);
}
Would really appreciate if anyone can help.
You can use below code
In your second activity
// declare global variables
String id;
String name;
Use below code inside onCreate
Bundle bundle = getIntent().getExtras();
//Extract the data…
id = bundle.getString("pass_selected_meal_plan_id");
name = bundle.getString("pass_selected_meal_name");
Now in your Asynctask, write the code below before launching 3rd activity.
#Override
protected void onPostExecute(String result) {
Intent intent = new Intent(ctx, SelectMeals.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Bundle extras = new Bundle();
extras.putString("pass_selected_meal_plan_id",id); // first activity data
extras.putString("pass_selected_meal_name",name); // first activity data
intent.putExtras(extras);
ctx.startActivity(intent);
}
Finally, you can get these values in third activity.
One important point I would like to highlight is that avoid using generic variable names, e.g. id. It is used just for reference in this answer but it is not a good idea. One obvious problem you may face doing so is with Refactor > Rename. It will change even the #+id in XML files.

Get calling activity from some other activity

I am calling an activity from another activity by this code:
Intent intent = new Intent(context, mClass);
context.startActivity(intent);
and from my new activity which is started by this code. I want to know which activity starts this activity. I used this code for this purpose
Intent intent = getIntent();
Class<?> c = intent.getClass();
if (c != OffersActivity.class) {
prepareForNotifications();
setListAdapter();
}
but by this code I am not able to get the classname which starts this activity. I really need some help.
thanks
There is a method getCallingActivity(), but that only works, if the calling activity calls you with startActivityForResult(). I have seen libraries use that and say that you must call them that way, but frankly it is a bit nasty. The simple answer is that you're not supposed to know. Android is a system of loosely coupled activities and the calling activity should thus have no real meaning to your activity. Any information your activity needs should be put explicitly in the intent, so if you really want to know who called you then the caller needs to put that extra in. You won't be able to tell if they are lying of course, so don't go trying to use this for anything security-related. However, I would suggest that whatever you're determining based on the caller, is what the caller should be passing you instead. Might be time for a rethink on why you want to do this, since trying to fight the system will only lead to pain.
I would suggest:
public static final String INTENTSENDER = "sender";
void mMethod() {
Intent intent = new Intent(context, mClass);
intent.putExtra(INTENTSENDER, mClass);
context.startActivity(intent);
}
knowing who sent it:
Class<?> c = (Class<?>)intent.getExtras().get(INTENTSENDER);
However, you can also use this:
ComponentName componentName = this.getCallingActivity();
Now, you can use componentName to get the sender of the intent.
Maybe it's best to use the extras parameters in the intent when you call them...like: Intent.putExtra(PARAM,value) on the caller activity...and on the opened activity you check:
intent.getStringExtra(PARAM)
getParentActivity() is not what yout are looking for?

How do i create Intent and to where to put the codes?

I am trying to follow the lesson here and now im stuck on "Building an Intent". I am quite confused for how to make this Intent and where to paste it. Can someone show me the step by step process on this tutorial? I am getting massive headaches now. Please I want to learn to do this.
Build an Intent
An Intent is an object that provides runtime binding between separate
components (such as two activities). The Intent represents an app’s
"intent to do something." You can use intents for a wide variety of
tasks, but most often they’re used to start another activity.
Inside the sendMessage() method, create an Intent to start an activity
called DisplayMessageActivity:
Intent intent = new Intent(this, DisplayMessageActivity.class); The
constructor used here takes two parameters:
A Context as its first parameter (this is used because the Activity
class is a subclass of Context) The Class of the app component to
which the system should deliver the Intent (in this case, the activity
that should be started)
As the tutorial says, you need to add the line of code that creates an new instance of the Intent class. You will use this instance later to tell the OS to launch another activity or a service. In this particular example, the Intent you are building will direct the OS to launch the DisplayMessageActivity.
To do this step properly, you need to modify the sendMessage method that you have added in the previous step of the tutorial. The final method should look something like this:
/** Called when the user clicks the Send button */
public void sendMessage(View view) {
Intent intent = new Intent(this, DisplayMessageActivity.class);
EditText editText = (EditText) findViewById(R.id.edit_message);
String message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);
}
After creating the Intent, the code will take the content of the editText control in the current activity, assign it to the message variable, and then add it as an additional parameter to the intent, so that the target DisplayMessageActivity activity can do something with it.
Don't worry about the DisplayMessageActivity yet. It will be added in a later step.
How do i create Intent and to where to put the codes?
You want to open the activity using intent then you can write your code in this method.
/** Called when the user clicks the Send button */
public void sendMessage(View view) {
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
startActivity(intent);
}

Get parameters from the intent used for onResume()

I'm using a LocalActivityManager to have activities in different tabs, when I switch from a tab to another one, I start the Activity corresponding to the tab selected.
My problem is simple :
if I click on tab 1, I create intent11 and the first time, the method onCreate(Bundle emptyBundle) of Activity1 is called.
If I click on tab 2, I create intent2 and the method onCreate() is called.
Then, when I click on tab1, I create intent12 , the method onCreate(Bundle emptyBundle) is not called but onResume() is called (normal behavior).
I put special extras in the intent11 and intent12 to create Activity1, so I access it using getIntent().getExtras().
My problem is : the second time I go to the tab1, the intent12 is used to start the Activity, but the result of getIntent() is still intent11.
So I can't retreive the extras set in intent12, I can only retreive the extras set in intent11.
What am I doing wrong ? Should I avoid putting extras() in the intents ? Thank you.
Thank you.
PS : for the moment, I set a special flag to my intent to force to call onCreate(), but I'm sure it's not the good way of doing it.
I believe what you are looking for is here:
https://developer.android.com/reference/android/app/Activity.html#onNewIntent%28android.content.Intent%29
onNewIntent(Intent newIntent) allows you to override the previous intent that was used to create/resume the app with the newest intent.
In Xamarin.Android / Monotouch I just added the following method to my Activity and it worked smoothly.
protected override void OnNewIntent(Intent intent)
{
base.OnNewIntent(intent);
Intent = intent;
}
The principle should work fine also in Native Android.
no you should be able to still put the extras but I'm wondering if the extras are getting 'overwritten' when you are creating the new intents so I suggest trying this:
Put your extras into the bundle for the first intent you create, then before creating the next intent set your bundle to whatever might be in the bundle already by doing
Bundle bundle = getResultExtras(false);
Then you can create your new intent then when you are ready to get your data out of the bundle you can do
Bundle bundle = getResultExtras(false);
again and then get your data like you normally would from the bundle, just make sure that the extras your put in Intent1 don't have the same key name as the extras you put in Intent2
hope that helps some.
if you need more specific help it might be useful to post your code.

Difference Between 2 Ways to Start an Activity?

I have seen the following two examples of starting activities in Android:
Example 1
Intent myIntent = new Intent(CurrentActivity.this, NextActivity.class);
CurrentActivity.this.startActivity(myIntent);
Example 2
// Calling activity
NextActivity.show(this)
// In the called activity
static void show(Context context) {
final Intent intent = new Intent(context, NextActivity.class);
context.startActivity(intent);
}
It seems the obvious difference between the two examples is that you attach the logic of how an activity is created to the implementation of the activity. Are there any other key differences? (e.g. is the calling activity told to wait until the called activity finishes in one case, but not in the other, etc.)
I see no difference to your 2 methods, other than the 2 lines of code in your first method just happen to be located in a static method that just happens to be located in the 2nd activity's class.
The actual lines of code that are being executed to start the activity are identical. Thus the behavior of the 2 methods will be identical.
Also, the code could be shortened to
context.startActivity(new Intent (context, NextActivity.class));
Only reason to create an instance of Intent as a field is if you need to set flags or add extras, etc.

Categories

Resources