第三单元:双击退出,Notitfcation 通知
双击退出
实现的基本原理就是,当按下BACK键时,会被onKeyDown捕获,判断是BACK键,则执行exit方法。
判断用户两次按键的时间差是否在一个预期值之内,是的话直接直接退出,不是的话提示用户再按一次后退键退出。
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK ){
//判断用户两次按键的时间差是否在一个预期值之内,是的话直接直接退出,不是的话提示用户再按一次后退键退出。
if(System.currentTimeMillis() - exitTime > 2000){
Toast.makeText(this,"在点就退出",Toast.LENGTH_SHORT).show();
exitTime = System.currentTimeMillis();
//当返回true时,表示已经完整地处理了这个事件,并不希望其他的回调方法再次进行处理,而当返回false时,
// 表示并没有完全处理完该事件,更希望其他回调方法继续对其进行处理,
return true;
}else{
finish(); //结束当前activity
}
}
return super.onKeyDown(keyCode, event);
}
Notification通知
Notification.Builder builder = new Notification.Builder(this);
builder.setSmallIcon(R.mipmap.ic_launcher);
builder.setContentTitle("设置标题");
builder.setContentText("设置内容");
builder.setTicker("设置提示信息");
Notification build = builder.build();
final NotificationManager manager= (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
manager.notify(1,build);
自定义通知
Notification.Builder builder1 = new Notification.Builder(this);
builder1.setSmallIcon(R.mipmap.ic_launcher);
builder1.setContentTitle("设置标题");
builder1.setContentText("设置内容");
builder1.setTicker("设置提示信息");
RemoteViews remoteViews = new RemoteViews(getPackageName(),R.layout.activity_custom);
remoteViews.setImageViewResource(R.id.image,R.mipmap.ic_launcher);
remoteViews.setTextViewText(R.id.text,"what?");
//点击通知跳转页面
Intent intent = new Intent(MainActivity.this,Main2Activity.class);
PendingIntent activity = PendingIntent.getActivity(this, 10, intent, PendingIntent.FLAG_ONE_SHOT);
remoteViews.setOnClickPendingIntent(R.id.text,activity);
// builder1.setContentIntent(activity);
builder1.setCustomContentView(remoteViews);
Notification build1 = builder1.build();
NotificationManager manager1= (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
manager1.notify(2,build1);
break;
进度条通知
final NotificationManager manager2= (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
final Notification.Builder builder2 = new Notification.Builder(this);
builder2.setContentTitle("设置标题");
builder2.setSmallIcon(R.mipmap.ic_launcher);
final Timer timer = new Timer();
timer.schedule(new TimerTask() {
int progress;
@Override
public void run() {
builder2.setContentText("正在下载,当前进度"+progress);
builder2.setProgress(100,progress,false);
progress+=10;
manager2.notify(3,builder2.build());
if(progress==100){
builder2.setContentText("正在安装");
builder2.setProgress(0,0,true);
manager2.notify(3,builder2.build());
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
manager2.cancel(3);
timer.cancel();
}
}
},0,1000);