简体   繁体   中英

How can I call this method in another activity?

In my main Activity, I have this method:

 public void CancelAlarms() {

            AlarmManager manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
            Intent intent = new Intent(context, AlarmReceiver.class);
            pendingIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
            manager.cancel(pendingIntent);
        }

but I want to call it in my other activity.

How can I call it from one activity to another? Also, would it be alright if I am using context in the method? Would the context change if I call it from another activity to this one?

If you want to make public void CancelAlarms() available in all Activity then create a Base Activity class implement this method in that Activity now extend all your Activity with Base Activity class than you can call this method from any Activity which has extended with Base Activity. Or put public void CancelAlarms() method in Application class. Now using getApplicationContext() you can call this method in Any Activity or Service.

You should probably move this method to a utility class or to a base Activity class, for exactly the reason you mention: it depends on a Context .

You simply won't be able to invoke this method without having a reference to an instance of the Activity it is in, because it is not marked static . And even if you did, it would use its host Activity --probably not what you intend.

Instead, you could make a utility class containing the method. There are two ways to go about this: you could pass the Context in to the function every time, or you could pass a Context once to the class's constructor. The former is probably better for one-off convenience methods grouped into a Utilities class, while the latter is a bit more Java-like and is better if the class has a definite function (like an ActivityAlarmWrangler ).

Finally, you could move the function to a base class. This will be cleanest for simple cases because you don't have to have a different member object in your Activity , but if your Activity already extends a custom superclass, you won't be able to use this method unless you are willing to modify the superclass. Because Java doesn't have multiple inheritance (which would be useful in this case), inheriting this method could get hairy fairly quickly.

static MainActivity mainActivity;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(....);
mainActivity= this;
}

public static MainActivity getInstance() {
return mainActivity;
}

MainActivity.getInstance().CancelAlarms();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM