You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何根据Microsoft Cognitive API结果自动跳转Android Activity

实现情绪识别后的自动页面跳转

你只需要在GetEmotionCall的onPostExecute方法中,拿到识别出的情绪结果后添加判断逻辑,就能实现自动跳转。具体修改如下:

核心修改代码

找到onPostExecute方法,在获取到emotion值后,添加条件判断并启动对应Activity:

@Override
protected void onPostExecute(String result) {
    JSONArray jsonArray = null;
    try {
        jsonArray = new JSONArray(result);
        String emotions = "";

        for(int i = 0;i<jsonArray.length();i++) {
            JSONObject jsonParentObject = new JSONObject(jsonArray.get(i).toString());
            JSONObject jsonObject = jsonParentObject.getJSONObject("faceAttributes");
            JSONObject scores = jsonObject.getJSONObject("emotion");

            double max = 0;
            String emotion = "";
            for (int j = 0; j < scores.names().length(); j++) {
                if (scores.getDouble(scores.names().getString(j)) > max) {
                    max = scores.getDouble(scores.names().getString(j));
                    emotion = scores.names().getString(j);
                }
            }
            emotions += emotion + "\n";
            
            // 新增:判断情绪并跳转页面
            if ("neutral".equals(emotion)) {
                Intent intent = new Intent(MainActivity.this, BodyActivity.class);
                startActivity(intent);
            } else if ("happiness".equals(emotion)) {
                Intent intent = new Intent(MainActivity.this, MindActivity.class);
                startActivity(intent);
            }
        }
        resultText.setText(emotions);

    } catch (JSONException e) {
        resultText.setText("No emotion detected. Try again later");
    }
}

注意事项

  • 如果图片中识别到多个人脸,上面的代码会对每个人脸的情绪都做判断并跳转。如果只需要处理第一个人脸的情绪,可以在判断后添加break;跳出循环。
  • 确保BodyActivity和MindActivity已经在AndroidManifest.xml中注册,示例注册代码:
<activity android:name=".BodyActivity"/>
<activity android:name=".MindActivity"/>
  • 你的订阅密钥已经在代码中暴露,建议不要把密钥硬编码在代码里,后续可以移到本地配置文件中,避免泄露。

内容的提问来源于stack exchange,提问作者Gigi0425

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 06:31:11