我有一个应用程序,可在设备连接到互联网时通知用户。我使用workmanager,它工作正常,但仅当应用程序正在运行时!
它应该在人们未连接互联网时通知他们!怎么才能做到这一点!?
这是我的第一个活动:
public class WorkActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_work);
Intent intent = new Intent();
PendingIntent pendingIntent = PendingIntent.getActivity(WorkActivity.this,0,intent,0);
Constraints constraints = new Constraints.Builder().setRequiredNetworkType(NetworkType.CONNECTED).build();
NotifyWorker.pendingIntent = pendingIntent;
NotifyWorker.context = this;
OneTimeWorkRequest oneTimeWorkRequest = new OneTimeWorkRequest.Builder(NotifyWorker.class).setConstraints(constraints).build();
WorkManager workManager = WorkManager.getInstance();
workManager.enqueue(oneTimeWorkRequest);
}
}
这是我的工人班:
public class NotifyWorker extends Worker {
public static Context context;
public static PendingIntent pendingIntent;
@NonNull
@Override
public Result doWork() {
Log.i("wd","wd");
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context,"con")
.setSmallIcon(R.mipmap.ic_launcher)
.setLargeIcon(BitmapFactory.decodeResource(context.getResources(),R.mipmap.ic_launcher))
.setSmallIcon(R.drawable.logo)
.setContentTitle("Title")
.setContentText("Desc")
.setContentIntent(pendingIntent);
android.app.NotificationManager notificationManager =
(android.app.NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0 , notificationBuilder.build());
return Result.SUCCESS;
}
}
我很困惑:/请帮忙!