public class Main extends Activity
{
private NotificationManager notificationManager;
private Notification notification;
@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());
Log.d("11111111111", "Oncreate");
}
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if(keyCode == KeyEvent.KEYCODE_BACK )
{
showDialog();//调用退出对话框
Log.d("back", "back");
}
return super.onKeyDown(keyCode, event);
}
/**如果用户按下home键,会调用onStop()。发送一个通知。通过这个通知就可以回到原来的界面,而不会调用onCreate方法*/
@Override
protected void onStop()
{
Intent notificationIntent = new Intent(Main.this, Main.class);//这个实际上只是指定启动一个Activity,这里选择本身
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
notification.flags = Notification.FLAG_ONGOING_EVENT;//这个表示“正在进行的”,而不是“通知”
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(){
@Override
public void onClick(DialogInterface dialog, int which) {
//finish();//如果这里执行的是finish(),则也会调用onStop()
android.os.Process.killProcess(android.os.Process.myPid());//整个结束掉,这样就不会执行onStop()
}
}).setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
}).show();
}
}