首页 \ 问答 \ 如何在按下主页按钮时终止活动?(How to kill an activity when the Home button is pressed?)

如何在按下主页按钮时终止活动?(How to kill an activity when the Home button is pressed?)

我想在用户按下Home按钮时终止Activity。 为此,我使用以下代码:

public void onPause() {
    super.onPause();
    this.finish();
}

它工作正常。 但是如果用户按下“返回”按钮而不是“主页”,则它也会终止活动。 我希望后退按钮像往常一样执行,即它应该让用户进行上一个活动。 有什么想法吗?

以下是我的Activity类的代码:

public class HomeScreen extends Activity {
    /** Called when the activity is first created. */
        private Button btn_play;
        private MediaPlayer mp = new MediaPlayer();
        private static int AUDIO_NO = 1;
        public static String isVideoSelected = "";
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
            try{
                btn_play = (Button)findViewById(R.id.btn_play);
                btn_play.setOnClickListener(btn_listener);
                if(isVideoSelected!="") isVideoSelected="";
                Handler handler = new Handler();
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        // TODO Auto-generated method stub
                        play_audio(AUDIO_NO);
                    }
                }, 1000);
            } catch(Exception e) {

            }
        }
        private void play_audio(int slno) {
            try {
                if(slno == 1) mp = MediaPlayer.create(getBaseContext(), R.raw.audio_1);
                else if(slno == 2) mp = MediaPlayer.create(getBaseContext(), R.raw.audio_2);
                mp.setLooping(false);
                mp.setOnCompletionListener(audio_listener);
                mp.start();
            } catch(Exception e) {
                // do nothing
            }
        }
        private MediaPlayer.OnCompletionListener audio_listener = new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                // TODO Auto-generated method stub
                try{
                    mp.release();
                    if(AUDIO_NO == 1) {
                        play_audio(2);
                        AUDIO_NO++;
                    }
                } catch(Exception e) {

                }
            }
        };
        private View.OnClickListener btn_listener = new View.OnClickListener() {        
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                try{
                    if(mp.isPlaying()) {
                        mp.stop();
                        mp.release();
                    }
                    Intent intent = new Intent(getApplicationContext(), ScreenTwo.class);
                    startActivity(intent);
                } catch(Exception e) {

                } finally {
                }
            }
        };
        public void onUserLeaveHint() {
            super.onUserLeaveHint();
            try{
                if(mp.isPlaying()) {
                    mp.stop();
                    mp.release();
                }
                btn_play = null;
            } catch(Exception e) {

            }
        }
        @Override
        public void onDestroy() {
            super.onDestroy();
            try{
                if(mp.isPlaying()) {
                    mp.stop();
                    mp.release();
                }
                btn_play = null;
            } catch(Exception e) {

            }
        }
    }

I want to kill an Activity when the user presses the Home button. For this I'm using the following code:

public void onPause() {
    super.onPause();
    this.finish();
}

It works fine. But instead of Home if the user presses the Back button it also kills the activity. I want the back button to perform as usual i.e it should take the user to the previous activity. Any thoughts?

The following is the code of my Activity class:

public class HomeScreen extends Activity {
    /** Called when the activity is first created. */
        private Button btn_play;
        private MediaPlayer mp = new MediaPlayer();
        private static int AUDIO_NO = 1;
        public static String isVideoSelected = "";
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
            try{
                btn_play = (Button)findViewById(R.id.btn_play);
                btn_play.setOnClickListener(btn_listener);
                if(isVideoSelected!="") isVideoSelected="";
                Handler handler = new Handler();
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        // TODO Auto-generated method stub
                        play_audio(AUDIO_NO);
                    }
                }, 1000);
            } catch(Exception e) {

            }
        }
        private void play_audio(int slno) {
            try {
                if(slno == 1) mp = MediaPlayer.create(getBaseContext(), R.raw.audio_1);
                else if(slno == 2) mp = MediaPlayer.create(getBaseContext(), R.raw.audio_2);
                mp.setLooping(false);
                mp.setOnCompletionListener(audio_listener);
                mp.start();
            } catch(Exception e) {
                // do nothing
            }
        }
        private MediaPlayer.OnCompletionListener audio_listener = new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                // TODO Auto-generated method stub
                try{
                    mp.release();
                    if(AUDIO_NO == 1) {
                        play_audio(2);
                        AUDIO_NO++;
                    }
                } catch(Exception e) {

                }
            }
        };
        private View.OnClickListener btn_listener = new View.OnClickListener() {        
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                try{
                    if(mp.isPlaying()) {
                        mp.stop();
                        mp.release();
                    }
                    Intent intent = new Intent(getApplicationContext(), ScreenTwo.class);
                    startActivity(intent);
                } catch(Exception e) {

                } finally {
                }
            }
        };
        public void onUserLeaveHint() {
            super.onUserLeaveHint();
            try{
                if(mp.isPlaying()) {
                    mp.stop();
                    mp.release();
                }
                btn_play = null;
            } catch(Exception e) {

            }
        }
        @Override
        public void onDestroy() {
            super.onDestroy();
            try{
                if(mp.isPlaying()) {
                    mp.stop();
                    mp.release();
                }
                btn_play = null;
            } catch(Exception e) {

            }
        }
    }

原文:https://stackoverflow.com/questions/5220456
更新时间:2023-03-08 21:03

最满意答案

这可能是OS X上的安全功能的结果,也是JNativeHook设计用于运行的方式的一部分。 大多数系统都没有强制执行这种策略,但是,Apple通过其可访问性API确实在输入安全方面处于领先地位。 如果要在OS X上获取密码数据,则需要在内核级别创建一些内容,并且需要某种特权升级才能至少安装。


This is probably the result of a security feature on OS X and is part of the way JNativeHook was designed to function. Most systems do not enforce this kind of policy, however, Apple has really lead the way on input security via their accessibility API. If you want to get password data on OS X, you will need to create something at the kernel level and it will require some kind of privilege escalation to at least install.

相关问答

更多
  • Mac OS X的“钥匙串访问”应用程序可让您访问漂亮的OS X密码生成器。 点击命令-N并点击键图标。 您可以选择密码样式(难忘,数字,字母数字,随机,FIPS-181)并选择长度。 它还会警告您密码较弱。 Mac OS X's "Keychain Access" application gives you access to the nice OS X password generator. Hit command-N and click the key icon. You get to choose ...
  • 您需要监听所需组合的每个单独的按键和释放事件,并在按下每个按键时设置某种标记。 如果按下其中一个所需的键,并且满足标志条件,则可以执行将这些键按在一起时需要执行的操作。 如果不创建自定义键盘驱动程序,则无法为两个键获取单个事件。 如果您的目标是在按下W和A键之前抑制W和A键事件,请查看Wiki的不支持的消费事件部分。 请注意,事件抑制仅适用于Windows和OS X目标,并且抑制的事件不会传递到其他应用程序。 它不是最漂亮的例子,但它应该做你想要的。 private short hotKeyFlag = 0 ...
  • 如果安全性对你来说真的很重要,那么我真的会喜欢HTTPS。 如果它不适用于你,也许切换网络主机或任何你的限制? 如果钱是问题,那么在问题评论中有一些建议(免费的,自签名的等)。 这种哈希与时间戳,这几乎只会最终作为安全通过默默无闻 ( 相关问题 )。 但我不是安全专家。 我所知道的是,安全非常非常困难,那些想要突破的人通常比我聪明。 所以我尽量保持简单,并使用通用的经过良好测试的解决方案,而不是试图提出自己的“聪明”的东西。 If security really is so important to you ...
  • 我认为这篇文章指的是钩子在目标的进程空间中运行的事实。 它可以刮掉屏幕或内存,它可以注入代码,它可以监视事件队列。 I think the article is referring to the fact that the hook runs in the process space of the target. It can scrape screen or memory, it can inject code, it can monitor the event queue.
  • 更仔细地考虑“获得对机器的访问权”的含义。 对于被盗的计算机,请考虑使用Bitlocker。 对于侵入式用户,请考虑用户权限和登录策略/权限。 保护文件最直接的方法是使用NTFS权限。 将文件存储在目录中,并仅为包含脚本运行程序帐户的特定组授予读访问权限。 加密凭证文件是一个鸡和蛋问题。 无论如何,您都需要将加密密钥存储在某处,除非每次运行脚本时都会提示密钥。 EFS可以在某种程度上使用,但它也不是银弹。 Think more carefully what's meant by "gains access ...
  • 这可能是OS X上的安全功能的结果,也是JNativeHook设计用于运行的方式的一部分。 大多数系统都没有强制执行这种策略,但是,Apple通过其可访问性API确实在输入安全方面处于领先地位。 如果要在OS X上获取密码数据,则需要在内核级别创建一些内容,并且需要某种特权升级才能至少安装。 This is probably the result of a security feature on OS X and is part of the way JNativeHook was designed to ...
  • hook_set_logger_proc应该在链接时由libuiohook定义。 这可能与问题#43有关 。 hook_set_logger_proc should be defined by libuiohook at link-time. This is probably related to Issue #43.
  • 在异常描述中,您有提示如何解决此错误: mapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS); 你能尝试一下吗? 如果要仅序列化某些属性,还可以为此字段实现自定义序列化程序。 In exception description you have tip how to solve this bug: mapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS); Could you try wit ...
  • 你会想调查马尔可夫链方法 。 这是一个例子: http://www.multicians.org/thvv/gpw.html 这里有一些自动生成的密码: http://www.manic.org/new/pw/pron.html You'll want to investigate the Markov chain method. Here's an example: http://www.multicians.org/thvv/gpw.html and here are some auto-generat ...
  • 在让用户选择新密码时,您可以输入他/她的旧密码。 这允许您将新密码与旧密码进行比较,而无需将旧密码存储在纯文本中。 At the time of making the user choose a new password, you make him/her enter his/her old password. This allows you to compare the new password to the old password without having to store the old pas ...

相关文章

更多

最新问答

更多
  • 您如何使用git diff文件,并将其应用于同一存储库的副本的本地分支?(How do you take a git diff file, and apply it to a local branch that is a copy of the same repository?)
  • 将长浮点值剪切为2个小数点并复制到字符数组(Cut Long Float Value to 2 decimal points and copy to Character Array)
  • OctoberCMS侧边栏不呈现(OctoberCMS Sidebar not rendering)
  • 页面加载后对象是否有资格进行垃圾回收?(Are objects eligible for garbage collection after the page loads?)
  • codeigniter中的语言不能按预期工作(language in codeigniter doesn' t work as expected)
  • 在计算机拍照在哪里进入
  • 使用cin.get()从c ++中的输入流中丢弃不需要的字符(Using cin.get() to discard unwanted characters from the input stream in c++)
  • No for循环将在for循环中运行。(No for loop will run inside for loop. Testing for primes)
  • 单页应用程序:页面重新加载(Single Page Application: page reload)
  • 在循环中选择具有相似模式的列名称(Selecting Column Name With Similar Pattern in a Loop)
  • System.StackOverflow错误(System.StackOverflow error)
  • KnockoutJS未在嵌套模板上应用beforeRemove和afterAdd(KnockoutJS not applying beforeRemove and afterAdd on nested templates)
  • 散列包括方法和/或嵌套属性(Hash include methods and/or nested attributes)
  • android - 如何避免使用Samsung RFS文件系统延迟/冻结?(android - how to avoid lag/freezes with Samsung RFS filesystem?)
  • TensorFlow:基于索引列表创建新张量(TensorFlow: Create a new tensor based on list of indices)
  • 企业安全培训的各项内容
  • 错误:RPC失败;(error: RPC failed; curl transfer closed with outstanding read data remaining)
  • C#类名中允许哪些字符?(What characters are allowed in C# class name?)
  • NumPy:将int64值存储在np.array中并使用dtype float64并将其转换回整数是否安全?(NumPy: Is it safe to store an int64 value in an np.array with dtype float64 and later convert it back to integer?)
  • 注销后如何隐藏导航portlet?(How to hide navigation portlet after logout?)
  • 将多个行和可变行移动到列(moving multiple and variable rows to columns)
  • 提交表单时忽略基础href,而不使用Javascript(ignore base href when submitting form, without using Javascript)
  • 对setOnInfoWindowClickListener的意图(Intent on setOnInfoWindowClickListener)
  • Angular $资源不会改变方法(Angular $resource doesn't change method)
  • 在Angular 5中不是一个函数(is not a function in Angular 5)
  • 如何配置Composite C1以将.m和桌面作为同一站点提供服务(How to configure Composite C1 to serve .m and desktop as the same site)
  • 不适用:悬停在悬停时:在元素之前[复制](Don't apply :hover when hovering on :before element [duplicate])
  • 常见的python rpc和cli接口(Common python rpc and cli interface)
  • Mysql DB单个字段匹配多个其他字段(Mysql DB single field matching to multiple other fields)
  • 产品页面上的Magento Up出售对齐问题(Magento Up sell alignment issue on the products page)