我使用asynctask和notification实现了一个非常基本的服务演示:
public class ImageSendEmailService extends Service implements EmailCallback {
private static final int IMAGE_SEND_EMAIL_SERVICE_ID = 100;
@Override
public void onCreate() {
super.onCreate();
}
public int onStartCommand(Intent intent, int flags, int startId) {
if (intent.getAction().equals(ForegroundServiceTags.STARTFOREGROUND_ACTION.getValue())) {
EmailTask emailTask = new EmailTask();
emailTask.setCallback(this);
emailTask.execute();
}
return super.onStartCommand(intent, flags, startId);
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
public void onEmailSendingStarted() {}
@Override
public void onEmailSendingProgressUpdate(String progressMessage) {
Notification.Builder builder = new Notification.Builder(this);
builder.setContentTitle("Progress");
builder.setContentText(progressMessage);
builder.setTicker("Notification!");
builder.setWhen(System.currentTimeMillis());
builder.setSmallIcon(R.drawable.ic_launcher);
Notification notification = builder.build();
this.startForeground(IMAGE_SEND_EMAIL_SERVICE_ID, notification);
}
@Override
public void onEmailSendingCompleted() {
Notification.Builder builder = new Notification.Builder(this);
builder.setContentTitle("Progress");
builder.setContentText("Progress completed");
builder.setTicker("Notification!");
builder.setWhen(System.currentTimeMillis());
builder.setSmallIcon(R.drawable.ic_launcher);
Notification notification = builder.build();
this.startForeground(IMAGE_SEND_EMAIL_SERVICE_ID, notification);
}
}
public class EmailTask extends AsyncTask<Void, Void, Void> {
private EmailCallback callback = null;
private int progress = 0;
private String progressMessage = null;
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected Void doInBackground(Void... params) {
this.callback.onEmailSendingStarted();
for (this.progress = 0; this.progress <= 10; this.progress++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
this.progressMessage = String.valueOf((int) (100 * this.progress / 10)) + " %";
this.publishProgress();
}
return null;
}
@Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
this.callback.onEmailSendingProgressUpdate(this.progressMessage);
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
this.callback.onEmailSendingCompleted();
}
public void setCallback(EmailCallback callback) {
this.callback = callback;
}
}
正如您所看到的,我没有将通知设置为正在进行,但通知仍然无法解决。我希望只要用户决定将通知从通知栏中滑出,通知就会保留。
我该怎么做?
顺便说一下。当用户刷掉可能导致长时间运行过程的通知时,我还能发出警告吗?
答案 0 :(得分:3)
即使用户点击,我希望只要用户决定滑动就会保留通知 它远离通知栏。
builder.setAutoCancel(false);
也会使您的通知保持不变。用户必须将其滑开。
builder.setOngoing(true)
会使您的通知无法清除。
除非您有其他方法删除通知,否则不要将这两者结合使用。
当用户刷掉可能会导致死亡的通知时,我还可以发出警告 漫长的过程?
前台服务应该使用持续通知(因此用户不会通过轻扫无意中杀死它),这将在单击时启动活动。此活动可能包含以下内容:
在setContentIntent
搜索this article,了解如何通过点击通知启动活动。