【问题标题】:Disable permissions for a certain activity within an app禁用应用内特定活动的权限
【发布时间】:2019-04-02 16:06:01
【问题描述】:

我正在创建一个简单的应用程序。我目前发现的是,当我打开我的应用程序时,.gradle文件夹中已经设置了以下权限:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />

但是,我的应用程序有第二个名为 Gvoice.java 的活动,它依赖于谷歌的语音转文本。

我发现,如果我将上述权限保留在 .gradle 文件夹中,我的主活动窗口可以与 pocketsphinx 完美配合。但是我的 Gvoice 活动给了我一条消息 'Can't open microphone'。

但我发现如果我删除 .gradle 文件夹中的三个权限。我的主要活动不再做我想要它做的事情,但我的第二个活动称为 Gvoice 现在可以正确地将语音转换为文本并且没有给我'Can't open microphone' 消息。

有没有一种简单的方法来解决这个问题,因为我相信它肯定与麦克风权限有关。另请注意,每当我返回主要活动时,都需要设置权限,当我在主要活动之外的另一个活动中时,它需要禁用权限(或者,如果有其他方法可以这样做)。

可以在manifest文件中为不同的activity设置不同的权限吗?

下面我已经更新了到目前为止的内容,请看一下:

public class PocketSphinxActivity extends Activity implements RecognitionListener
{

private static final String KWS_SEARCH = "wakeup";

/* Keyword we are looking for to activate menu */
private static final String KEYPHRASE = "open voice command";   //adjust this keyphrase here and in string!

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

ListView lv;
TextView tv;
EditText a;
Button b;
Button c;

Boolean isDone = false;

@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);
    setContentView(R.layout.main);
    ((TextView) findViewById(R.id.caption_text))
            .setText("Preparing the recognizer");

    lv = (ListView) findViewById(R.id.lvVoiceReturn);
    tv = (TextView) findViewById(R.id.result_text);
    a = (EditText) findViewById(R.id.TFusername);
    b = (Button) findViewById(R.id.bVoice);
    c = (Button)findViewById(R.id.Blogin);

    // 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();
//line added.../////////////////////////
    a.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            if (s.toString().trim().equalsIgnoreCase("open voice command")) {
                //
                //Do your stuff here OR button.performClick()
                //

                //DELAY
                Handler handler = new Handler();
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        if (!isDone) {
                            b.performClick();
                            isDone = true;
                        }
                    }
                }, 500);
            }
        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    });
////////////////////////////////////////
}

@Override
public void onDestroy() {
    super.onDestroy();
    recognizer.cancel();
    recognizer.shutdown();
}

/**
 * In partial result we get quick updates about current hypothesis. In
 * keyword spotting mode we can react here, in other modes we need to wait
 * for final result in onResult.
 */
@Override
public void onPartialResult(Hypothesis hypothesis) {
    if (hypothesis == null)
        return;

    String text = hypothesis.getHypstr();
    //((TextView) findViewById(R.id.result_text)).setText(text);
    ((EditText) findViewById(R.id.TFusername)).setText(text);
}

/**
 * This callback is called when we stop the recognizer.
 */
@Override
public void onResult(Hypothesis hypothesis) {
    //((TextView) findViewById(R.id.result_text)).setText("");
    ((EditText) findViewById(R.id.TFusername)).setText("");
    if (hypothesis != null) {
        String text = hypothesis.getHypstr();
        makeText(getApplicationContext(), text, Toast.LENGTH_SHORT).show();


    //a.setText((String) tv.getText());
        //tv = TextView.getText().toString();
    }
}

@Override
public void onBeginningOfSpeech() {
}

/**
 * We stop recognizer here to get a final result
 */
@Override
public void onEndOfSpeech() {
    if (!recognizer.getSearchName().equals(KWS_SEARCH))
        switchSearch(KWS_SEARCH);
}

private void switchSearch(String searchName) {
    recognizer.stop();

    // If we are not spotting, start listening with timeout (10000 ms or 10 seconds).
    if (searchName.equals(KWS_SEARCH))
        recognizer.startListening(searchName);
    else
        recognizer.startListening(searchName, 10000);

    String caption = getResources().getString(captions.get(searchName));
    ((TextView) findViewById(R.id.caption_text)).setText(caption);
}

private void setupRecognizer(File assetsDir) throws IOException {
    // The recognizer can be configured to perform multiple searches
    // of different kind and switch between them

    recognizer = defaultSetup()
            .setAcousticModel(new File(assetsDir, "en-us-ptm"))
            .setDictionary(new File(assetsDir, "cmudict-en-us.dict"))

                    // To disable logging of raw audio comment out this call (takes a lot of space on the device)
            .setRawLogDir(assetsDir)

                    // Threshold to tune for keyphrase to balance between false alarms and misses
            .setKeywordThreshold(1e-45f)

                    // Use context-independent phonetic search, context-dependent is too slow for mobile
            .setBoolean("-allphone_ci", true)

            .getRecognizer();
    recognizer.addListener(this);

    /** In your application you might not need to add all those searches.
     * They are added here for demonstration. You can leave just one.
     */

    // Create keyword-activation search.
    recognizer.addKeyphraseSearch(KWS_SEARCH, KEYPHRASE);

}

@Override
public void onError(Exception error) {
    ((TextView) findViewById(R.id.caption_text)).setText(error.getMessage());
}

@Override
public void onTimeout() {
    switchSearch(KWS_SEARCH);
}

//Assign button clicks to go to a new activity:
public void onButtonClick_1(View v){
    if (v.getId() == R.id.bVoice){
        String str_1 = a.getText().toString();

        //Go to the relevant page if any part of the phrase or word entered in the 'EditText' field contains 'command' which is not case sensitive
        if (str_1.toLowerCase().contains("command")) {
            Intent userintent = new Intent(PocketSphinxActivity.this, Gvoice.class);

            startActivity(userintent);
        } else {
            Toast.makeText(getApplicationContext(), "Incorrect Information", Toast.LENGTH_SHORT).show();
        }
    }
}

【问题讨论】:

  • 为了使用麦克风,您需要录制音频,这是一项要求。您不能没有该录音权限,如果需要将其发送到云端,那么您还需要互联网。并且根据您运行的 android 版本,它会随着 Andoroid M 更改权限结构而有所不同。如果它在 android M 之前,您根本无法在运行时更改您的权限。还要确保清理您的资源。
  • 听起来您没有在主要活动中释放麦克风资源。您可能想发布相关的源代码。
  • 我已经发布了主要活动的源代码,第二个活动目前只是一个简单的语音到文本活动,顺便说一下我在 Nexus 6p (Android M) 上运行跨度>
  • 对不起,我看到你后来删除了源代码,并认为你已经解决了这个问题......正如我在之前的评论中提到的,你没有释放麦克风资源。即,尝试在onResume() 中初始化语音识别器并在onPause() 中取消/销毁它; onDestroy() 在您的主要活动完全从堆栈中删除之前不会被调用。
  • 使用noHistory 不是一个解决方案,它恰好在大多数情况下都有效。当您的应用不再处于前台时,由于收到来电等原因,您不希望丢失用户体验,而是希望它暂停。正确管理onPause 和onResume 是基本的基本要求,使用noHistory 会暂时为您避免。

标签: android speech-recognition voice-recognition speech


【解决方案1】:

在我的评论中我说:

使用noHistory 不是一个解决方案,它恰好在大多数情况下都有效。当您的应用不再处于前台时,由于接到来电等原因,您不希望失去用户体验,而是希望它暂停。正确管理 onPause 和 onResume 是基本的基本要求,使用noHistory 将暂时避免您。

这是一个示例,说明在您的应用暂停并随后恢复时如何管理 recognizer 对象。

@Override
protected void onResume() {
    super.onResume();

    if (recognizer == null) {
        // Set up recognizer again
    }
}

@Override
protected void onPause() {
    super.onPause();

    if (recognizer != null) {
        recognizer.cancel();
        recognizer.shutdown();
        recognizer = null;
    }
}

虽然每次暂停都会销毁您的应用,但会解决释放麦克风和识别器资源的解决方案,但这不是您想要做的 - 您希望优雅地管理您的生命周期应用程序进入后台并再次进入前台,而您所持有的资源(例如麦克风)不会导致其他应用程序出现问题。

【讨论】:

  • 我同意,我的回答部分正确,但是,是的,我完全理解您的意思,因此即使在我的应用程序上按下后退按钮,我现在也可以看到完整的操作历史记录,而不是破坏以前做过的事情
  • 酷。我添加了一个缺失的行,其中 recognizer 应该在 onPause() 中设置为 null
  • 嘿@brandall 有没有机会请您帮我解决另一个问题,这会导致您帮助我解决上述问题? stackoverflow.com/questions/43177064/…
【解决方案2】:

我想出了另一种方法是将以下内容添加到我的清单文件android:noHistory="true" 这似乎清除了主要活动堆栈的历史记录,现在 onClickListener 正在第二个活动中工作。

另一种方法是将以下内容放在我的 MainActivity 文件的底部,这是@brandall 建议的onPause 方法:

@Override
protected void onPause() {
super.onPause();
finish();
}

【讨论】:

  • 我目前使用这种方法看到的唯一问题是它不会让我回到主要活动,人们还有其他选择吗,因为我确实需要回到主要活动不时使用按钮按下等?
  • 这不是我在评论中的意思。我会添加一个答案。
猜你喜欢
  • 1970-01-01
  • 2021-02-16
  • 2021-04-20
  • 2019-02-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-28
  • 1970-01-01
相关资源
最近更新 更多