不是QQ的那种效果,我实现的是:当用户点击BACK键的时候,拦截这个事件,弹出一个对话框,提示用户是否退出,如果用户点击是,则退出。当用户点击HOME键。这时候在状态栏上面发送一个提醒,表示程序还在运行。
public class TestNotificationActivity extends Activity
{
private NotificationManager notificationManager;
private Notification notification;
private Button btnExit;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notification = new Notification(R.drawable.ic_launcher, "", System.currentTimeMillis());
btnExit = (Button)findViewById(R.id.btn_exit);
btnExit.setOnClickListener(new BtnExitClickedListener());
Log.d("11111111111", "Oncreate");
//notificationManager.cancelAll();
}
class BtnExitClickedListener implements OnClickListener
{
public void onClick(View v)
{
notificationManager.cancelAll();//清理notification
android.os.Process.killProcess(android.os.Process.myPid());//整个结束掉
}
}
public boolean onKeyDown(int keyCode, KeyEvent event)
{
// if(keyCode==KeyEvent.KEYCODE_HOME )
// {
// Log.d("home", "home");
// // flag = true;
// finish();//实际上这里已经将应用程序杀死了。而从notification中启动只是启动指定的Activity。程序已经死掉了。返回键同样道理
//
// //return true;
// }
if(keyCode == KeyEvent.KEYCODE_BACK )
{
showDialog();//调用对话框
Log.d("back", "back");
// return true;
}
return super.onKeyDown(keyCode, event);
}
// @Override
//
// //要有这个监听home键才可以实现
// public void onAttachedToWindow()
//
// { // TODO Auto-generated method stub
//
// this.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD);
//
// super.onAttachedToWindow();
//
// }
/**如果用户按下home键,会调用onStop()。发送一个通知。在这个通知里面就可以回到原来的界面,而不会调用onCreate方法*/
@Override
protected void onStop()
{
notification.flags = Notification.FLAG_ONGOING_EVENT;//这个表示在运行中
Intent notificationIntent = new Intent(TestNotificationActivity.this, TestNotificationActivity.class);//这个实际上只是指定启动一个Activity
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
notification.setLatestEventInfo(this, "哇哈哈","哥在运行中...", contentIntent);
notificationManager.notify(R.drawable.ic_launcher, notification);
Log.d("111111111", "onStop");
super.onStop();
}
/** 重新获得焦点的时候清理notification*/
@Override
protected void onResume()
{
notificationManager.cancelAll();
super.onResume();
}
/** 创建一个对话框,确认是否退出*/
private void showDialog()
{
new AlertDialog.Builder(this).setTitle("是否退出应用程序?")
.setPositiveButton("确定", new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int which) {
finish();
}
}).setNegativeButton("取消", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
}).show();
}
}