I want to start one of my existing activities and force the activity to call a specific method after it starts. Is this possible?
Can I define a method that should b
You question seems interesting, but there is no way you can do it using Intent
. You have to understand that when you start an activity, it goes through a life cycle which is : onCreate()
->onStart()
->OnResume()
. So what you can do is start that method from onResume()
like this:
@Override
protected void onResume() {
super.onResume();
myMethod();//start your method from here
}
I'm just trying to help,give me some more information about your problem if this approach does not solve your problem.
Hello You can't call a particular method from intent but alternately you can use a service from intent and your requirement will be done.
Intent intent = new Intent(this, MyService.class);
and in MyService.class
public class MyService extends Service {
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
yourParticularMethod(); //do your task and stop the service when your task is done for battery saving purpose
context.stopService(new Intent(context, MyService.class));
return super.onStartCommand(intent, flags, startId);
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
}
and register this service in your manifest file like this
<service android:name=".MyService" />
.
.
</application>
I solve this issue by using onCreate
instead of onNewIntent
.
Activity A:
Intent intent = new Intent(this, com.app.max.Home.class);
intent.putExtra("methodName","myMethod");
startActivity(intent);
com.app.max.Home Activity:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.home);
if(savedInstanceState == null)
{
Bundle extras = getIntent().getExtras();
if (extras == null)
{
//Extra bundle is null
}else{
String method = extras.getString("methodName");
if (method.equals("myMethod"))
{
//Call method here!
}
}
}
Hope this solution solve your problem
No, I don't think you can have something like this:
Intent intent = new Intent(this, com.app.max.Home.class.method);
but you can do this:
Intent intent = new Intent(this, com.app.max.Home.class);
intent.putExtra("methodName","myMethod");
startActivity(intent);
and then in the called activity (where you need to start the method), you can take the intent and decide which method to call like this:
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
if(intent.getStringExtra("methodName").equals("myMethod")){
mymethod();
}
}