要安排通知:
FirebaseJobDispatcher dispatcher = new FirebaseJobDispatcher(new GooglePlayDriver(this));
Job myJob = dispatcher.newJobBuilder()
.setService(MyJobService.class) // the JobService that will be called
.setTag("my-unique-tag") // uniquely identifies the job
.setTrigger(Trigger.executionWindow(0, 5))
.build();
dispatcher.mustSchedule(myJob);
工作服务:
public class MyJobService extends JobService
{
@Override
public boolean onStartJob(JobParameters job)
{
// Do some work here
sendNotification("TEST");
return true; // Answers the question: "Is there still work going on?"
}
@Override
public boolean onStopJob(JobParameters job)
{
return false; // Answers the question: "Should this job be retried?"
}
private void sendNotification(String messageBody)
{
Log.d("TEST","Notification: " + messageBody);
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
PendingIntent.FLAG_ONE_SHOT);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("Job executed")
.setContentText(messageBody)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}
}
作业按原样执行(我可以在 logcat 中看到“TEST”)。但是,通知不会出现(没有抛出任何错误)。
你知道为什么通知不会触发吗?难道我做错了什么?