我正在开发一个 Android 应用程序,它在应用程序运行时在后台跟踪一些事情。我是 Android 的初学者,所以我会尝试描述我想做什么。
设置:MainActivity、TrackerActivity、TrackerService(该服务包含唤醒锁)和TrackerServiceWakeupReciever
这在 TrackerService 关闭时运行。
public class TrackerServiceWakeupReciever extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Intent serviceIntent = new Intent();
serviceIntent.setAction("com.example.android.TrackerService");
serviceIntent.putExtra("action", "checkSound");
context.startService(serviceIntent);
}
}
从 TrackerActivity 启动服务的代码:
Intent serviceIntent = new Intent();
serviceIntent.setAction("com.example.android.TrackerService");
startService(serviceIntent);
进入 App 时 MainActivity 正在启动,当 TrackerActivity 从 MainActivity 启动时 TrackerService 在 TrackerActivity 的 onCreate 中启动。该服务运行恰好 10 秒后关闭。然后 TrackerServiceWakeupReciever 再次启动服务并再次运行 10 秒并循环。
为什么它只在 10 秒内运行?我注意到,如果我快速返回 MainActivity 并按下睡眠按钮,那么该服务将继续运行。即使设备退出睡眠状态,服务也会按照我的意愿运行。
如何解决这个问题呢?花了一周时间才弄明白。我想这很简单:)
提前致谢。马丁