Abhishek Chandale
Abhishek Chandale

Reputation: 1

Regarding issue on App Lock Service Android

I am working for App Locker. I have made services that will check locked apps and will show LOCK APP SCREEN so that user can enter password code. My code is working fine till this stage when Lock App open.

I need to stop my service because my service is continuously running? It is showing my Login Activity again and again while user has already enter correct credentials. How can I stop this issue? code: Service:

public class ProcessService extends Service {

private Set<String> mLockedApps = new HashSet<String>();
private long lastModified = 0;
private BroadcastReceiver mScreenStateReceiver;
private File mLockedAppsFile;
ArrayList<String> packagezList;
SharedPreferences sharedPrefs;
Map<String, ?> allEntries;
SharedPreferences sharedPrefsapp;
Object obj;
private String prefix;
private Handler handler;
private DbAccess dbAccess;
@Override
public IBinder onBind(Intent arg0) {
    return null;
}


@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    startService(new Intent(this, ProcessService.class));
     dbAccess=new DbAccess(this);

    if (TIMER == null) {

        TIMER = new Timer(true);
        TIMER.scheduleAtFixedRate(new LockAppsTimerTask(), 3000, 750);
        mScreenStateReceiver = new BroadcastReceiver() {

            private boolean screenOff;

            @Override
            public void onReceive(Context context, Intent intent) {



                if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
                    screenOff = true;
                } else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
                    screenOff = false;
                }

                if (screenOff) {
                    //Log.i(TAG, "Cancel Timer");
                    TIMER.cancel();
                } else {
                    // Log.i(TAG, "Restart Timer");
                    TIMER = new Timer(true);
                    TIMER.scheduleAtFixedRate(new LockAppsTimerTask(), 1000, 250);
                }
            }
        };

        IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
        filter.addAction(Intent.ACTION_SCREEN_OFF);
            registerReceiver(mScreenStateReceiver, filter);

    }
    // this.stopSelf();
    //startforeground goes here
    return START_STICKY;
}

@Override
public void onDestroy() {
    super.onDestroy();
    startService(new Intent(this, ProcessService.class));
}

private class LockAppsTimerTask extends TimerTask {

    @Override
    public void run() {


        sharedPrefs = getApplicationContext().getSharedPreferences(getApplicationContext().getPackageName(), Context.MODE_PRIVATE);
        sharedPrefsapp = getApplicationContext().getSharedPreferences("appdb", Context.MODE_PRIVATE);
        allEntries= null;
        allEntries = sharedPrefsapp.getAll();

        //prefix = "m";
        packagezList= null;
        packagezList = new ArrayList<String>();
        for (Map.Entry<String, ?> entry : allEntries.entrySet()) {

            Log.e("right key: ", entry.getKey().toString() + "right value: " + entry.getValue().toString());


            packagezList.add(entry.getKey());
        }

        for(Object object: packagezList){
            Log.e("Object!", (String) object);
        //    Log.e("Package",""+packagezList.get(0));
        }


        ActivityManager activityManager = (ActivityManager) getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE);

        try {
            //List<RecentTaskInfo> recentTasks = activityManager.getRecentTasks(1, ActivityManager.RECENT_IGNORE_UNAVAILABLE);
            ActivityManager mActivityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
            List<ActivityManager.RunningTaskInfo> RunningTask = mActivityManager
                    .getRunningTasks(1);
            ActivityManager.RunningTaskInfo ar = RunningTask.get(0);
            String activityOnTop = ar.topActivity.getPackageName();

            Log.e("activity on Top", "" + activityOnTop);
            Log.e(" My package name", "" + getApplicationContext().getPackageName());
            //for (Object data : newArrayList) {

            for(Object object: packagezList){
                Log.e("My Object!", (String)object);



                if(activityOnTop.equals("com.android.settings"))
                {  // you have to make this check even better
                    Intent i = new Intent(getApplicationContext(), MainActivity.class);
                    i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_NO_USER_ACTION);
                    i.putExtra("callFromService",true);
                    i.putExtra("ApppakageName", "com.android.settings" );
                    startActivity(i);
                }

            }
        } catch (Exception e) {
            Log.e("Foreground App", e.getMessage(), e);
        }
    }



}

}

LockScreenActivity:

public class SeconActivity extends Activity {

    public static final String TAG = "AppLock-Abhishek";
    private String oldPasscode = null;
    protected EditText codeField1 = null;
    protected EditText codeField2 = null;
    protected EditText codeField3 = null;
    protected EditText codeField4 = null;
    protected TextView tvMessage = null;
    protected InputFilter[] filters = null;
    private String str1,str2,str3,str4;
    private ProgressDialog dialog;
    Map<String, ?> allEntries;
    SharedPreferences sharedPrefsapp;
    ArrayList<String> packagezList;
    private DbAccess dbAccess;
    private ActionBar actionBar;

    private int type=0;
    private String confirmPass=null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        dbAccess=new DbAccess(this);
        dialog=new ProgressDialog(this);
        setContentView(R.layout.page_passcode);
        Cursor c;
        c=dbAccess.getType();
        if(c.moveToNext())
        type=c.getInt(c.getColumnIndex("type"));
        Cursor cursor;
        cursor=dbAccess.getPasssword();
        if (cursor.moveToNext()) {
            confirmPass = cursor.getString(cursor.getColumnIndex("password"));
        }
            tvMessage = (TextView) findViewById(R.id.tv_message);
        tvMessage.setText(R.string.reenter_passcode);
        //editcodeFields
        filters = new InputFilter[2];
        filters[0] = new InputFilter.LengthFilter(1);
        filters[1] = numberFilter;

        codeField1 = (EditText) findViewById(R.id.passcode_1);
        setupEditText(codeField1);

        codeField2 = (EditText) findViewById(R.id.passcode_2);
        setupEditText(codeField2);

        codeField3 = (EditText) findViewById(R.id.passcode_3);
        setupEditText(codeField3);

        codeField4 = (EditText) findViewById(R.id.passcode_4);
        setupEditText(codeField4);

        // setup the keyboard
        ((Button) findViewById(R.id.button0)).setOnClickListener(btnListener);
        ((Button) findViewById(R.id.button1)).setOnClickListener(btnListener);
        ((Button) findViewById(R.id.button2)).setOnClickListener(btnListener);
        ((Button) findViewById(R.id.button3)).setOnClickListener(btnListener);
        ((Button) findViewById(R.id.button4)).setOnClickListener(btnListener);
        ((Button) findViewById(R.id.button5)).setOnClickListener(btnListener);
        ((Button) findViewById(R.id.button6)).setOnClickListener(btnListener);
        ((Button) findViewById(R.id.button7)).setOnClickListener(btnListener);
        ((Button) findViewById(R.id.button8)).setOnClickListener(btnListener);
        ((Button) findViewById(R.id.button9)).setOnClickListener(btnListener);

        ((Button) findViewById(R.id.button_clear))
                .setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        clearFields();
                    }
                });

        ((Button) findViewById(R.id.button_erase))
                .setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        onDeleteKey();
                    }
                });
    }


    private InputFilter numberFilter = new InputFilter() {
        @Override
        public CharSequence filter(CharSequence source, int start, int end,
                                   Spanned dest, int dstart, int dend) {

            if (source.length() > 1) {
                return "";
            }

            if (source.length() == 0) // erase
            {
                return null;
            }

            try {
                int number = Integer.parseInt(source.toString());
                if ((number >= 0) && (number <= 9))
                    return String.valueOf(number);
                else
                    return "";
            } catch (NumberFormatException e) {
                return "";
            }
        }
    };

    protected  void reEnterePass()

    {
        codeField1.setText("");
        codeField2.setText("");
        codeField3.setText("");
        codeField4.setText("");
        codeField1.requestFocus();


        // set the value and move the focus
    }

    protected void onPasscodeError() {
        Toast toast = Toast.makeText(this, getString(R.string.passcode_wrong),
                Toast.LENGTH_SHORT);
        toast.setGravity(Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 30);
        toast.show();

        Thread thread = new Thread() {
            public void run() {
                Animation animation = AnimationUtils.loadAnimation(
                        SeconActivity.this, R.anim.shake);
                findViewById(R.id.ll_applock).startAnimation(animation);
                codeField1.setText("");
                codeField2.setText("");
                codeField3.setText("");
                codeField4.setText("");
                codeField1.requestFocus();
            }
        };
        runOnUiThread(thread);
    }
    protected void setupEditText(EditText editText) {
        editText.setInputType(InputType.TYPE_NULL);
        editText.setFilters(filters);
        editText.setOnTouchListener(touchListener);
        editText.setTransformationMethod(PasswordTransformationMethod
                .getInstance());
    }


    private View.OnTouchListener touchListener = new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            v.performClick();
            clearFields();
            return false;
        }
    };

    private void clearFields() {
        codeField1.setText("");
        codeField2.setText("");
        codeField3.setText("");
        codeField4.setText("");
        codeField1.postDelayed(new Runnable() {

            @Override
            public void run() {
                codeField1.requestFocus();
            }
        }, 200);
    }

    private View.OnClickListener btnListener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            int currentValue = -1;
            int id = view.getId();
            if (id == R.id.button0) {
                currentValue = 0;
            } else if (id == R.id.button1) {
                currentValue = 1;
            } else if (id == R.id.button2) {
                currentValue = 2;
            } else if (id == R.id.button3) {
                currentValue = 3;
            } else if (id == R.id.button4) {
                currentValue = 4;
            } else if (id == R.id.button5) {
                currentValue = 5;
            } else if (id == R.id.button6) {
                currentValue = 6;
            } else if (id == R.id.button7) {
                currentValue = 7;
            } else if (id == R.id.button8) {
                currentValue = 8;
            } else if (id == R.id.button9) {
                currentValue = 9;
            } else {
            }

            // set the value and move the focus
            String currentValueString = String.valueOf(currentValue);
            if (codeField1.isFocused()) {
                codeField1.setText(currentValueString);
                str1=currentValueString;
                codeField2.requestFocus();
                codeField2.setText("");

            } else if (codeField2.isFocused()) {
                codeField2.setText(currentValueString);
                str2=currentValueString;
                codeField3.requestFocus();
                codeField3.setText("");
            } else if (codeField3.isFocused()) {
                codeField3.setText(currentValueString);
                str3=currentValueString;
                codeField4.requestFocus();
                codeField4.setText("");

            } else if (codeField4.isFocused()) {
                codeField4.setText(currentValueString);
                str4=currentValueString;
            }
            if (codeField4.getText().toString().length() > 0
                    && codeField3.getText().toString().length() > 0
                    && codeField2.getText().toString().length() > 0
                    && codeField1.getText().toString().length() > 0) {
                Log.e(TAG, str1 + str2 + str3 + str4);
                String passCode=(str1+str2+str3+str4).trim();
                switch (type){

                    case 1:
                            if (passCode.equals(confirmPass)){
                                startActivity(new Intent(getApplicationContext(),LockScreenActivity.class));
                            }else
                            {
                                onPasscodeError();
                            }


                        break;
                    case 2:

                        if(passCode.equalsIgnoreCase(confirmPass)){

                            finish();

                        }else
                        {
                            Intent startHomescreen=new Intent(Intent.ACTION_MAIN);
                            startHomescreen.addCategory(Intent.CATEGORY_HOME);
                            startHomescreen.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
                            startActivity(startHomescreen);
                        }
                        break;
                    default:
                        break;
                }
            }
        }
    };

    private void onDeleteKey() {
        if (codeField1.isFocused()) {

        } else if (codeField2.isFocused()) {
            codeField1.requestFocus();
            codeField1.setText("");
        } else if (codeField3.isFocused()) {
            codeField2.requestFocus();
            codeField2.setText("");
        } else if (codeField4.isFocused()) {
            codeField3.requestFocus();
            codeField3.setText("");
        }
    }
}//end of class

Upvotes: 0

Views: 1506

Answers (1)

user5645695
user5645695

Reputation:

First of all I would like to tell you that you should not rely on Timer for your code to run repetitively because timer is destroyed by system after sometime , i hope u would have realized this bug. And for your problem you should create a hashmap to know weather the foreground activity is already accessed by user or not by verifying the password.

Upvotes: 1

Related Questions