创建一个后台服务,该服务启动后在一个新的线程中持续地以 1 秒间隔更新 通知栏,点击“启动服务”按钮后,服务启动,通知栏上出现图标并按照预设间隔交 替更新;点击“停止服务”按钮后,服务停止,通知栏图标被清除。 交替显示两个不同的图标,实验的代码
时间: 2023-10-02 13:06:03 浏览: 112
以下是一个实现上述功能的简单示例代码:
```java
public class NotificationService extends Service {
private static final int NOTIFICATION_ID = 1;
private static final int INTERVAL = 1000; // 1秒间隔
private NotificationManager mNotificationManager;
private boolean mIsRunning;
private boolean mIsSwitched; // 切换标记
private Handler mHandler;
private Runnable mUpdateRunnable = new Runnable() {
@Override
public void run() {
switchNotificationIcon(); // 切换通知栏图标
mHandler.postDelayed(this, INTERVAL);
}
};
@Override
public void onCreate() {
super.onCreate();
mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
mHandler = new Handler();
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
startForeground(NOTIFICATION_ID, createNotification()); // 启动前台服务
startUpdate(); // 启动更新线程
mIsRunning = true;
return START_STICKY;
}
@Override
public void onDestroy() {
stopUpdate(); // 停止更新线程
mNotificationManager.cancel(NOTIFICATION_ID); // 取消通知栏图标
mIsRunning = false;
super.onDestroy();
}
private void startUpdate() {
mHandler.post(mUpdateRunnable);
}
private void stopUpdate() {
mHandler.removeCallbacks(mUpdateRunnable);
}
private Notification createNotification() {
NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_notification_1)
.setContentTitle(getString(R.string.notification_title))
.setContentText(getString(R.string.notification_text))
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setOngoing(true);
return builder.build();
}
private void switchNotificationIcon() {
Notification notification = createNotification();
if (mIsSwitched) {
notification.icon = R.drawable.ic_notification_1;
} else {
notification.icon = R.drawable.ic_notification_2;
}
mNotificationManager.notify(NOTIFICATION_ID, notification);
mIsSwitched = !mIsSwitched;
}
public static Intent getIntent(Context context) {
return new Intent(context, NotificationService.class);
}
public boolean isRunning() {
return mIsRunning;
}
}
```
在按钮的点击事件中,可以通过以下代码启动或停止服务:
```java
if (!mService.isRunning()) {
startService(NotificationService.getIntent(this));
} else {
stopService(NotificationService.getIntent(this));
}
```
阅读全文