所以我写了这段 Job Service Class,它的目的是在后台访问 Internet,下载一些东西,并以 15 秒的间隔显示 Notification(稍后会增加到 45 分钟,不用担心):
import android.app.PendingIntent;
import android.app.job.JobParameters;
import android.app.job.JobService;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.util.Log;
import androidx.core.app.NotificationCompat;
import androidx.core.app.NotificationManagerCompat;
import java.util.ArrayList;
import java.util.HashMap;
public class NotificationService extends JobService {
DownloadNotification d;
@Override
public boolean onStartJob(JobParameters params) {
d=new DownloadNotification();
d.execute(params);
return true;
}
@Override
public boolean onStopJob(JobParameters params) {
return false;
}
private class DownloadNotification extends AsyncTask<JobParameters,Void,JobParameters>
{
ArrayList<HashMap<String,String>> resN;
ArrayList<HashMap<String,String>> resP;
SharedPreferences sp;
@Override
protected void onPreExecute() {
sp=getSharedPreferences("eTutionPro",MODE_PRIVATE);
super.onPreExecute();
}
@Override
protected JobParameters doInBackground(JobParameters... params) {
resN=Connectivity.query("SELECT * FROM `notices` WHERE noticeID>? ORDER BY noticeID DESC LIMIT 15",""+sp.getInt("LastNotificationID",-1));
return params[0];
}
@Override
protected void onPostExecute(JobParameters pam) {
Log.d("Thread","From Thread NOTICE RESULT : "+(resN!=null?""+resN.size():"null"));
SharedPreferences.Editor prefEditor = sp.edit();
if(resN!=null) {
boolean b=true;
for (HashMap<String, String> i : resN) {
if(b)
{
b=false;
prefEditor.putInt("LastNotificationID", Integer.parseInt(i.get("noticeID")));
prefEditor.commit();
}
Intent intent = new Intent(getApplicationContext(), ViewNotice.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), 0, intent, 0);
NotificationCompat.Builder builder = new NotificationCompat.Builder(getApplicationContext(), "101")
.setSmallIcon(R.drawable.logo)
.setContentTitle(i.get("noticeTitle"))
.setContentText(i.get("noticeBody"))
.setContentIntent(pendingIntent)
.setPriority(NotificationCompat.PRIORITY_DEFAULT);
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(getApplicationContext());
notificationManager.notify(Integer.parseInt(i.get("noticeID")), builder.build());
}
}
jobFinished(pam,false);
}
}
}
当应用程序处于活动状态或处于最近状态时,一切正常。
但是当应用程序从最近删除时,除了 NotificationService 类中的 Async 类,即 DownloadNotification 中的 doInBackground 无法访问 Internet 下载数据外,一切都正常工作。
自定义函数 Connectivity.query(String,String...) 在无法获取数据时返回 null(按设计)。我猜这个类没有问题,因为一切正常。不知道该怎么办。