pl.zajecia.cw3.MainActivity.java Source code

Java tutorial

Introduction

Here is the source code for pl.zajecia.cw3.MainActivity.java

Source

/*
 * Copyright (C) 2012 ukasz Wasylkowski
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at 
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software 
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and 
 * limitations under the License.
 */

package pl.zajecia.cw3;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.AlertDialog;
import android.app.ActivityManager.RunningServiceInfo;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.Toast;
import android.widget.ToggleButton;

public class MainActivity extends Activity {

    @SuppressWarnings("unused")
    private static final String TAG = "SettingsFragment";

    /** Public static final fields used in messages */
    public static final String DEFAULT_INTERVAL = "30";
    public static final String PREFERENCES = "WallpaperChangerPreferences";
    public static final String FILE_PATHS = "FilePaths";
    public static final String ACTIVATE_ON_BOOT = "activateOnBoot";
    public static final int INTERVAL_SECONDS = 0;
    public static final int INTERVAL_MINUTES = 1;
    public static final int INTERVAL_HOURS = 2;
    public static final int INTERVAL_DAYS = 3;

    /** View elements */
    private EditText mIntervalEditText;
    private CheckBox mRandomOrderCheckBox;
    private CheckBox mChangeDuringSleepCheckBox;
    private CheckBox mChangeOnScreenOnCheckBox;
    private CheckBox mDisableOnBatteryLowCheckBox;
    private Spinner mIntervalSpinner;
    private ToggleButton mActivatedButton;
    private Button mEditPhotosButton;
    private Button mSaveSettingsButton;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.settings_layout);

        mIntervalEditText = (EditText) findViewById(R.id.intervalEditText);
        mIntervalSpinner = (Spinner) findViewById(R.id.intervalSpinner);

        /** 
         * On focus change listener to hide keyboard when focus left editText
         */
        ((LinearLayout) findViewById(R.id.mainLinearLayout)).setOnFocusChangeListener(new OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean arg) {
                InputMethodManager imm = (InputMethodManager) view.getContext()
                        .getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
            }
        });

        mRandomOrderCheckBox = (CheckBox) findViewById(R.id.randomOrderCheckBox);
        mChangeDuringSleepCheckBox = (CheckBox) findViewById(R.id.changeDuringSleepCheckBox);
        mChangeOnScreenOnCheckBox = (CheckBox) findViewById(R.id.changeOnScreenOnCheckBox);
        mDisableOnBatteryLowCheckBox = (CheckBox) findViewById(R.id.dontChangeOnBatteryLowCheckBox);

        mEditPhotosButton = (Button) findViewById(R.id.viewGalleryButton);
        mSaveSettingsButton = (Button) findViewById(R.id.saveSettingsButton);
        mActivatedButton = (ToggleButton) findViewById(R.id.activateButton);

        //Listeners:      
        mSaveSettingsButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                saveSettings();
                Toast.makeText(getApplicationContext(), R.string.settings_saved, Toast.LENGTH_SHORT).show();
            }
        });

        mActivatedButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                ToggleButton button = (ToggleButton) v;
                if (button.isChecked()) {
                    button.setChecked(runService());
                } else {
                    cancelService();
                }
            }
        });

        mEditPhotosButton.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getApplication(), PhotosActivity.class);
                startActivity(intent);
            }
        });
    }

    @Override
    protected void onStart() {
        mActivatedButton.setChecked(isServiceStarted());
        loadSettings();

        super.onStart();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.activity_main, menu);
        return true;
    }

    @Override
    public boolean onMenuItemSelected(int featureId, MenuItem item) {
        switch (item.getItemId()) {
        case R.id.kill_app_menu_button:
            AlertDialog.Builder builder = new Builder(this);
            builder.setMessage(R.string.confirm_terminate).setTitle(R.string.title_close)
                    .setPositiveButton(R.string.yes_close, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            cancelService();
                            moveTaskToBack(true);
                        }
                    }).setNegativeButton(R.string.no_close, new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                        }
                    }).show();
            break;
        case R.id.open_gallery_menu_button:
            Intent intent = new Intent(getApplication(), PhotosActivity.class);
            startActivity(intent);
        default:
            break;
        }
        return super.onMenuItemSelected(featureId, item);
    }

    /**
     * Checks if main service is already started.
     * Necessary in order not to mess with intervals 
     * (e.g register more than one broadcasts)
     */
    private boolean isServiceStarted() {
        ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
            if (MainService.class.getName().equals(service.service.getClassName())) {
                return true;
            }
        }
        return false;
    }

    /**
     * Starts main service. App will appear in background.
     * If service is started (and only then), wallpapers will be changed 
     */
    private boolean runService() {
        if (!isServiceStarted()) {
            SharedPreferences settings = getSharedPreferences(PREFERENCES, 0);
            if (settings.getString(FILE_PATHS, "").isEmpty()) {
                Toast.makeText(this, R.string.no_photos_selected, Toast.LENGTH_SHORT).show();
                return false;
            }
            startService(new Intent(this, MainService.class));
            return true;
        }
        return true;
    }

    @Override
    protected void onStop() {
        saveSettings();
        super.onStop();
    }

    /**
     * Cancels main service. App will no longer appear in background.
     */
    private void cancelService() {
        if (isServiceStarted()) {
            stopService(new Intent(this, MainService.class));
        }
    }

    /**
     * Saves settings to shared preferences.
     */
    private void saveSettings() {
        SharedPreferences settings = getSharedPreferences(PREFERENCES, 0);
        SharedPreferences.Editor editor = settings.edit();

        editor.putInt("intervalValue", getInterval());
        editor.putInt("intervalType", getIntervalType());
        editor.putBoolean("randomOrder", mRandomOrderCheckBox.isChecked());
        editor.putBoolean("changeDuringSleep", mChangeDuringSleepCheckBox.isChecked());
        editor.putBoolean("changeOnScreenOn", mChangeOnScreenOnCheckBox.isChecked());
        editor.putBoolean("changeOnBatteryLow", mDisableOnBatteryLowCheckBox.isChecked());

        editor.commit();

        //Send broadcast for service to continue work using new settings
        Intent intent = new Intent(MainService.MESSAGE_UPDATE_SETTINGS);
        LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
    }

    /**
     * Loads settings from preferences to set controls.
     */
    private void loadSettings() {
        SharedPreferences settings = getSharedPreferences(PREFERENCES, 0);

        if (settings == null) {
            return;
        }

        mRandomOrderCheckBox.setChecked(settings.getBoolean("randomOrder", true));
        mChangeDuringSleepCheckBox.setChecked(settings.getBoolean("changeDuringSleep", false));
        mChangeOnScreenOnCheckBox.setChecked(settings.getBoolean("changeOnScreenOn", true));
        mDisableOnBatteryLowCheckBox.setChecked(settings.getBoolean("changeOnBatteryLow", false));
        mIntervalEditText
                .setText(String.valueOf(settings.getInt("intervalValue", Integer.parseInt(DEFAULT_INTERVAL))));
        mIntervalSpinner.setSelection(settings.getInt("intervalType", 1));
    }

    /**
     * Returns interval parsed ass integer
     */
    private int getInterval() {
        try {
            int val = Integer.parseInt(mIntervalEditText.getText().toString());
            if (val < 1) {
                Toast.makeText(this, R.string.wrong_interval, Toast.LENGTH_SHORT);
                mIntervalEditText.setText("30");
                return 30;
            }
            return val;
        } catch (NumberFormatException ex) {
            Toast.makeText(this, R.string.interval_not_number, Toast.LENGTH_SHORT).show();
            return Integer.parseInt(DEFAULT_INTERVAL);
        }
    }

    private int getIntervalType() {
        return mIntervalSpinner.getSelectedItemPosition();
    }
}