我的问题是我想制作一个带有 IntentService 的 SDK(要包含在不同应用程序项目中的库项目)。此 Intent 服务与 AlarmManager 一起安排为每 2 秒重复一次(实际上这将是每 2 分钟一次):
Intent startServiceIntent = new Intent("com.my.package.MY_UNIQUE_ACTION");
startServiceIntent.setClass(context, InstalledAppsService.class);
PendingIntent pendingIntent = PendingIntent.getService(context, 0, startServiceIntent, PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, 2000, 2000, pendingIntent);
因此,当我从启动服务的应用程序中使用此方法时:
private boolean isMyServiceRunning() {
Intent startServiceIntent = new Intent("com.my.package.MY_UNIQUE_ACTION");
startServiceIntent.setClass(context, InstalledAppsService.class);
boolean alarmUp = (PendingIntent.getService(context, 0,
startServiceIntent,
PendingIntent.FLAG_NO_CREATE) != null);
return alarmUp;
}
如果服务已安排,则返回 true。我不希望使用相同的 SDK 从不同的应用程序启动相同的服务。我希望使用 SDK 为所有应用程序提供一项服务,我只需要检查每个应用程序是否正在运行此服务。
但是当我使用相同的方法但来自不同的应用程序时,它返回 false。 这是我的 list :
<service
android:name="com.test.services.InstalledAppsService"
android:exported="true"
android:process="com.test.InstalledAppsService">
<intent-filter>
<action android:name="com.my.package.MY_UNIQUE_ACTION" />
</intent-filter>
</service>
我应该向 list 添加一些东西还是使用 ActivityManager 检查进程是否存在?目前我从两个不同的服务中得到两个日志标签。
我想要的是:启动服务、完成工作、处理服务。我不需要它总是运行。目前,警报管理器会执行此操作,但使用的是单独的进程。
这是我的服务:
public class InstalledAppsService extends IntentService {
private static final String TAG = "services.InstalledAppsService";
public InstalledAppsService() {
super("InstalledAppsService");
}
protected void onHandleIntent(Intent intent) {
}
public void onCreate() {
super.onCreate();
}
public void onDestroy() {
super.onDestroy();
}
}
最佳答案
所以问题是我的服务完成它的工作太快了,当下一个应用程序检查服务是否正在运行时,它已经完成了它的工作并从系统中销毁了。 AlarmManager 也没有检查是否有任何计划的选项。
所以我做了一个定时器任务来完成这项工作,这样系统就不会在完成工作时破坏服务。
服务代码可以在这里看到: Here
并使用这个方法:
private boolean isServiceRunning(Class<?> serviceClass) {
ActivityManager manager = (ActivityManager)
context.getSystemService(Context.ACTIVITY_SERVICE);
for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (serviceClass.getName().equals(service.service.getClassName())) {
return true;
}
}
return false;
}
我可以检测服务是否正在运行。
关于android - 如何跨多个应用程序共享服务并检查它是否已经运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25837454/