android studio开发环境下,实现一个后台计时器,时间到了,通知栏提示计时结束
2023-09-12
先说,该程序不用貌似不用root,因为我没有不root的设备,其次该软件不能关闭,即手机设备上查看最近任务列表的时候是可以看到的,确实不难,看一下就懂了,和iApp的代码居然很像很像
创建一个新的Android项目
打开Android Studio。
创建一个新的Android项目,取名为supertimer
创建一个后台服务类:
在你的项目中创建一个新的Java类,表示后台服务。例如,创建一个名为TimerService.java的类。
具体如何点击,在自己的包名位置右键

选择Java Class

输入类名为TimerService.java 或者不加java后缀也可以,选中class就行

在TimerService.java,除了第一行的代码保留,其余代码均复制如下代码,1秒是1000毫秒,那么测试的时候建议把60000改成3000,方便看到效果
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Intent;
import android.os.Build;
import android.os.CountDownTimer;
import android.os.IBinder;
import androidx.annotation.Nullable;
import androidx.core.app.NotificationCompat;
public class TimerService extends Service {
private CountDownTimer countDownTimer;
private static final int NOTIFICATION_ID = 1;
private static final String CHANNEL_ID = "TimerChannel";
@Override
public void onCreate() {
super.onCreate();
createNotificationChannel();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
startTimer();
return START_STICKY;
}
private void startTimer() {
countDownTimer = new CountDownTimer(3000, 1000) { // 60秒
@Override
public void onTick(long millisUntilFinished) {
// 计时逻辑
}
@Override
public void onFinish() {
// 计时结束时发送通知
showNotification("计时结束");
}
};
countDownTimer.start();
}
private void createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(
CHANNEL_ID,
"Timer Channel",
NotificationManager.IMPORTANCE_DEFAULT
);
NotificationManager manager = getSystemService(NotificationManager.class);
manager.createNotificationChannel(channel);
}
}
private void showNotification(String contentText) {
Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
.setSmallIcon(android.R.drawable.ic_lock_idle_alarm) // 使用系统默认的闹钟图标
.setContentTitle("计时器")
.setContentText(contentText)
.build();
NotificationManager manager = getSystemService(NotificationManager.class);
manager.notify(NOTIFICATION_ID, notification);
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
}在AndroidManifest.xml中注册服务:
在AndroidManifest.xml文件中添加服务的声明。在<application>标签内添加以下内容:
<service android:name=".TimerService" android:enabled="true" android:exported="false" />

配置权限:
在AndroidManifest.xml中确保添加了必要的权限。在<manifest>标签内添加以下内容:
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" /

最后一部,在MainActivity.java中,将代码放入对应位置,其为界面载入事件,软件打开界面加载的时候会自动执行
Intent serviceIntent = new Intent(this, TimerService.class); startService(serviceIntent);

发表评论: