我能够每隔15分钟发送定期通知,但我无法更改通知的内容。我有一个字符串数组,但工作管理器始终发送相同的项。例如,它先取值为“four”,然后一直发送“four”。
1- 我在strings.xml中定义了一个字符串数组
<string-array name="numbers">
<item>one</item>
<item>two</item>
<item>three</item>
<item>four</item>
<item>five</item>
</string-array>
2 - 我的MainActivity类
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
public static final String KEY_TASK_DESC = "key_task_desc";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String[] list = getResources().getStringArray(R.array.numbers);
Random random = new Random();
int number = random.nextInt(list.length);
Data data = new Data.Builder()
.putString(KEY_TASK_DESC, list[number]).build();
PeriodicWorkRequest periodicWorkRequest = new PeriodicWorkRequest
.Builder(MyWorker.class, 15, TimeUnit.MINUTE)
.setInputData(data)
.build();
WorkManager.getInstance().enqueue(periodicWorkRequest);
}}
3 - MyWorker类包含displayNotif(String inputData)方法
public class MyWorker extends Worker {
public MyWorker(@NonNull Context context, @NonNull WorkerParameters workerParams) {
super(context, workerParams);
}
@NonNull
@Override
public Result doWork() {
String inputData = getInputData().getString(MainActivity.KEY_TASK_DESC);
displayNotif(inputData);
return Result.success();
}
private void displayNotif(String inputData) {
NotificationManager manager =
(NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel("notif",
"notif", NotificationManager.IMPORTANCE_DEFAULT);
manager.createNotificationChannel(channel);
}
NotificationCompat.Builder builder = new NotificationCompat.Builder(getApplicationContext(), "notif")
.setContentText(inputData)
.setSmallIcon(R.mipmap.ic_launcher);
manager.notify(1, builder.build());
}}