org.interactiverobotics.headset_launcher.LauncherService.java Source code

Java tutorial

Introduction

Here is the source code for org.interactiverobotics.headset_launcher.LauncherService.java

Source

/*
 * LauncherService.java
 *
 * Copyright (C) 2015,2016  Pavel Prokhorov (pavelvpster@gmail.com)
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */
package org.interactiverobotics.headset_launcher;

import android.app.KeyguardManager;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.os.Handler;
import android.os.IBinder;
import android.os.PowerManager;
import android.support.annotation.Nullable;
import android.support.v4.app.NotificationCompat;
import android.util.Log;

/**
 *  ? ? (? ??).
 *
 * @author pavelvpster
 *
 */
public final class LauncherService extends Service {

    /**
     *  ? ? logcat  ? ??.
     *
     */
    private static final String TAG = "launcher_service";

    /**
     * ?  .
     *
     */
    public LauncherService() {
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {

        return null;
    }

    @Override
    public void onCreate() {

        super.onCreate();

        Log.d(TAG, "Create");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        Log.d(TAG, "Launch application (intent).");

        final SharedPreferences preferences = getSharedPreferences(Constants.PREFERENCES_NAME, 0);

        final int multiclickTimeout = preferences.getInt(Constants.MULTICLICK_TIMEOUT, 1);

        //    ? ,  ? ? 
        //   ;    ? 

        if (mClickCount == 0) {

            mClickHandler.postDelayed(mClickRunnable, (multiclickTimeout + 1) * 1000);
        }

        mClickCount++;

        return START_STICKY;
    }

    @Override
    public void onDestroy() {

        super.onDestroy();

        Log.d(TAG, "Destroy");
    }

    /**
     *  .
     *
     */
    private int mClickCount = 0;

    /**
     *   ??? ? ? .
     *
     */
    private final Handler mClickHandler = new Handler();

    /**
     *    .
     *
     */
    private Runnable mClickRunnable = new Runnable() {

        @Override
        public void run() {

            launch();

            mClickCount = 0;
        }

    };

    /**
     *   ?   ? ?,   ??.
     *
     */
    private void launch() {

        Log.d(TAG, "Click count: " + mClickCount);

        final String actionParameterName, appParameterName;

        switch (mClickCount) {

        case 1:

            actionParameterName = Constants.ACTION;

            appParameterName = Constants.APPLICATION;

            break;

        case 2:

            actionParameterName = Constants.ACTION_2;

            appParameterName = Constants.APPLICATION_2;

            break;

        case 3:

            actionParameterName = Constants.ACTION_3;

            appParameterName = Constants.APPLICATION_3;

            break;

        default:

            Log.e(TAG, "Unsupported click count: " + mClickCount);

            return;
        }

        final SharedPreferences preferences = getSharedPreferences(Constants.PREFERENCES_NAME, 0);

        final String action = preferences.getString(actionParameterName, null);

        if (action == null) {

            return;
        }

        final String app = preferences.getString(appParameterName, null);

        if (action.equals(Constants.ACTION_LAUNCH) && app == null) {

            return;
        }

        //  ?, ? ?   ??

        if (preferences.getBoolean(Constants.UNLOCK_SCREEN, false)) {

            unlockScreen();
        }

        //  , ? ?   ??

        if (preferences.getBoolean(Constants.SHOW_NOTIFICATION, false)) {

            String t = "";

            if (action.equals(Constants.ACTION_LAUNCH)) {

                t = app;

            } else {

                final String[] actionNames = getResources().getStringArray(R.array.array_action_names);

                final String[] actions = getResources().getStringArray(R.array.array_actions);

                for (int i = 0; i < actions.length; i++) {

                    if (action.equals(actions[i])) {

                        t = actionNames[i];

                        break;
                    }
                }
            }

            showNotification(t);
        }

        // ? ?

        if (action.equals(Constants.ACTION_LAUNCH)) {

            // ? 

            startActivity(getPackageManager().getLaunchIntentForPackage(app));

        } else {

            // ? ?? ?

            final Intent intent = new Intent(action);

            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

            startActivity(intent);
        }
    }

    /**
     *  .
     *
     */
    @SuppressWarnings("deprecation")
    private KeyguardManager.KeyguardLock mKeyguardLock = null;

    /**
     *  ?.
     *
     */
    private PowerManager.WakeLock mWakeLock = null;

    /**
     *    ?.
     *
     */
    @SuppressWarnings("deprecation")
    private void unlockScreen() {

        final KeyguardManager keyguardManager = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE);

        mKeyguardLock = keyguardManager.newKeyguardLock("HeadsetLauncherLock");

        mKeyguardLock.disableKeyguard();

        final PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);

        mWakeLock = powerManager.newWakeLock(
                PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP | PowerManager.ON_AFTER_RELEASE,
                "HeadsetLauncherWakeLock");

        mWakeLock.acquire();

        // ?  ?  ?

        mTimeoutHandler.postDelayed(mTimeoutRunnable, Constants.NOTIFICATION_TIMEOUT * 1000);
    }

    /**
     *      ? ?.
     *
     * @param app  (package name).
     *
     */
    private void showNotification(String app) {

        //  ? ?

        CharSequence name;

        try {

            final ApplicationInfo appInfo = (ApplicationInfo) getPackageManager().getApplicationInfo(app, 0);

            name = getPackageManager().getApplicationLabel(appInfo);

        } catch (PackageManager.NameNotFoundException e) {

            // ? ?   ?, ? 

            name = getString(R.string.text_notification_title);
        }

        //  

        final NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
                .setSmallIcon(R.mipmap.headset_launcher_notification).setContentTitle(name)
                .setContentText(getString(R.string.text_notification_text)).setAutoCancel(true);

        final NotificationManager notificationManager = (NotificationManager) getSystemService(
                Context.NOTIFICATION_SERVICE);

        notificationManager.notify(1, builder.build());

        // ?  ?  ?

        mTimeoutHandler.postDelayed(mTimeoutRunnable, Constants.NOTIFICATION_TIMEOUT * 1000);
    }

    /**
     *   ?   .
     *
     */
    private void cancelNotificationAndLocks() {

        // ? 

        final NotificationManager notificationManager = (NotificationManager) getSystemService(
                Context.NOTIFICATION_SERVICE);

        notificationManager.cancel(1);

        // ?  ?

        if (mWakeLock != null) {

            mWakeLock.release();

            mWakeLock = null;
        }

        if (mKeyguardLock != null) {

            mKeyguardLock.reenableKeyguard();

            mKeyguardLock = null;
        }

        //    ?

        stopSelf();
    }

    /**
     *   ??? ?   ?  .
     *
     */
    private final Handler mTimeoutHandler = new Handler();

    /**
     *   ?   ?  .
     *
     */
    private Runnable mTimeoutRunnable = new Runnable() {

        @Override
        public void run() {

            cancelNotificationAndLocks();
        }
    };

}