android基础学习之back键的监听和回到主页面

以前一直看别人写back键的监听,今天朋友问到自己了,然后自己说了一下,突然发现自己写不出来,然后百度了一下,不过就是一个onKeyDown的重写,。。。因为感觉代码太少,所以在添加监听的时候一个是关闭当前的activity,然后另外一个是跳转到桌面。ok,基本就这些,贴代码了

package com.jk.backdemo;

import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.text.AlteredCharSequence;
import android.view.KeyEvent;
import android.view.Menu;
import android.widget.Toast;

public class MainActivity extends Activity {

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


   @Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
	//judge the keyCode
	   if(keyCode==KeyEvent.KEYCODE_BACK){
		   //create a AlertDialog.Builder's builder object
		AlertDialog.Builder builder=new Builder(this);
		//set the title
		builder.setTitle("确认退出");
		//set a postive button and add a listerer
		builder.setPositiveButton("确定", new OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				//finish Activity
			finish();
			}
			//set a negative button and add a listener
		}).setNegativeButton("取消", new OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				//init a intent
				Intent intent=new Intent();
				//add the Action property
				intent.setAction(intent.ACTION_MAIN);
				//Intent intent=new Intent(Intent.ACTION_MAIN);这句话和上面两句是等价的
				//add the Category property
				intent.addCategory(Intent.CATEGORY_HOME);
				//launch activity
				startActivity(intent);
			}
		}).show();
	   }
	return true;
}
    
}


你可能感兴趣的:(Android基础学习)