2013/01/21

Android 攔截Back鍵

如果要攔截Back鍵可以用以下這個方法,如果要攔截Home鍵建議去攔截廣播會比較方便





package com.cyfang.button;

import android.app.Activity;
import android.os.Build;
import android.os.Bundle;
import android.view.KeyEvent;
import android.widget.Toast;

public class Wow extends Activity {

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (getApplicationInfo().targetSdkVersion >= Build.VERSION_CODES.ECLAIR) {
                event.startTracking();
            } else {
                onBackPressed(); // 是其他按鍵則再Call Back方法
            }
        }
        return false;
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if (keyCode == 4) {
            Toast.makeText(Wow.this, "沒辦法返回喔", Toast.LENGTH_LONG).show();
        }
        return super.onKeyUp(keyCode, event);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_wow);
    }
}


參考資料:
http://www.javaworld.com.tw/jute/post/view?bid=26&id=283763