java - 设备旋转后如何防止 Intent 重置?

标签 java android android-intent gyroscope

我的 Android 应用程序有一个主要的 Intent 供用户登录。之后,它会加载另一个带有箭头按钮、一些标签、一个进度条和一些输入的 Intent当用户单击按钮转到另一个问题(研究表格)时交替显示的组件。对于每个问题,标签都会发生变化,一些组件会隐藏,而另一些组件会出现。但是如果用户旋转设备,Intent 类型会重置,因为它会返回到第一个问题。

第二个 Intent 的代码是:

    public void onClick(View v) 
    {
        if ((!selectedFormCode.equalsIgnoreCase("")) && (!userCode.getText().toString().equals("")))
        {
            Intent questionScreen = new Intent();
            questionScreen.setClassName("com.android.artemis", "com.android.artemis.QuestionScreen");

            func.ShowMessage("Aguarde,\nCarregando o Formulário...");

            // envia as configurações para a tela de entrevista
            questionScreen.putExtra("formProperties", formProperties.toString()); 
            questionScreen.putExtra("selectedFormCode", selectedFormCode);
            questionScreen.putExtra("selectedRegionCode", selectedRegionCode);
            questionScreen.putExtra("selectedSubRegionCode", selectedSubRegionCode);
            questionScreen.putExtra("selectedRegionLabel", selectedRegionLabel);
            questionScreen.putExtra("selectedSubRegionLabel", selectedSubRegionLabel);
            questionScreen.putExtra("userRegistrationCode", userCode.getText().toString());

            startForm.setEnabled(false); // evita que o usuário clique mais de uma vez

            startActivity(questionScreen);

            startForm.setEnabled(true);
        }
        else
        {
            func.ShowMessage("Complete todas as Informações antes de Continuar!");
        }
    }

第二个 Intent 加载时触发的代码是:

        super.onAttachedToWindow();
        try {
            // recebe informações vindas da tela inicial
            selectedFormCode = getIntent().getStringExtra("selectedFormCode");
            selectedRegionCode = getIntent().getStringExtra("selectedRegionCode");
            selectedSubRegionCode = getIntent().getStringExtra("selectedSubRegionCode");
            selectedRegionLabel = getIntent().getStringExtra("selectedRegionLabel");
            selectedSubRegionLabel = getIntent().getStringExtra("selectedSubRegionLabel");
            userRegistrationCode =  getIntent().getStringExtra("userRegistrationCode");
            formProperties = new JSONObject(getIntent().getStringExtra("formProperties"));
            //ArrayList<JSONObject> formList;
            //JSONObject mainData = new JSONObject(func.getTextAssetFile("forms.dat"));
            //formList = func.getJSONArrayList(mainData.get("forms").toString()); 
            //formProperties = formList.get(func.getIndexFromObject(formList, selectedFormCode));

            // inicializa a tela
            formLabel.setText(formProperties.get("l").toString()); // label         
            customEdit.clearFocus();
            // inicializa variáveis a serem usadas na entrevista
            totalQuestion = (Integer) formProperties.get("total");
            questionAnswer = new String[totalQuestion];
            subQuestionAnswer = new String[totalQuestion];
            questionsData = formProperties.getJSONArray("questions");
            // recupera a informação de quantidade de entrevistas feitas deste formulário, por este entrevistador
            SharedPreferences settings = getSharedPreferences(selectedFormCode, 0);
            totalInterview = settings.getInt(userRegistrationCode, 0);
            // inicia uma nova entrevista depois que configura a tela
            startNewInterview();
/*          
            // Inicialização de uma sessão do dropbox para sincronização de arquivos de entrevistas
            AppKeyPair appKeys = new AppKeyPair(APP_KEY, APP_SECRET);
            AndroidAuthSession session = new AndroidAuthSession(appKeys, ACCESS_TYPE);
            mDBApi = new DropboxAPI<AndroidAuthSession>(session);
            //
            SharedPreferences dbas = getSharedPreferences("SPM", 0);
            AccessTokenPair access = new AccessTokenPair(dbas.getString("dropboxKey", ""),dbas.getString("dropboxSecret", "")); 
            mDBApi.getSession().setAccessTokenPair(access);
            mDBApi.getSession().startAuthentication(this);
*/          
        } 
        catch (JSONException e) 
        {
            e.printStackTrace();
            func.ShowMessage("Não foi possível decodificar as propriedades do formulário de pesquisa. \nErro Fatal! \nLibere mais Memória!!");
        }

    }

public void startNewInterview() // inicializa uma nova entrevista
{
    // reinicia a barra de progresso
    currentQuestion = 1;
    progressBar.setMax(totalQuestion);
    progressBar.setProgress(currentQuestion);
    // limpar as variáveis de respostas
    for (int i = 0; i < totalQuestion; i++)
    {
        questionAnswer[i] = "";
        subQuestionAnswer[i] = "";
    }
    // inicializar o relógio
    func.startChronometer();
    startTime = func.getChronometerTime(); 
    // determinat o momento do início da entrevista
    Date now = new Date();;  
    SimpleDateFormat formatTime = new SimpleDateFormat(dateMask);  
    interviewDate = formatTime.format(now);  
    formatTime = new SimpleDateFormat(hourMask);  
    interviewHour = formatTime.format(now);  
    // ir para a primeira questão
    goQuestion(currentQuestion);
}

最佳答案

将此添加到您的 Manifest

<activity
        android:name="MyActivity"
        android:configChanges="orientation|keyboard|keyboardHidden"
        android:screenOrientation="sensor" />

关于java - 设备旋转后如何防止 Intent 重置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20583842/

相关文章:

当输入负数时,Java 找到最小的数字会出现困惑

java - Java 中的 Character.getNumericValue(..) 为大小写字符返回相同的数字

java - 多线程环境下HashMap的使用,定时更新

android - 可以在手机上观看所有 Intents/Broadcasts

安卓相机 : when capturing image data intent returns null

java - 没有在 Java 中定义标签的 SAX 解析器

android - 如何在 Android 中使用接口(interface)名称执行 ping 命令(例如 : wlan0)?

java - 如何在android中检查设备是否设置了密码?

javascript - 在 react-native 中调用 Appregistry.runApplication 时出错

android - 来自 MediaDocumentsProvider 的权限拒绝