//用于发送通知,ID和Name可以修改,确保唯一性即可
private static final int PUSH_NOTIFICATION_ID = (0x002);
private static final String PUSH_CHANNEL_ID = "PUSH_NOTIFY_ID";
private static final String PUSH_CHANNEL_NAME = "PUSH_NOTIFY_NAME";
private void testAsyncTaskAndNotify() {
final NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
//创建通知通道之前先判断sdk是否>=26,若是则需要创建channel才允许发送通知
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(PUSH_CHANNEL_ID, PUSH_CHANNEL_NAME, NotificationManager.IMPORTANCE_LOW);//如果为IMPORTANCE_HIGH则会一直弹出提示及提示音
if (manager != null) {
manager.createNotificationChannel(channel);
}
}
final Notification.Builder builder = new Notification.Builder(MainActivity.this);
final Notification notification = builder.build();
//下面通过创建一个匿名类执行异步任务,
AsyncTask<Void, Integer, Boolean> task = new AsyncTask() {
@Override
protected void onProgressUpdate(Object[] values) {
builder.setContentTitle("Download:");
builder.setContentText(values[0].toString() + "%");
builder.setSmallIcon(R.drawable.blue);
builder.setWhen(System.currentTimeMillis());
builder.setChannelId(PUSH_CHANNEL_ID);
if (manager != null) {
manager.notify(PUSH_NOTIFICATION_ID, notification);
}
super.onProgressUpdate(values);
if (values[0].equals(100)) {
manager.cancel(PUSH_NOTIFICATION_ID);
Toast.makeText(MainActivity.this, "download success!!!", Toast.LENGTH_SHORT).show();
onCancelled();
}
}
@Nullable
@Override
protected Object doInBackground(Object[] objects) {
for (int i = 0; i <= 100; i++) {
try {
Thread.sleep(1000);//线程休眠1000ms
} catch (InterruptedException e) {
e.printStackTrace();
}
publishProgress(i);
if (isCancelled()) {
break;
}
}
return null;
}
};
task.execute();//一定要记得execute,开启异步线程
}
遇到的问题:
- 进度条一直弹出提示及提示音
只需要把Notify的importance值从“IMPORTANCE_HIGH”改为“IMPORTANCE_LOW”即可。
参考链接:https://blog.csdn.net/qq_25749749/article/details/80448313