简体   繁体   中英

How can a PhoneGap plugin change the menu on Android?

I've written a PhoneGap plugin for Android that gets called from the browser on various events, and I'd like it to affect what menu items are shown when the Menu button is pressed. For example, I'd like to disable a certain event, or add certain items. Following the directions on the Android site , I know I need to override onPrepareOptionsMenu() to dynamically change the menu items.

Currently, my solution involves writing a file in the plugin, and then parsing that file in onPrepareOptionsMenu. Is there a better way of doing this? And is there any way to get a handle to the main Activity from the plugin?

edit: One other way I've just done is to use a public static variable in the main Activity class that I access from the plugin.

I have used the SharedPreferences ( PreferenceManager.getDefaultSharedPreferences ) to exchange data between plugin and activity. Although it may not suite your situation completely but here is the way I used it.

Plugin1.java

public PluginResult execute(String action, JSONArray args, String callbackId) {
        PluginResult result = new PluginResult(Status.OK);
        result.setKeepCallback(true);

        // Set the preference data based on plugin call
        counter++;
        PreferenceManager.getDefaultSharedPreferences(this.ctx.getApplicationContext()).edit().putInt("counter", counter).commit();

        return result;
}

AppActivity.java

public boolean onPrepareOptionsMenu(Menu menu) {
        int counter = PreferenceManager.getDefaultSharedPreferences(this.getApplicationContext()).getInt("counter", 0);
        Log.i("App", "counter value - " + counter);

        return super.onPrepareOptionsMenu(menu);
}

In my case the shared preferences did the job as it persists the data. You can look into other options here

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