gpt4 book ai didi

java - Android 中如何让服务在启动后一直保持 Activity 状态,直到应用程序被关闭或终止?

转载 作者:行者123 更新时间:2023-12-02 11:46:16 25 4
gpt4 key购买 nike

我正在开发 Android 应用程序,因此我正在启动一个带有警报的服务:

public void scheduleLocationCheckerAlarm() {
Intent intent = new Intent(getApplicationContext(), LocationCheckerReceiver.class);
final PendingIntent pIntent = PendingIntent.getBroadcast(this, LocationCheckerReceiver.REQUEST_CODE, intent, PendingIntent.FLAG_UPDATE_CURRENT);
long firstMillis = System.currentTimeMillis();
AlarmManager alarm = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
alarm.setInexactRepeating(AlarmManager.RTC_WAKEUP, firstMillis, 600000, pIntent);
}

位置检查接收器:

public class LocationCheckerReceiver extends BroadcastReceiver {
public static final int REQUEST_CODE = 12345;

@Override
public void onReceive(Context context, Intent intent) {
Intent i = new Intent(context, LocationNotificator.class);
context.startService(i);
}

服务:

public class LocationNotificator extends Service {
public LocationNotificator() {
}

@Override
public IBinder onBind(Intent intent) {
throw new UnsupportedOperationException("Not yet implemented");
}

public int onStartCommand(Intent intent, int flags, int startId) {
Log.d("Location checker", "Service running");
//My code is here
return START_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
Log.d("Location checker", "Service destroyed");
}

因此,我希望该服务每 1 分钟检查一次某些内容,并且始终运行,即使用户关闭了应用程序也是如此。

最佳答案

您必须调用 startForeground(FOREGROUND_ID, buildForegroundNotification(filename)); 以确保您的服务持续运行。此外,这还会从您的应用程序发布一条通知,向用户显示服务状态。请关注reference 。这是代码:

public class LocationNotificator extends Service {
private static int FOREGROUND_ID=1338;
public LocationNotificator() {
}

@Override
public IBinder onBind(Intent intent) {
throw new UnsupportedOperationException("Not yet implemented");
}

public int onStartCommand(Intent intent, int flags, int startId) {
Log.d("Location checker", "Service running");
//My code is here

startForeground(FOREGROUND_ID,
buildForegroundNotification(filename));
stopForeground(true);
return START_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
Log.d("Location checker", "Service destroyed");
}
private Notification buildForegroundNotification(String filename) {
NotificationCompat.Builder b=new NotificationCompat.Builder(this);

b.setOngoing(true);

b.setContentTitle("Some Title")
.setContentText("some File name")
.setSmallIcon(android.R.drawable.stat_sys_download)
.setTicker("downloading");

return(b.build());
}

关于java - Android 中如何让服务在启动后一直保持 Activity 状态,直到应用程序被关闭或终止?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48183591/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com