0

I am currently using a custom AlertDialog which has a Theme.Dialog theme in a Activity that requires users to type the current password to proceed.

According to Android - Is It possible to disable the click of home button i have tried most of the methods but it doesn't work.

Activity - onCreate

      SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(PhysicalTheftDialog.this);

        boolean isServerRunning = sp.getBoolean("isServerRunning", false);
            if (isServerRunning == false) {
                startService(new Intent(PhysicalTheftDialog.this, MyService.class));

            }
            else {
                sp.getBoolean("isServerRunning", true);
            }

Service

    @Override
    public void onCreate() {
/*      //Toast.makeText(this, "My Service Created", Toast.LENGTH_LONG).show();
        Log.d(TAG, "onCreate");

        player = MediaPlayer.create(this, R.raw.braincandy);
        player.setOnPreparedListener(this);
        try {
            player.prepareAsync();

        } catch (Exception e) {
            Log.e(TAG, "", e);
        }
        player.setLooping(true); // Set looping*/
        this.context = getApplicationContext();
        //Toast.makeText(this, "My Service Created", Toast.LENGTH_LONG).show();
        SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
        boolean isServerRunning = sp.getBoolean("isServerRunning", true);

        while (!isServerRunning) {
            // THAT CODE: check if activity is on the top
            Handler handler = new Handler(); 

            handler.postDelayed(new Runnable() { 
                 public void run() { 

                        // get a list of running processes and iterate through them
                        ActivityManager activityManager = (ActivityManager)context.getSystemService(Activity.ACTIVITY_SERVICE);

                        // get the info from the currently running task
                        List<ActivityManager.RunningTaskInfo> taskInfo = activityManager.getRunningTasks(1);
                        ComponentName componentInfo = taskInfo.get(0).topActivity;

                        // if top activity is not "MyActivity" activity, then launch it
                        if("nyp.android.project".equals(componentInfo.getClassName()) == false) {
                            Intent intent = new Intent(MyService.this, PhysicalTheftDialog.class);
                            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            startActivity(intent);
}
                 } 
            }, 2000); 

            boolean serviceStatus = sp.getBoolean("isServerRunning", false);
        }
    }

Logcat

E/AndroidRuntime( 9799): FATAL EXCEPTION: main
E/AndroidRuntime( 9799): java.lang.RuntimeException: Unable to start service nyp.android.project.MyService@41b29ff0 with Intent { cmp=xxxx }: java.lang.NullPointerException
E/AndroidRuntime( 9799):    at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:2387)
E/AndroidRuntime( 9799):    at android.app.ActivityThread.access$1900(ActivityThread.java:127)
E/AndroidRuntime( 9799):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1221)
E/AndroidRuntime( 9799):    at android.os.Handler.dispatchMessage(Handler.java:99)
E/AndroidRuntime( 9799):    at android.os.Looper.loop(Looper.java:137)
E/AndroidRuntime( 9799):    at android.app.ActivityThread.main(ActivityThread.java:4511)
E/AndroidRuntime( 9799):    at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime( 9799):    at java.lang.reflect.Method.invoke(Method.java:511)
E/AndroidRuntime( 9799):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:980)
E/AndroidRuntime( 9799):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:747)
E/AndroidRuntime( 9799):    at dalvik.system.NativeStart.main(Native Method)
E/AndroidRuntime( 9799): Caused by: java.lang.NullPointerException
E/AndroidRuntime( 9799):    at nyp.android.project.MyService.onStart(MyService.java:95)
E/AndroidRuntime( 9799):    at android.app.Service.onStartCommand(Service.java:438)
E/AndroidRuntime( 9799):    at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:2370)
E/AndroidRuntime( 9799):    ... 10 more
Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
dythe
  • 840
  • 5
  • 21
  • 45
  • BTW: if ("nyp.android.project".equals(service.service.getClassName())) is a Yoda Condition http://www.codinghorror.com/blog/2012/07/new-programming-jargon.html – Maxim Jul 25 '12 at 15:48
  • boolean isServerRunning = sp.getBoolean("isServerRunning", true); If there is no "isServiceRunning" in preferences, you code return you true by default. Should be false I think. It looks okay. Run in debugger and see how it works. – Maxim Jul 25 '12 at 19:25
  • I'm getting 'ActivityManager cannot be resolved to a variable' – dythe Jul 25 '12 at 19:59
  • put ActivityManager activityManager = (ActivityManager)context.getSystemService(Activity.ACTIVITY_SERVICE); out of while. 2. It should be, try to Clean... your project. No dot (ActivityManager)context in front of context – Maxim Jul 25 '12 at 20:18
  • where do you put the Activity part of the code? I tried onPause but it hangs the moment i press the home button. – dythe Jul 26 '12 at 14:28
  • When Activity starts, in onCreate. Every time it's started it will check if service running or not to whether run it or not. Keep in mind that Service is running in the same thread. Better to use IntentService or start a new thread in your standard service. – Maxim Jul 26 '12 at 14:57
  • I updated the post with my current code and current logcat error, could it be because of the service on the same thread like you said? – dythe Jul 26 '12 at 15:30
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/14468/discussion-between-maxim-and-dythe) – Maxim Jul 26 '12 at 15:48

4 Answers4

1

McAfee Wave Secure did it in the following way: they run a background service that checks every couple seconds if your screen is active. If not Service relaunch your activity or bring it to the front (make it active). In onPause you can save input data to reload it when activity restarted.

My example:

// get a list of running processes and iterate through them
ActivityManager activityManager = (ActivityManager)_context
        .getSystemService(Activity.ACTIVITY_SERVICE);

// get the info from the currently running task
List<ActivityManager.RunningTaskInfo> taskInfo = activityManager.getRunningTasks(1);
ComponentName componentInfo = taskInfo.get(0).topActivity;

// if top activity is not "MyActivity" activity, then launch it
if(componentInfo.getClassName().equals("com.namespace.MyActivity") == false) {
    Intent intent = new Intent(context, MyActivity.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    context.startActivity(intent);
}

I do "FLAG_ACTIVITY_NEW_TASK" because I`ve been gotten many instances of the same activity. Maybe there is a way just to make it active.

Example "PSEUDO"

{
    Activity:
    preference isServerRunning = getPreference("isServerRunning");
    if (serviceIsRunning == false) {
        runService();
    }
    // othervise, service is running and will do the job
    Onclick.UserLogged() {
        setPreference("isUserLoged", true);
    }

    Service:
    while (!userIsLogged) {
        // THAT CODE: check if activity is on the top

        sleepFor2seconds();
        userIsLogger = getPreference("isUserLogged");
    }

}
Maxim
  • 4,152
  • 8
  • 50
  • 77
  • Any idea how to check whether the screen is active? – dythe Jul 25 '12 at 14:57
  • So i will just put this inside the onCreate() method of a Service and use in my main Activity i will call the service in the onPause() method? – dythe Jul 25 '12 at 15:11
  • This can be implemented like this: when your activity is run check a flag (e.g. have a preference) if your service is running or not. If not then set the flag and run the service. Until work is done (while user still need to do something) service in a loop every 2-5 sec will check if specific activity is on the top of activity stack, if not then make it on the top. When user is done, set the flag off, server next run will read the flag and finish its run – Maxim Jul 25 '12 at 15:22
  • Is it going to be something like this? Updated the post. I can't return the value for spe – dythe Jul 25 '12 at 15:31
0

Try overiding the onPause() method so that the activity will not stop when the home button press calls it

ghostbust555
  • 2,040
  • 16
  • 29
0

Try to override the method onKeyDown of your Activity class where u want to disable HOME button. In this method check if the user has pressed the HOME button.

FrancescoAzzola
  • 2,666
  • 2
  • 15
  • 22
0

Maybe I'm Late But

This Is The Only Way Possible

First You Have To Detect The Home Is Pressed

See This Answer To Detect It

Detect Home Button Pressed

Make Changes To This Part Of The Above Answer

 HomeWatcher homeWatcher=new HomeWatcher(this);
    homeWatcher.setOnHomePressedListener(new OnHomePressedListener() {
        @Override
        public void onHomePressed() {
            //So Here The Main Thing Is..

            //You Will Have To Figure Out A Condition On When You Do You Want The Home Button Not To Close The Activity

            //In The Condition You Have To Restart The Activity 

            Intent intent = getIntent();
            overridePendingTransition(0, 0);
            intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
            finish();
            overridePendingTransition(0, 0);
            startActivity(intent);
           }
        });

So This Code Will Disable The Home Button ( Not Exactly But A Sort Of )

I Hope You Understood It And Works Fine ... If Not , Feel Free To Reach Me Out ( Relating any other sort of additional questions on this OR The Explanation For This )

Daksh Rawal
  • 238
  • 2
  • 13