写一段java代码 在android12 中 间隔5秒 循环发送通知
时间: 2024-03-10 07:44:06 浏览: 31
以下是一个简单的 Java 代码示例,可以在 Android 12 中循环发送通知,并且每隔5秒钟发送一次通知:
```
import android.app.Notification;
import android.app.NotificationManager;
import android.content.Context;
public class NotificationSender {
private static final int NOTIFICATION_ID = 1;
private static final int DELAY_IN_MILLIS = 5000;
private final NotificationManager notificationManager;
private final Notification.Builder notificationBuilder;
public NotificationSender(Context context) {
notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationBuilder = new Notification.Builder(context)
.setContentTitle("My Notification Title")
.setContentText("My Notification Text")
.setSmallIcon(R.drawable.notification_icon);
}
public void startSendingNotifications() {
new Thread(new Runnable() {
@Override
public void run() {
while (true) {
try {
Thread.sleep(DELAY_IN_MILLIS);
} catch (InterruptedException e) {
e.printStackTrace();
}
notificationManager.notify(NOTIFICATION_ID, notificationBuilder.build());
}
}
}).start();
}
}
```
在 MainActivity 类中,你可以创建一个 NotificationSender 实例,并调用 startSendingNotifications() 方法来启动通知发送循环:
```
public class MainActivity extends AppCompatActivity {
private NotificationSender notificationSender;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
notificationSender = new NotificationSender(this);
notificationSender.startSendingNotifications();
}
}
```
请注意,这只是一个简单的示例,真实的应用程序可能需要更加复杂和精细的通知发送逻辑,例如在特定的时间段内发送通知,或者根据用户的偏好设置来发送不同类型的通知等。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)