Android 久坐提醒:使用 NotificationCompat.Builder 设置振动提醒
Android 久坐提醒:使用 NotificationCompat.Builder 设置振动提醒
长时间坐着对健康有害,因此拥有一个提醒我们定期起身活动的应用程序非常有用。本文将指导您使用 Android 的 NotificationCompat.Builder 类创建一个简单的久坐提醒应用程序,该应用程序会发出带有自定义振动模式的通知。
代码示例
以下是完整的代码:javaimport android.app.Activity;import android.app.NotificationChannel;import android.app.NotificationManager;import android.content.Context;import android.os.Build;import android.os.Bundle;import android.os.Handler;import android.view.View;import android.widget.Button;
import androidx.core.app.NotificationCompat;
public class jiuzuo extends Activity { private static final long REMINDER_INTERVAL = 60 * 60 * 1000; // 1小时 private static final int NOTIFICATION_ID = 1; private static final String CHANNEL_ID = 'sit_reminder_channel'; private Handler handler; private Runnable reminderRunnable;
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.jiuzuo);
Button startButton = findViewById(R.id.start_button); Button stopButton = findViewById(R.id.stop_button);
handler = new Handler(); reminderRunnable = new Runnable() { @Override public void run() { showReminder(); handler.postDelayed(this, REMINDER_INTERVAL); } };
startButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startReminder(); } });
stopButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { stopReminder(); } }); }
private void startReminder() { handler.postDelayed(reminderRunnable, REMINDER_INTERVAL); }
private void stopReminder() { handler.removeCallbacks(reminderRunnable); }
private void showReminder() { createNotificationChannel();
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID) .setSmallIcon(R.drawable.ic_notification) .setContentTitle('久坐提醒') .setContentText('您已长时间未活动,请起身活动一下。') .setVibrate(new long[]{0, 1000, 1000, 1000, 1000}) .setAutoCancel(true);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); notificationManager.notify(NOTIFICATION_ID, builder.build()); }
private void createNotificationChannel() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { CharSequence name = 'Sit Reminder'; String description = '久坐提醒通知'; int importance = NotificationManager.IMPORTANCE_DEFAULT; NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, importance); channel.setDescription(description);
NotificationManager notificationManager = getSystemService(NotificationManager.class); notificationManager.createNotificationChannel(channel); }
原文地址: https://www.cveoy.top/t/topic/QoP 著作权归作者所有。请勿转载和采集!