我想在用户打开应用程序时运行一项服务,然后只要每 1 分钟安装一次应用程序就让它运行。该服务将通过调用 API 来检查是否有新订单,如果有,则会显示通知。
我做了一些研究,发现 JobIntentService 和 Broadcast Reciever 是我需要用来解决我的问题,但我无法将它们放在一起使其工作。如果有人可以提供详细的解决方案,我将不胜感激。我也想知道对于我的问题是否有比这更好的方法?下面是我设法编写的代码。
后台服务
public class BackgroundService extends JobIntentService {
private static final String TAG = BackgroundService.class.getName();
private static final int JOB_ID = 1;
private NotificationManager notificationManager;
public static void enqueueWork(Context context, Intent intent) {
enqueueWork(context, BackgroundService.class, JOB_ID, intent);
}
@Override
public void onCreate() {
super.onCreate();
Log.d(TAG, getClass().getSimpleName() + "#onCreate");
notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
}
@Override
public void onDestroy() {
super.onDestroy();
Log.d(TAG, "Running in background!");
sendBroadcast(new Intent(getApplicationContext(), BackgroundService.class));
}
@Override
protected void onHandleWork(@NonNull Intent intent) {
Log.d(TAG, getClass().getSimpleName() + "#onHandleWork!");
APIInterface service = RetrofitClientInstance.getRetrofitInstance().create(APIInterface.class);
Call<List<OrdersModel>> call = service.getAllOrders(Services.CONSUMER_KEY,Services.CONSUMER_SECRET);
call.enqueue(new Callback<List<OrdersModel>>() {
@Override
public void onResponse(@NonNull Call<List<OrdersModel>> call,@NonNull Response<List<OrdersModel>> response) {
if (response.body() != null) {
for (OrdersModel orders : response.body()){
if (orders.getStatus().equals("processing")){
sendNotification("#" + orders.getNumber());
}
}
}
}
@Override
public void onFailure(@NonNull Call<List<OrdersModel>> call,@NonNull Throwable t) {
Log.d(TAG, getClass().getSimpleName() + "Network Error!");
}
});
}
private void sendNotification(String title) {
Uri defaultSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Intent intent = new Intent(this, GetOrdersActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
Notification.Builder notificationBuilder = new Notification.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher_round)
.setContentTitle(title)
.setAutoCancel(true)
.setSound(defaultSound)
.setContentText("New Order")
.setContentIntent(pendingIntent)
.setWhen(System.currentTimeMillis())
.setPriority(Notification.PRIORITY_HIGH)
.setCategory(Notification.CATEGORY_MESSAGE);
notificationManager.notify(0, notificationBuilder.build());
Log.d("GoParty", "Notification sent ----- ");
}
}
广播接收器
public class NotificationReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Intent notificationIntent = new Intent(context, BackgroundService.class);
BackgroundService.enqueueWork(context, notificationIntent);
}
}