public class MainActivity extends Activity {
/** Called when the activity is first created. */
NotificationManager nm;
Notification notifi;
PendingIntent pi;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
nm = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
notifi = new Notification(R.drawable.ic_launcher,"",System.currentTimeMillis());
Intent intent = new Intent(this,MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|Intent.FLAG_ACTIVITY_NEW_TASK);
pi = PendingIntent.getActivity(this, 0, intent, 0);
notifi.setLatestEventInfo(this,"别当心", "哥还在", pi);
notifi.flags = Notification.FLAG_INSISTENT|Notification.FLAG_ONGOING_EVENT;
setContentView(R.layout.main);
}
@Override
public void onBackPressed() {
// TODO Auto-generated method stub
//super.onBackPressed();
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setIcon(R.drawable.ic_launcher);
builder.setTitle("是否退出");
//builder.setMessage("");
builder.setPositiveButton("退出", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
finish();
android.os.Process.killProcess(android.os.Process.myPid());
}
});
builder.setNeutralButton("隐藏", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addCategory(Intent.CATEGORY_HOME);
MainActivity.this.startActivity(intent);
}
});
builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
});
builder.create().show();
}
@Override
public void finish() {
// TODO Auto-generated method stub
super.finish();
nm.cancel(R.drawable.ic_launcher);
}
@Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
Log.e("MainActivity", "onDestroy");
nm.cancelAll();
}
@Override
protected void onStop() {
// TODO Auto-generated method stub
super.onStop();
nm.notify(R.drawable.ic_launcher, notifi);
}
感谢大神:http://www.cnblogs.com/bvin/archive/2012/08/18/2645584.html