-----------------------------------------------------------------------------------------------
Starting activities Using Intents :-
To start an activity use the method startActivity(intent). This method is defined on the Context object which Activity extends.
The following code demonstrates how you can start another activity via an intent.
say: Activity1 (Sender Activity)
Button btn = (Button)findViewById(R.id.goBackBtn);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//write an Intent to redirect to Activity2--
Intent gotoActivity2= new Intent();
gotoActivity2.setComponent(new ComponentName(Activity2_pkg_name, Activity2_class_name));
MainActivity.this.startActivity(gotoActivity2); //the Current Activity(ie MainActivity) will start the Intent -'gotoActivity2'
}
});
say: Activity2 (Sub-Activity/ Target Activity/)
Activities which are started by other Android activities are called sub-activities.
public void onClick(View v){
//write an Intent to redirect to Activity1--
Intent gotoActivity1= new Intent();
gotoActivity1.setComponent(new ComponentName(Activity1_pkg_name, Activity1_class_name));
this.startActivity(gotoActivity1); //the Current Activity will start the Intent -'gotoActivity1'
}
So, as soon as the control comes to this onClick() method the current activity will start an Intent named-'gotoActivity1' which will take the control back to activity1.
Note: the text highlighted with green should be replaced by you in application. Something like this:
Activity1_pkg_name could be replaced by a package name of activity1 say: [com.blogs.prabhakar.activity1]
-----------------------------------------------------------------------------------------------
Passing/Receiving data through Intent ...
I am trying to pass data through my Intent into the next activity so I can receive itsay: Sender Activity
Hereby , im sending the following three params [isLocationAvailable , latitude, longitude] alongwith the Intent & receiving the same in the Receiver Activity(Target Activity)...
Intent gotoActivity2= new Intent();
gotoActivity2 .setComponent(new ComponentName(Activity2_package_name, Activity2_class_name));
gotoActivity2 .putExtra(isLocationAvailable,true);
gotoActivity2 .putExtra(latitude ,dest_Coordinates.latitude);
gotoActivity2 .putExtra(longitude, dest_Coordinates.longitude);
this.startActivity(gotoActivity2 );
say: Receiver Activity
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
boolean isLocationAvailable = getIntent().getExtras().getBoolean("isLocationAvailable");
if(isLocationAvailable){
double dest_lat = getIntent().getExtras().getDouble("latitude");
double dest_lng = getIntent().getExtras().getDouble("longitude");
toPosition = new LatLng(dest_lat, dest_lng);
}
}
---------------------------------------------------------------------------------------------------
No comments:
Post a Comment