[:ru]Защита андроид-приложения с помощью пинкода[:en]App lock library for Android[:]

[:ru]В этом видеоуроке реализуем блокировку приложения с помощью библиотеки AppLocker.  Исходный код – ниже, под видео.

Для импорта библиотеки в проект добавьте строки в файл сборки build.gradle (Module: app):

allprojects {
    repositories {
        maven { url "https://jitpack.io" }
    }
}

dependencies {
    compile 'com.github.balrampandey19:AppLocker:1.0.1'
}

Также понадобятся такие строковые ресурсы в файле res/values/strings.xml:

<resources>
    <string name="app_name">AppLock</string>

    <string name="manage_passcode">Manage Pin</string>
    <string name="enter_passcode">Enter Pin</string>
    <string name="enter_old_passcode">Enter old Pin</string>
    <string name="reenter_passcode">Re-enter Pin</string>
    <string name="change_passcode">Change Pin</string>
    <string name="setup_passcode">Setup pin</string>
    <string name="passcode_wrong">Wrong pin, please try again.</string>
    <string name="enable_passcode">Enable Pin</string>
</resources>

В главном пакете создаем класс приложения App.java, в котором инициализируем AppLocker:

import android.app.Application;

import com.balram.locker.view.AppLocker;


public class App extends Application {
    @Override
    public void onCreate() {
        super.onCreate();
        AppLocker.getInstance().enableAppLock(this);
    }
}

Объявим класс App.java в манифесте в секции application:

<application
        android:name=".App"
        ...
    </application>

Макет главного экрана activity_main.xml содержит две кнопки:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:gravity="center"
    tools:context="info.fandroid.applock.MainActivity">

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/bt_change"
        android:layout_above="@+id/bt_on_off"
        android:layout_alignParentStart="true" />

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/bt_on_off"
        android:layout_alignParentBottom="true"
        android:layout_alignParentStart="true"
        android:layout_marginBottom="156dp" />
</RelativeLayout>

И код класса MainActivity.java, который унаследован от библиотечного класса LockActivity:

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.balram.locker.utils.Locker;
import com.balram.locker.view.AppLocker;
import com.balram.locker.view.LockActivity;

public class MainActivity extends LockActivity implements View.OnClickListener {

    private Button btOnOff;
    private Button btChange;

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

        btOnOff = (Button) findViewById(R.id.bt_on_off);
        btChange = (Button) findViewById(R.id.bt_change);

        btOnOff.setOnClickListener(this);
        btChange.setOnClickListener(this);
        btChange.setText(R.string.change_passcode);

        updateUI();
    }

    @Override
    public void onClick(View view) {
        if (view.equals(btOnOff)) {
            int type = AppLocker.getInstance().getAppLock().isPasscodeSet() ? Locker.DISABLE_PASSLOCK : Locker.ENABLE_PASSLOCK;
            Intent intent = new Intent(this, LockActivity.class);
            intent.putExtra(Locker.TYPE, type);
            startActivityForResult(intent, type);
        } else if (view.equals(btChange)) {
            Intent intent = new Intent(this, LockActivity.class);
            intent.putExtra(Locker.TYPE, Locker.CHANGE_PASSWORD);
            intent.putExtra(Locker.MESSAGE, getString(R.string.enter_old_passcode));
            startActivityForResult(intent, Locker.CHANGE_PASSWORD);
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        switch (requestCode) {
            case Locker.DISABLE_PASSLOCK:
                break;
            case Locker.ENABLE_PASSLOCK:
                case Locker.CHANGE_PASSWORD:
                    if (resultCode == RESULT_OK) {
                        Toast.makeText(this, getString(R.string.setup_passcode), Toast.LENGTH_SHORT).show();
                    }
                    break;
                default:
                    break;
        }
        updateUI();

    }
    private void updateUI() {
        if (AppLocker.getInstance().getAppLock().isPasscodeSet()) {
            btOnOff.setText(R.string.disable_passcode);
            btChange.setEnabled(true);
        } else {
            btOnOff.setText(R.string.enable_passcode);
            btChange.setEnabled(false);
        }
    }
}

В методе onCreate объявлены кнопки и присвоен обработчик нажатия.  В методе onClick определяем нажатую кнопку, а также содаем и отправляем интенты с наборами данных, вызывающие класс LockActivity. Последний отображает экран ввода для установки или смены пароля. В методе onActivityResult можно добавить нужное поведение приложения, в зависимости от того, какой интент пришел. Метод updateUI  меняет текст на кнопках и делает кнопку смены пароля неактивной, если защита паролем отключена.

Исходный код библиотеки AppLocker – на странице в GitHub.[:en]In this video tutorial we implement application locks with AppLocker library. Source code – below, under the video.

To import the library into the project, add the line in build.gradle assembly file (Module: app):

allprojects {
    repositories {
        maven { url "https://jitpack.io" }
    }
}

dependencies {
    compile 'com.github.balrampandey19:AppLocker:1.0.1'
}

Also needed are string resources in res / values ​​/ strings.xml file:

<resources>
    <string name="app_name">AppLock</string>

    <string name="manage_passcode">Manage Pin</string>
    <string name="enter_passcode">Enter Pin</string>
    <string name="enter_old_passcode">Enter old Pin</string>
    <string name="reenter_passcode">Re-enter Pin</string>
    <string name="change_passcode">Change Pin</string>
    <string name="setup_passcode">Setup pin</string>
    <string name="passcode_wrong">Wrong pin, please try again.</string>
    <string name="enable_passcode">Enable Pin</string>
</resources>

In the main class of the application package is created App.java, which initialize AppLocker:

import android.app.Application;

import com.balram.locker.view.AppLocker;


public class App extends Application {
    @Override
    public void onCreate() {
        super.onCreate();
        AppLocker.getInstance().enableAppLock(this);
    }
}

Declare App.java class in the manifest in the application section:

<application
        android:name=".App"
        ...
    </application>

Макет главного экрана activity_main.xml содержит две кнопки:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:gravity="center"
    tools:context="info.fandroid.applock.MainActivity">

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/bt_change"
        android:layout_above="@+id/bt_on_off"
        android:layout_alignParentStart="true" />

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/bt_on_off"
        android:layout_alignParentBottom="true"
        android:layout_alignParentStart="true"
        android:layout_marginBottom="156dp" />
</RelativeLayout>

And the code class MainActivity.java, which is inherited from the library class LockActivity:

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.balram.locker.utils.Locker;
import com.balram.locker.view.AppLocker;
import com.balram.locker.view.LockActivity;

public class MainActivity extends LockActivity implements View.OnClickListener {

    private Button btOnOff;
    private Button btChange;

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

        btOnOff = (Button) findViewById(R.id.bt_on_off);
        btChange = (Button) findViewById(R.id.bt_change);

        btOnOff.setOnClickListener(this);
        btChange.setOnClickListener(this);
        btChange.setText(R.string.change_passcode);

        updateUI();
    }

    @Override
    public void onClick(View view) {
        if (view.equals(btOnOff)) {
            int type = AppLocker.getInstance().getAppLock().isPasscodeSet() ? Locker.DISABLE_PASSLOCK : Locker.ENABLE_PASSLOCK;
            Intent intent = new Intent(this, LockActivity.class);
            intent.putExtra(Locker.TYPE, type);
            startActivityForResult(intent, type);
        } else if (view.equals(btChange)) {
            Intent intent = new Intent(this, LockActivity.class);
            intent.putExtra(Locker.TYPE, Locker.CHANGE_PASSWORD);
            intent.putExtra(Locker.MESSAGE, getString(R.string.enter_old_passcode));
            startActivityForResult(intent, Locker.CHANGE_PASSWORD);
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        switch (requestCode) {
            case Locker.DISABLE_PASSLOCK:
                break;
            case Locker.ENABLE_PASSLOCK:
                case Locker.CHANGE_PASSWORD:
                    if (resultCode == RESULT_OK) {
                        Toast.makeText(this, getString(R.string.setup_passcode), Toast.LENGTH_SHORT).show();
                    }
                    break;
                default:
                    break;
        }
        updateUI();

    }
    private void updateUI() {
        if (AppLocker.getInstance().getAppLock().isPasscodeSet()) {
            btOnOff.setText(R.string.disable_passcode);
            btChange.setEnabled(true);
        } else {
            btOnOff.setText(R.string.enable_passcode);
            btChange.setEnabled(false);
        }
    }
}

In the method onCreate announced button and pressing the assigned handler. In the method onClick define the touch of a button as well as soda and send Intents with data sets that cause LockActivity class. Last displays the input screen to set or change the password. The method onActivityResult desired behavior can add applications, depending on what came intent. updateUI method changes the text on the buttons and make the change password button is disabled if the password protection is disabled.

AppLocker Source code library – on the page in GitHub.[:]

Додати коментар