如何在不同的活动上调用onOptionsItemSelected

时间:2015-02-11 14:07:17

标签: java android android-activity methods

我有一个活动,在FolderActivity中使用 onOptionsItemSelected(MenuItem item)方法,我想在另一个活动(MainActivity)上调用此方法 主要活动使用CMU Sphinx - 语音识别工具包。 我需要调用FolderActivity到MainActivity的一些方法。

    package com.evolution.filemanager.folders;

    import static android.widget.Toast.makeText;

    import java.io.File;
    import java.util.ArrayList;

    import android.annotation.TargetApi;
    import android.app.ActionBar;
    import android.app.Activity;
    import android.app.Fragment;
    import android.content.Intent;
    import android.content.res.Configuration;
    import android.os.Build;
    import android.os.Bundle;
    import android.support.v4.app.ActionBarDrawerToggle;
    import android.support.v4.view.GravityCompat;
    import android.support.v4.widget.DrawerLayout;
    import android.util.Log;
    import android.view.Gravity;
    import android.view.KeyEvent;
    import android.view.Menu;
    import android.view.MenuItem;
    import android.view.View;
    import android.view.WindowManager;
    import android.widget.AdapterView;
    import android.widget.AdapterView.OnItemClickListener;
    import android.widget.ListView;
    import android.widget.Toast;

    import com.evolution.filemanager.FileManagerApplication;
    import com.evolution.filemanager.about.AboutActivity;
    import com.evolution.filemanager.clipboard.Clipboard;
    import com.evolution.filemanager.clipboard.Clipboard.ClipboardListener;
    import com.evolution.filemanager.clipboard.ClipboardFileAdapter;
    import com.evolution.filemanager.favourites.FavouritesManager;
    import com.evolution.filemanager.favourites.FavouritesManager.FavouritesListener;
    import com.evolution.filemanager.nav_drawer.NavDrawerAdapter;
    import com.evolution.utils.FontApplicator;
    import com.evolution.utils.ListViewUtils;

    import edu.cmu.pocketsphinx.demo.R;

    public class FolderActivity extends Activity implements OnItemClickListener, ClipboardListener, FavouritesListener
    {   
        public static class FolderNotOpenException extends Exception
        {

        }

        private static final String LOG_TAG = "Main Activity";

        public static final String EXTRA_DIR = FolderFragment.EXTRA_DIR;

        DrawerLayout drawerLayout;
        ActionBarDrawerToggle actionBarDrawerToggle;
        File lastFolder=null;
        private FontApplicator fontApplicator;

        public static Activity FOLDERACTIVITY;

        protected void onCreate(Bundle savedInstanceState)
        {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main_folder);

            setupDrawers();
            Clipboard.getInstance().addListener(this);

            FOLDERACTIVITY = this;

            fontApplicator = new FontApplicator(getApplicationContext(), "Roboto_Light.ttf").applyFont(getWindow().getDecorView());
        }

        public FontApplicator getFontApplicator()
        {
            return fontApplicator;
        }

        @Override
        protected void onDestroy()
        {
            Clipboard.getInstance().removeListener(this);
            FileManagerApplication application = (FileManagerApplication) getApplication();
            application.getFavouritesManager().removeFavouritesListener(this);
            super.onDestroy();
        }

        public void setLastFolder(File lastFolder)
        {
            this.lastFolder = lastFolder;
        }

        @Override
        protected void onPause()
        {
            if (lastFolder != null)
            {
                FileManagerApplication application = (FileManagerApplication) getApplication();
                application.getAppPreferences().setStartFolder(lastFolder).saveChanges(getApplicationContext());
                Log.d(LOG_TAG, "Saved last folder "+lastFolder.toString());
            }
            super.onPause();
        }

        public void setActionbarVisible(boolean visible)
        {
            ActionBar actionBar = getActionBar();
            if (actionBar == null) return;
            if (visible)
            {
                actionBar.show();
                setSystemBarTranslucency(false);
            }
            else
            {
                actionBar.hide();
                setSystemBarTranslucency(true);
            }
        }

        @TargetApi(Build.VERSION_CODES.KITKAT)
        protected void setSystemBarTranslucency(boolean translucent)
        {
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) return;

            if (translucent)
            {
                getWindow().setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS, WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            }
            else
            {
                WindowManager.LayoutParams params = getWindow().getAttributes();
                params.flags &= (~WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
                getWindow().setAttributes(params);
                getWindow().clearFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
            }
        }

        public void setupDrawers()
        {
            this.drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
            actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, R.drawable.ic_drawer, R.string.open_drawer, R.string.close_drawer)
            {
                boolean actionBarShown = false;

                @Override
                public void onDrawerOpened(View drawerView)
                {
                    makeText(getApplicationContext(), "drawer open", Toast.LENGTH_SHORT).show();
                    super.onDrawerOpened(drawerView);
                    setActionbarVisible(true);
                    invalidateOptionsMenu();
                }

                @Override
                public void onDrawerClosed(View drawerView)
                {
                    makeText(getApplicationContext(), "drawer close", Toast.LENGTH_SHORT).show();

                    actionBarShown=false;
                    super.onDrawerClosed(drawerView);
                    invalidateOptionsMenu();
                }

                @Override
                public void onDrawerSlide(View drawerView, float slideOffset)
                {
                    super.onDrawerSlide(drawerView, slideOffset);
                    if (slideOffset > 0 && actionBarShown == false)
                    {
                        actionBarShown = true;
                        setActionbarVisible(true);
                    }
                    else if (slideOffset <= 0) actionBarShown = false;
                }
            };
            drawerLayout.setDrawerListener(actionBarDrawerToggle);
            drawerLayout.setDrawerShadow(R.drawable.drawer_shadow, Gravity.START);
            drawerLayout.setFocusableInTouchMode(false);
    //      drawerLayout.setDrawerShadow(R.drawable.drawer_shadow, Gravity.END);

            getActionBar().setDisplayHomeAsUpEnabled(true);
            getActionBar().setHomeButtonEnabled(true);

            setupNavDrawer();
            setupClipboardDrawer();
        }

        @Override
        public void onBackPressed()
        {
            if (drawerLayout.isDrawerOpen(GravityCompat.START))
                drawerLayout.closeDrawer(GravityCompat.START);
            else if (drawerLayout.isDrawerOpen(GravityCompat.END))
                drawerLayout.closeDrawer(GravityCompat.END);
            else
                super.onBackPressed();
        }

        void setupNavDrawer()
        {
            FileManagerApplication application = (FileManagerApplication) getApplication();

            // add listview header to push items below the actionbar
            ListView navListView = (ListView) findViewById(R.id.listNavigation);
            ListViewUtils.addListViewPadding(navListView, this, true);

            loadFavourites(application.getFavouritesManager());
            application.getFavouritesManager().addFavouritesListener(this);
        }

        void setupClipboardDrawer()
        {
            // add listview header to push items below the actionbar
            ListView clipboardListView = (ListView) findViewById(R.id.listClipboard);
            ListViewUtils.addListViewHeader(clipboardListView, this);
            onClipboardContentsChange(Clipboard.getInstance());
        }

        void loadFavourites(FavouritesManager favouritesManager)
        {
            ListView listNavigation = (ListView) findViewById(R.id.listNavigation);
            NavDrawerAdapter navDrawerAdapter = new NavDrawerAdapter(this, new ArrayList<NavDrawerAdapter.NavDrawerItem>(favouritesManager.getFolders()));
            navDrawerAdapter.setFontApplicator(fontApplicator);
            listNavigation.setAdapter(navDrawerAdapter);
            listNavigation.setOnItemClickListener(this);
        }

        @Override
        protected void onPostCreate(Bundle savedInstanceState)
        {
            super.onPostCreate(savedInstanceState);
            actionBarDrawerToggle.syncState();

            if (getFragmentManager().findFragmentById(R.id.fragment) == null)
            {
                FolderFragment folderFragment = new FolderFragment();
                if (getIntent().hasExtra(EXTRA_DIR))
                {
                    Bundle args = new Bundle();
                    args.putString(FolderFragment.EXTRA_DIR, getIntent().getStringExtra(EXTRA_DIR));
                    folderFragment.setArguments(args);
                }

                getFragmentManager()
                    .beginTransaction()
                    .replace(R.id.fragment, folderFragment)
                    .commit();
            }
        }

        @Override
        public void onConfigurationChanged(Configuration newConfig)
        {
            makeText(getApplicationContext(), "unsa ni?", Toast.LENGTH_SHORT).show();

            super.onConfigurationChanged(newConfig);
            actionBarDrawerToggle.onConfigurationChanged(newConfig);
        }

        @Override
        public boolean onOptionsItemSelected(MenuItem item)
        {

            makeText(getApplicationContext(), item.toString(), Toast.LENGTH_SHORT).show();
            if (actionBarDrawerToggle.onOptionsItemSelected(item))
                return true;
            switch (item.getItemId())
            {
                case R.id.menu_about:
                    startActivity(new Intent(getApplicationContext(), AboutActivity.class));
                    return true;
            }
            return super.onOptionsItemSelected(item);
        }

        public void showFragment(Fragment fragment)
        {
            getFragmentManager()
                .beginTransaction()
                .addToBackStack(null)
                .replace(R.id.fragment, fragment)
                .commit();
        }

        public void goBack()
        {
            getFragmentManager().popBackStack();

        }

        @Override
        public boolean onCreateOptionsMenu(Menu menu)
        {
            getMenuInflater().inflate(R.menu.main, menu);
            return true;
        }

        public FolderFragment getFolderFragment()
        {
            Fragment fragment = getFragmentManager().findFragmentById(R.id.fragment);
            if (fragment instanceof FolderFragment)
                return (FolderFragment) fragment;
            else return null;

        }

        public File getCurrentFolder() throws FolderNotOpenException
        {
            FolderFragment folderFragment = getFolderFragment();
            if (folderFragment == null)
                throw new FolderNotOpenException();
            else return folderFragment.currentDir;
        }

        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3)
        {
            switch (arg0.getId())
            {
                case R.id.listNavigation:
                    NavDrawerAdapter.NavDrawerItem item = (NavDrawerAdapter.NavDrawerItem) arg0.getItemAtPosition(arg2);
                    if (item.onClicked(this))
                        drawerLayout.closeDrawers();
                    break;

                case R.id.listClipboard:
                    FolderFragment folderFragment = getFolderFragment();
                    if (folderFragment != null)
                    {
                        // TODO: paste single file
                    }
                    break;

                default:
                    break;
            }
        }

        public File getLastFolder()
        {
            return lastFolder;
        }

        @Override
        public void onClipboardContentsChange(Clipboard clipboard)
        {
            invalidateOptionsMenu();

            ListView clipboardListView = (ListView) findViewById(R.id.listClipboard);

            if (clipboard.isEmpty() && drawerLayout != null)
                drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED, Gravity.END);
            else 
            {
                drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED, Gravity.END);
                FileManagerApplication application = (FileManagerApplication) getApplication();
                if (clipboardListView != null)
                {
                    ClipboardFileAdapter clipboardFileAdapter = new ClipboardFileAdapter(this, clipboard, application.getFileIconResolver());
                    clipboardFileAdapter.setFontApplicator(fontApplicator);
                    clipboardListView.setAdapter(clipboardFileAdapter);
                }
            }
        }

        @Override
        public void onFavouritesChanged(FavouritesManager favouritesManager)
        {
            loadFavourites(favouritesManager);
        }

        @Override
        public boolean onKeyLongPress(int keyCode, KeyEvent event)
        {
            Log.d("Key Long Press", event.toString());
            if (keyCode == KeyEvent.KEYCODE_BACK)
            {
                finish();
                return true;
            }
            else return super.onKeyLongPress(keyCode, event);
        }

    }

以及我想要致电的活动

    package edu.cmu.pocketsphinx.demo;

import static android.widget.Toast.makeText;
import static edu.cmu.pocketsphinx.SpeechRecognizerSetup.defaultSetup;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.evolution.filemanager.about.AboutActivity;
import com.evolution.filemanager.folders.FolderActivity;
import com.evolution.utils.DataClearer;

import edu.cmu.pocketsphinx.Assets;
import edu.cmu.pocketsphinx.Hypothesis;
import edu.cmu.pocketsphinx.RecognitionListener;
import edu.cmu.pocketsphinx.SpeechRecognizer;

public class MainActivity extends Activity implements
        RecognitionListener {

    public AnimationDrawable rocketAnimation;

    private static final String KWS_SEARCH = "wakeup";
    private static final String FORECAST_SEARCH = "forecast";
    private static final String DIGITS_SEARCH = "digits";
    private static final String MENU_SEARCH = "menu";
    private static final String KEYPHRASE = "frost";

    private static final String GO_BACK = "back"; 
    private static final String PREVIOUS = "previous";

    private static final String OPEN_FILE_MANAGER = "open file manager";
    private static final String OPEN_ABOUT = "open about";
    private static final String OPEN_MUSIC = "open music";
    private static final String OPEN_PICTURES = "open pictures";
    private static final String OPEN_VIDEOS = "open videos";
    private static final String SHOW_COMMANDS = "show commands";

    private static final String CLOSE_FILE_MANAGER = "close file manager";
    private static final String CLOSE_ABOUT = "close about";
    private static final String CLOSE_MUSIC = "close music";
    private static final String CLOSE_PICTURES = "close pictures";
    private static final String CLOSE_VIDEOS = "close videos";
    private static final String CLOSE_COMMANDS = "close commands";

    private static final String SHOW_DRAWER = "show drawer";
    private static final String HIDE_DRAWER = "hide drawer";

    public static boolean isOPEN_FILE_MANAGER = false;
    private static boolean isOPEN_ABOUT = false;
    private static boolean isOPEN_MUSIC = false;
    private static boolean isOPEN_PICTURES = false;
    private static boolean isOPEN_VIDEOS = false;
    private static boolean isSHOW_COMMANDS = false;
    private static boolean isSHOW_DRAWER = false;

    private static String MENU_CAPTION;

    private SpeechRecognizer recognizer;
    private HashMap<String, Integer> captions;

    @Override
    public void onCreate(Bundle state) {
        super.onCreate(state);

        // Prepare the data for UI
        captions = new HashMap<String, Integer>();
        captions.put(KWS_SEARCH, R.string.kws_caption);
        captions.put(MENU_SEARCH, R.string.menu_caption);
        captions.put(DIGITS_SEARCH, R.string.digits_caption);
        captions.put(FORECAST_SEARCH, R.string.forecast_caption);

        setContentView(R.layout.main);
        ((TextView) findViewById(R.id.caption_text))
                .setText("Preparing the recognizer");

        ImageView rocketImage = (ImageView) findViewById(R.id.imageViewAnim);
        rocketImage.setBackgroundResource(R.drawable.heart_animation);
        rocketAnimation = (AnimationDrawable) rocketImage.getBackground();

        // Recognizer initialization is a time-consuming and it involves IO,
        // so we execute it in async task

        new AsyncTask<Void, Void, Exception>() {
            @Override
            protected Exception doInBackground(Void... params) {
                try {
                    Assets assets = new Assets(PocketSphinxActivity.this);
                    File assetDir = assets.syncAssets();
                    setupRecognizer(assetDir);
                } catch (IOException e) {
                    return e;
                }
                return null;
            }

            @Override
            protected void onPostExecute(Exception result) {
                if (result != null) {
                    ((TextView) findViewById(R.id.caption_text))
                            .setText("Failed to init recognizer " + result);
                } else {
                    switchSearch(KWS_SEARCH);
                }
            }
        }.execute();
    }

    @Override
    public void onPartialResult(Hypothesis hypothesis) {
        String text = hypothesis.getHypstr();
        TextView tv = ((TextView) findViewById(R.id.caption_text));

        if (text.equals(KEYPHRASE))
        {
            switchSearch(MENU_SEARCH);
            rocketAnimation.start();
        }
        else if (text.equals(OPEN_FILE_MANAGER))
        {
            switchSearch(KWS_SEARCH);
            Intent intent = new Intent (PocketSphinxActivity.this , FolderActivity.class);
            startActivity(intent);
            isOPEN_FILE_MANAGER = true;

        }
        else if (text.equals(CLOSE_FILE_MANAGER))
        {
            if(isOPEN_FILE_MANAGER == true)
            {
                switchSearch(KWS_SEARCH);
                FolderActivity.FOLDERACTIVITY.finish();
                isOPEN_FILE_MANAGER = false;
            }
        }
        else if (text.equals(SHOW_COMMANDS))
        {
            switchSearch(KWS_SEARCH);
            Intent intent = new Intent (PocketSphinxActivity.this , Commands.class);
            startActivity(intent);
            isSHOW_COMMANDS = true;

        }
        else if (text.equals(CLOSE_COMMANDS))
        {
            if(isSHOW_COMMANDS == true)
            {
                switchSearch(KWS_SEARCH);
                Commands.SHOWCOMMANDS.finish();
            }
        }
        else if (text.equals(OPEN_PICTURES))
        {
            switchSearch(KWS_SEARCH);
            Intent intent = new Intent (PocketSphinxActivity.this , AboutActivity.class);
            startActivity(intent);

        }
        else if(text.equals(OPEN_ABOUT))
        {
            switchSearch(KWS_SEARCH);
            Intent intent = new Intent(PocketSphinxActivity.this, AboutActivity.class);
            startActivity(intent);
            isOPEN_ABOUT = true;
        }
        else if(text.equals(CLOSE_ABOUT))
        {
            if (isOPEN_ABOUT == true)
            {
                switchSearch(KWS_SEARCH);
                AboutActivity.ABOUTACTIVITY.finish();
            }
        }

        else if(text.equals(GO_BACK) || text.equals(PREVIOUS))
        {
            if(isOPEN_FILE_MANAGER == true )
            {
                FolderActivity.FOLDERACTIVITY//where i want to call onOptionsItemSelected
                switchSearch(KWS_SEARCH);
            }

        }
        else
        {
            switchSearch(KWS_SEARCH);
            ((TextView) findViewById(R.id.result_text)).setText(text);
        }
    }

    @Override
    public void onResult(Hypothesis hypothesis) {
        ((TextView) findViewById(R.id.result_text)).setText("");
        if (hypothesis != null) {
            String text = hypothesis.getHypstr();
            makeText(getApplicationContext(), text, Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onBeginningOfSpeech() {
    }

    @Override
    public void onEndOfSpeech() {
        if (DIGITS_SEARCH.equals(recognizer.getSearchName())
                || FORECAST_SEARCH.equals(recognizer.getSearchName())
                || OPEN_FILE_MANAGER.equals(recognizer.getSearchName()))
            switchSearch(KWS_SEARCH);
    }

    private void switchSearch(String searchName) {
        recognizer.stop();
        recognizer.startListening(searchName);
        String caption = getResources().getString(captions.get(searchName));
        ((TextView) findViewById(R.id.caption_text)).setText(caption);
    }

    private void setupRecognizer(File assetsDir) {
        File modelsDir = new File(assetsDir, "models");
        recognizer = defaultSetup()
                .setAcousticModel(new File(modelsDir, "hmm/en-us-semi"))
                .setDictionary(new File(modelsDir, "dict/cmu07a.dic"))
                .setRawLogDir(assetsDir).setKeywordThreshold(1e-20f)
                .getRecognizer();
        recognizer.addListener(this);

        // Create keyword-activation search.
        recognizer.addKeyphraseSearch(KWS_SEARCH, KEYPHRASE);
        // Create grammar-based searches.
        File menuGrammar = new File(modelsDir, "grammar/menu.gram");
        recognizer.addGrammarSearch(MENU_SEARCH, menuGrammar);
        File digitsGrammar = new File(modelsDir, "grammar/digits.gram");
        recognizer.addGrammarSearch(DIGITS_SEARCH, digitsGrammar);
        // Create language model search.
        File languageModel = new File(modelsDir, "lm/weather.dmp");
        recognizer.addNgramSearch(FORECAST_SEARCH, languageModel);
    }


    @Override
    protected void onStop(){
       super.onStop();
    }

    //Fires after the OnStop() state
    @Override
    protected void onDestroy() {
       super.onDestroy();
       try {
          trimCache(this); //clear cache to minimize the app size
          DataClearer.getInstance().clearApplicationData();
       } catch (Exception e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
       }
    }

    public static void trimCache(Context context) {
       try {
          File dir = context.getCacheDir();
          if (dir != null && dir.isDirectory()) {
             deleteDir(dir);
          }
       } catch (Exception e) {
          // TODO: handle exception
       }
    }

    public static boolean deleteDir(File dir) {
       if (dir != null && dir.isDirectory()) {
          String[] children = dir.list();
          for (int i = 0; i < children.length; i++) {
             boolean success = deleteDir(new File(dir, children[i]));
             if (!success) {
                return false;
             }
          }
       }

       // The directory is now empty so delete it
       return dir.delete();
    }

}

FolderActivity在MainActivty之上运行,但MainActivity中的语音识别仍处于活动状态,我希望语音本身在FolderActivity中进行一些操作

1 个答案:

答案 0 :(得分:0)

以下是一些建议:

  1. FolderActivity注册BroadcastReceiver作为某个Intent的听众。当MainActivity想要在FolderActivity中执行某项操作时,它可以发送广播IntentBroadcastReceiver中的FolderActivity可以看到广播MainActivity “活动。

  2. 中的适当方法
  3. FolderActivity想要在FolderActivity中执行某项操作时,它可以使用带有标记Intent的{​​{1}}和一些“额外”再次启动Intent.FLAG_ACTIVITY_SINGLE_TOP “这描述了FolderActivity应该做什么。在FolderActivity覆盖onNewIntent()中,读取传递的Intent参数并使用它来确定在FolderActivity. Because the Activity was launched with Intent.FLAG_ACTIVITY_SINGLE_TOP , Android won't create a new instance of the Activity, it will just call onNewIntent()`上调用哪种方法现有的实例。

  4. FolderActivitypublic static类型的Activity变量设置为onCreate()中对自身的引用。然后,MainActivity可以通过执行FolderActivity

  5. 之类的操作来调用FolderActivity.activityReference.doSomething()上的方法

    方法3不是首选方法,因为您需要确保在public static中将null变量设置为FolderActivity.onDestroy()并且还有其他问题(时序问题,内存泄漏)等等,需要妥善处理。

    注意:您可能不想直接致电onOptionsItemSelected()。当用户选择选项时,Android框架会调用此方法。你应该直接调用实际做某事的方法,而不是这个框架回调方法。