Java Android:Intent重新启动活动,而不是指向主活动

Java Android:Intent重新启动活动,而不是指向主活动,java,android,android-studio,Java,Android,Android Studio,在我的应用程序中,我们有一个EnterPin活动,它将pin保存在SharedReference中,并将其与您输入的内容进行比较。如果它是正确的,则意图会将您带到MainActivity,并传递一个键为“verified”的真布尔值 出于某种原因,在emulator和my s7上,输入正确的pin(通过调试确认)后,它只是重新启动EnterPinActivity 最恼人的是它有时有效,有时无效。我不明白是什么导致了这个问题 EnterPin.java public class EnterPin

在我的应用程序中,我们有一个EnterPin活动,它将pin保存在SharedReference中,并将其与您输入的内容进行比较。如果它是正确的,则意图会将您带到MainActivity,并传递一个键为“verified”的真布尔值

出于某种原因,在emulator和my s7上,输入正确的pin(通过调试确认)后,它只是重新启动EnterPinActivity

最恼人的是它有时有效,有时无效。我不明白是什么导致了这个问题

EnterPin.java

public class EnterPin extends AppCompatActivity {
//Used to check if there is a pin
SharedPreferences preferences;

//Title of the private file for the pin
public final String PINFILE = "PinFile";

private int pin;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_enter_pin);

    pin = getPinFromFile();

    //TODO::add similar check for security questions in case they exit the app during creation
    //If the user did not create a pin, send to create one and end this activity
    if(pin == -1) {
        forceCreatePin();
        finish();
    }

    Button logBtn = (Button)findViewById(R.id.logBtn);
    Button forgotBtn = (Button)findViewById(R.id.forgotPin);
}

public void onClick(View v){
    if(v.getId() == R.id.logBtn){
        EditText pinIn = (EditText) findViewById(R.id.enterPin);
        String pinStr = pinIn.getText().toString();
        if (pinStr.length() == 4) {
            int pinInt = Integer.parseInt(pinStr);
            if (pin == pinInt) {
                //Login
                Intent intent = new Intent(getApplicationContext(), MainActivity.class);
                intent.putExtra("verified", true);
                startActivity(intent);
                finish();
            } else {
                //clear input and notify user of wrong pin
                pinIn.setText("");
                Toast toast = Toast.makeText(getApplicationContext(), "Incorrect PIN", Toast.LENGTH_SHORT);
                toast.show();
            }
        } else {
            pinIn.setText("");
            Toast toast = Toast.makeText(getApplicationContext(), "PIN must be 4 characters", Toast.LENGTH_SHORT);
            toast.show();
        }
    }else if(v.getId() == R.id.forgotPin){
        Intent intent = new Intent(getApplicationContext(), ForgotPIN.class);
        startActivity(intent);
        finish();
    }

}

private int getPinFromFile() {
    preferences = getSharedPreferences(PINFILE, MODE_PRIVATE);
    //Returns value at key "pin" if it exists, -1 if pin is not created
    return preferences.getInt(PINFILE, -1);
}

private void forceCreatePin() {
    Intent intent = new Intent(this, CreatePin.class);
    startActivity(intent);
}
}
MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    //get verified key from intent activity was started with, set false if key not found
    isVerified = getIntent().getBooleanExtra("verified", false);
    if (!isVerified) {
        forceEnterPin();
    }

 //We create the db in the main class
 try {
     db = this.openOrCreateDatabase("budgetDB", MODE_PRIVATE, null);
     System.out.println("Succes!!!!!!!");

 }
 catch(Exception e)
 {
     System.out.println("It got caught....");
     Log.e("BudgetDatabase ERROR", "Error Creating/Loading database");
 }
    Database budDB = new Database(db);
    budDB.createTables();


    //Loading variables, settings the first fragment to the home screen
    spendableInc = loadSpendableInc();
    FragmentTransaction trans = getFragmentManager().beginTransaction();
    HomeFragment homeFragment = new HomeFragment();
    trans.add(R.id.frag_container, homeFragment, "home").commit();


    //Settings functionality for the bottom navigation bar
    final FrameLayout frameLayout = (FrameLayout) findViewById(R.id.frag_container);
    BottomNavigationView bottomNavigationView = (BottomNavigationView) findViewById(R.id.bottom_navigation);
    bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
        FragmentManager manager = getFragmentManager();
        final FragmentTransaction transaction = manager.beginTransaction();
        //Handling clicks on home, transaction, or overview
        switch (item.getItemId()) {
            case R.id.action_home:
                HomeFragment homeFragment = new HomeFragment();
                transaction.replace(R.id.frag_container, homeFragment, "home").commit();
                break;
            case R.id.action_transactions:
                TransactionFragment transactionFragment = new TransactionFragment();
                transaction.replace(R.id.frag_container, transactionFragment, "transaction").commit();
                break;
            case R.id.action_overview:
                OverviewFragment overviewFragment = new OverviewFragment();
                transaction.replace(R.id.frag_container, overviewFragment, "overview").commit();
                break;
        }
        return false;
    }
});

}

/**
 * Auto-generated method for toolbar
 * @param menu
 * @return
 */
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

/**
 * Auto-generated method for toolbar
 * @param item
 * @return
 */
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    } else if (id == R.id.logout) {
        forceEnterPin();
        return true;
    }

    return super.onOptionsItemSelected(item);
}


public void saveSpendableInc(float amt) {
    SharedPreferences.Editor editor = getSharedPreferences(SPENDABLE_INCOME, MODE_PRIVATE).edit();
    editor.putFloat(SPENDABLE_INCOME, amt);
    editor.commit();
}

public float loadSpendableInc() {
    SharedPreferences prefs = getSharedPreferences(SPENDABLE_INCOME, MODE_PRIVATE);
    return prefs.getFloat(SPENDABLE_INCOME, MODE_PRIVATE);
}

public void createIncome(View view) {
    Intent intent = new Intent(this, CreateIncome.class);
    intent.putExtra(SPENDABLE_INCOME, spendableInc);
    startActivity(intent);
}

public void createExpense(View view) {
    Intent intent = new Intent(this, CreateExpense.class);
    intent.putExtra(SPENDABLE_INCOME, spendableInc);
    startActivity(intent);
}

/**
 * Closes the database when the application is terminated
 * Set verified to false to force
 */
@Override
protected void onDestroy(){
    super.onDestroy();
    db.close();
    getIntent().putExtra("verified", false);
    idleStart = 0;
    idleFinish = 0;
}

//Forces user to create pin and ends the main activity so the user can't use the back button to get to home screen
private void forceEnterPin() {
    getIntent().putExtra("verified", false);
    Intent intent = new Intent(this, EnterPin.class);
    startActivity(intent);
    //finish();
}

@Override
protected void onPause(){
    super.onPause();
    Calendar tmpCalendar = Calendar.getInstance();
    idleStart = tmpCalendar.get(Calendar.MINUTE);
}

@Override
protected void onStop(){
    super.onStop();
    Calendar tmpCalendar = Calendar.getInstance();

    //If app went straight to stop phase, start at 0
    //If app started at pause and then went to stop, add time from before
    if(idleStart == 0)
        idleStart = tmpCalendar.get(Calendar.MINUTE);
    else
        idleStart += tmpCalendar.get(Calendar.MINUTE);
}

@Override
protected void onResume(){
    super.onResume();
    //Use calendar object to get the current time in minutes
    Calendar tmpCalendar = Calendar.getInstance();
    idleFinish = tmpCalendar.get(Calendar.MINUTE);
    if(idleFinish - idleStart >= 30)
        forceEnterPin();

    //Reset idle times because user started app again
    idleStart = 0;
    idleFinish = 0;
}
}

答:请先阅读您使用的API,然后再让它为您启动活动

在forceEnterPin()中,为什么要注释掉finish?我想您在验证意图时遇到了一些问题。尝试在启动另一个活动后完成MainActivity…它最初没有注释,只是用于测试。这两个版本都出现了错误,我昨天还没有看到,但是现在:在OnDestroy()中,您被放入了已验证的意图,删除这个。如果完成活动,通常会调用onDestroy()。它不能保证像api中规定的那样被调用。我想这就是问题所在,为什么它有时有效,有时无效。我已经弄明白了——我觉得自己真的很笨。我添加了一个功能,可以在30分钟后为您计时,但我使用的日历API给出了实际的一小时分钟数,而不是时间戳。因此,在任何一个小时的30分钟之后,你都无法使用该应用程序。叹气