关闭应用程序会撤消上一个动作

时间:2018-10-06 08:31:26

标签: android onbackpressed

我有一个闹钟应用程序,当在主活动中使用“后退”按钮时,我刚刚添加了代码以退出程序。但是,当我这样做时,用户执行的最后一个操作将被撤消。例如,如果用户创建了三个警报,然后按后退按钮,则只会显示两个警报。

这是“主要活动”中的“后退”按钮代码:

 @Override
    public void onBackPressed() {
        moveTaskToBack(true);
        android.os.Process.killProcess(android.os.Process.myPid());
        System.exit(1);
    }

以防万一,这是我正在测试的两个活动中的所有代码:

MainActivity.java(故意具有此后退按钮功能的唯一活动)

public class MainActivity extends AppCompatActivity {

    ListView alarmListView;
    ArrayList<Alarm> alarmList = new ArrayList<Alarm>();
    AlarmAdapter alarmAdapter;
    String filename = "alarmList";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

        alarmListView = findViewById(R.id.alarmListView);

        // Credit to Mitch Woodbright for helping with this section, and other try/catch blocks.
        try
        {
            ArrayList<Alarm> alarm = (ArrayList<Alarm>) getIntent().getSerializableExtra("alarmList");
            for(Alarm elements : alarm){
                alarmList.add(elements);
            }
            writeAlarmList(alarmList);
        }
        catch (NullPointerException e){
            System.out.println("AlarmList is empty.");
        }

        try {
            alarmList = readAlarmList();
        }
        catch (NullPointerException e) {

        }

        alarmAdapter = new AlarmAdapter(MainActivity.this, alarmList){
                @Override
                public void onUpdateClick(int position, ArrayList<Alarm> alarmList) {
                    super.onUpdateClick(position, alarmList);
                    Intent updateAlarmIntent = new Intent(MainActivity.this,
                            CreateAlarmActivity.class);
                    updateAlarmIntent.putExtra("alarmList", alarmList);
                    updateAlarmIntent.putExtra("position", position);
                    startActivity(updateAlarmIntent);
                }
            };

      alarmListView.setAdapter(alarmAdapter);
      alarmAdapter.notifyDataSetChanged();

        alarmListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent updateAlarmIntent = new Intent(MainActivity.this, CreateAlarmActivity.class);
                updateAlarmIntent.putExtra("alarmList", alarmList);
                updateAlarmIntent.putExtra("position", position);
                startActivity(updateAlarmIntent);
            }
        });

       // writeAlarmList(alarmList);

    }

    protected void onStart() {
        super.onStart();
        alarmList = readAlarmList();
    }

    protected void onResume() {
        super.onResume();
        alarmList = readAlarmList();
    }

    protected void onPause() {
        super.onPause();
        writeAlarmList(alarmList);
    }

    protected void onStop() {
        super.onStop();
        writeAlarmList(alarmList);
    }

    @Override
    public void onBackPressed() {
        // Thanks to Mitch for this line.
        moveTaskToBack(true);
        android.os.Process.killProcess(android.os.Process.myPid());
        System.exit(1);
    }

    // Create alarm when user presses FAB on activity_main.xml.
    public void createNewAlarm(View view) {
        Intent createAlarmIntent = new Intent(this, CreateAlarmActivity.class);
        createAlarmIntent.putExtra("alarmList", alarmList);
        startActivity(createAlarmIntent);
    }

    public void testAlarmActivated(View view){
        //Intent activateAlarmIntent = new Intent(this, AlarmActivatedActivity.class);
        //startActivity(activateAlarmIntent);
        while(alarmList.size() > 0){
            alarmList.remove(0);
        }
        Intent deleteEverythingIntent = new Intent(MainActivity.this, MainActivity.class);
        deleteEverythingIntent.putExtra("alarmList", alarmList);
        startActivity(deleteEverythingIntent);
    }

    public void writeAlarmList(ArrayList<Alarm> alarmList){
        try {
            FileOutputStream fos = openFileOutput(filename, Context.MODE_PRIVATE);
            ObjectOutputStream oos = new ObjectOutputStream(fos);
            oos.writeObject(alarmList);
            oos.close();
        }
        catch (FileNotFoundException e){
            e.printStackTrace();
        }
        catch (IOException e) {
            e.printStackTrace();
        }

    }

    public ArrayList<Alarm> readAlarmList(){
        try {
            FileInputStream fis = openFileInput(filename);
            ObjectInputStream ois = new ObjectInputStream(fis);
            ArrayList<Alarm> alarmList = (ArrayList<Alarm>) ois.readObject();
            ois.close();
            return alarmList;
        }
        catch (FileNotFoundException e) {
            ArrayList<Alarm> alarmList = new ArrayList<Alarm>();
            System.out.println("File not found. Making empty list.");
            return alarmList;
        }
        catch (IOException e) {
            e.printStackTrace();
        }
        catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        catch (NullPointerException e) {
            ArrayList<Alarm> alarmList = new ArrayList<Alarm>();
            System.out.println("Null pointer exception. Making empty list.");
            return alarmList;
        }
        ArrayList<Alarm> alarmList = new ArrayList<Alarm>();
        return alarmList;
    }

}

CreateAlarmActivity.java(用于创建/更新/删除警报的活动)

public class CreateAlarmActivity extends AppCompatActivity {

    // If the alarm is being created, position = -1.
    int position = -1;
    int alarmHour;
    int alarmMinute;
    boolean isPm;
    int snoozeTimer;
    int[] daysActive;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_create_alarm);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        alarmList = (ArrayList<Alarm>)getIntent().getSerializableExtra("alarmList");

        try {
            // If we're updating an alarm, return the position of the alarm to update.
            position = (int)getIntent().getSerializableExtra("position");
        }
        // Else, keep going.
        catch (NullPointerException e){

        }

        Button hourButton = findViewById(R.id.buttonHours);
        Button minuteButton = findViewById(R.id.buttonMinutes);
        Button isPmButton = findViewById(R.id.buttonAmPm);
        Button snoozeTimerButton = findViewById(R.id.buttonSnoozeTimer);

        Button sundayButton = findViewById(R.id.buttonSunday);
        Button mondayButton = findViewById(R.id.buttonMonday);
        Button tuesdayButton = findViewById(R.id.buttonTuesday);
        Button wednesdayButton = findViewById(R.id.buttonWednesday);
        Button thursdayButton = findViewById(R.id.buttonThursday);
        Button fridayButton = findViewById(R.id.buttonFriday);
        Button saturdayButton = findViewById(R.id.buttonSaturday);

        // If creating a new alarm, initialise data as default.
        if (position == -1){
            alarmHour = 6;
            alarmMinute = 0;
            isPm = false;
            snoozeTimer = 10;
            daysActive = new int[] {0, 0, 0, 0, 0, 0, 0};
        }

        // If updating an alarm, grab the defaults we already had.
        else {
            Alarm tempAlarm = alarmList.get(position);
            alarmHour = tempAlarm.hour;
            alarmMinute = tempAlarm.minute;
            isPm = tempAlarm.isPm;
            snoozeTimer = tempAlarm.snoozeTimer;
            daysActive = tempAlarm.daysActive;
        }

        // Set buttons to what they should be.

        hourButton.setText(Integer.toString(alarmHour));
        snoozeTimerButton.setText(Integer.toString(snoozeTimer));

        if (alarmMinute < 10){
            minuteButton.setText("0" + Integer.toString(alarmMinute));
        }
        else {
            minuteButton.setText(Integer.toString(alarmMinute));
        }

        if (!isPm){
            isPmButton.setText("am");
        }
        else {
            isPmButton.setText("pm");
        }

        setDayColor(sundayButton, daysActive[0]);
        setDayColor(mondayButton, daysActive[1]);
        setDayColor(tuesdayButton, daysActive[2]);
        setDayColor(wednesdayButton, daysActive[3]);
        setDayColor(thursdayButton, daysActive[4]);
        setDayColor(fridayButton, daysActive[5]);
        setDayColor(saturdayButton, daysActive[6]);

    }

    ArrayList<Alarm> alarmList = new ArrayList<Alarm>();

    // Add one to the hour of the alarm.
    public void changeHour(View view) {
        Button btn = findViewById(R.id.buttonHours);

        if (alarmHour == 12){
            alarmHour = 0;
        }
        else {
            alarmHour++;
        }

        btn.setText(Integer.toString(alarmHour));

    }

    // Add one to the minute of the alarm.
    public void changeMinute(View view) {
        Button btn = findViewById(R.id.buttonMinutes);

        if (alarmMinute == 59) {
            alarmMinute = 0;
        }
        else {
            alarmMinute++;
        }

        if (alarmMinute < 10) {
            // Ensure minute 1 becomes 01, e.g, 6:01 am.
            btn.setText("0" + Integer.toString(alarmMinute));
        }
        else {
            btn.setText(Integer.toString(alarmMinute));
        }
    }

    public void changeAmPm(View view) {
        Button btn = findViewById(R.id.buttonAmPm);
        if (isPm == true) {
            isPm = false;
            btn.setText("am");
        }
        else {
            isPm = true;
            btn.setText("pm");
        }
    }

    public void changeSnoozeTimer(View view) {
        Button btn = findViewById(R.id.buttonSnoozeTimer);
        if (snoozeTimer == 15){
            snoozeTimer = 1;
        }
        else {
            snoozeTimer++;
        }
        btn.setText(Integer.toString(snoozeTimer));
    }

    public void finishAlarm(View view){
        EditText alarmName = findViewById(R.id.alarmName);
        String name = alarmName.getText().toString();
        Alarm alarm = new Alarm(name, alarmHour, alarmMinute, isPm, daysActive, snoozeTimer);

        // If we're creating an alarm.
        if (position == -1) {

            try {
                alarmList.add(alarm);
            } catch (Exception e) {

            }
        }

        // Else, we're updating one.
        else {
            try {
                // Set the alarm we're updating to the new alarm.
                alarmList.set(position, alarm);
            } catch (Exception e) {

            }
        }

        Intent finishAlarmIntent = new Intent(this, MainActivity.class);
        finishAlarmIntent.putExtra("alarmList", alarmList);
        startActivity(finishAlarmIntent);
    }


    public void cancelAlarm(View view){
        Intent cancelAlarmIntent = new Intent(this, MainActivity.class);
        cancelAlarmIntent.putExtra("alarmList", alarmList);
        startActivity(cancelAlarmIntent);
    }

    public void deleteAlarm(View view) {

        // If creating a new alarm, deleting is the same as cancelling.
        if (position == -1) {
            Intent cancelAlarmIntent = new Intent(this, MainActivity.class);
            cancelAlarmIntent.putExtra("alarmList", alarmList);
            startActivity(cancelAlarmIntent);
        }
        else {
            // Remove the alarm.
            alarmList.remove(position);

            Intent cancelAlarmIntent = new Intent(this, MainActivity.class);
            cancelAlarmIntent.putExtra("alarmList", alarmList);
            startActivity(cancelAlarmIntent);
        }
    }

    public void changeSunday(View view) {
        Button btn = findViewById(R.id.buttonSunday);
        daysActive[0] = switchDay(daysActive[0]);
        setDayColor(btn, daysActive[0]);
    }

    public void changeMonday(View view) {
        Button btn = findViewById(R.id.buttonMonday);
        daysActive[1] = switchDay(daysActive[1]);
        setDayColor(btn, daysActive[1]);
    }

    public void changeTuesday(View view) {
        Button btn = findViewById(R.id.buttonTuesday);
        daysActive[2] = switchDay(daysActive[2]);
        setDayColor(btn, daysActive[2]);
    }

    public void changeWednesday(View view) {
        Button btn = findViewById(R.id.buttonWednesday);
        daysActive[3] = switchDay(daysActive[3]);
        setDayColor(btn, daysActive[3]);
    }

    public void changeThursday(View view) {
        Button btn = findViewById(R.id.buttonThursday);
        daysActive[4] = switchDay(daysActive[4]);
        setDayColor(btn, daysActive[4]);
    }

    public void changeFriday(View view) {
        Button btn = findViewById(R.id.buttonFriday);
        daysActive[5] = switchDay(daysActive[5]);
        setDayColor(btn, daysActive[5]);
    }

    public void changeSaturday(View view) {
        Button btn = findViewById(R.id.buttonSaturday);
        daysActive[6] = switchDay(daysActive[6]);
        setDayColor(btn, daysActive[6]);
    }

    // Helper method to switch the daysActive from 0 to 1 or from 1 to 0.
    public int switchDay(int day) {
        if (day == 0){
            return 1;
        }
        return 0;
    }
    // Helper method to set the color of a daysActive button when updating the alarm.
    public void setDayColor(Button btn, int day) {

        if (day == 1) {
            // Source: https://stackoverflow.com/questions/2173936/how-to-set-background-color-of-a-view
            // Credit goes to EddieB for the below line.
            btn.getBackground().setColorFilter(Color.parseColor("#00ff00"), PorterDuff.Mode.DARKEN);
        } else {
            // Source: https://stackoverflow.com/questions/14802354/how-to-reset-a-buttons-background-color-to-default
            // Credit goes to Ivo for the below line.
            btn.getBackground().clearColorFilter();

        }
    }

}

1 个答案:

答案 0 :(得分:0)

面向未来的人:

我最终使用以下方法解决了这个问题:

@Override
    public void onBackPressed() {
        this.finishAffinity();
    }

来源:How to quit android application programmatically