具有警报管理器和内部广播接收器的Android长时间运行服务

tun*_*ing 2 service android broadcastreceiver alarmmanager

我有一个使用自定义Connection类(扩展线程)到硬件控制器的服务.当用户更喜欢时,我希望永久保持这种联系.当Android设备失去互联网连接,在Wi-Fi之间切换等时,我已经有了处理代码.

为了保持连接,控制器要求您在每5分钟内与其通话.我目前在Connection类中启动一个在while()中运行的线程,并检查系统时间和上次通信的时间,当> 4分钟时它会请求状态.由于某种原因,在不同时间通信不会及时发生.即,在5分钟后发生.据我所知,服务不会死,但控制器的"Ping"迟到了.当我将手机插入充电器(或调试器)时,不会发生这种情况.此外,当我将服务移动到前台时,行为是相同的.

手机进入睡眠状态时手机是否会减速?

有没有更好的办法?

我认为它是AlarmManger,但是我无法在服务中使用内部类.我尝试使用API​​演示作为起点,但我似乎无法弄清楚如何注册广播接收器.我试图以编程方式注册接收器,而不更改清单.

public class DeviceConnectionService extends Service {

    @Override
    public void onCreate() {
        Intent intent = new Intent(this, PingConnection.class);
        intent.setAction("KEEP_CONNECTION_ALIVE");
        PendingIntent sender = PendingIntent.getBroadcast(this,
            0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        // We want the alarm to go off 30 seconds from now.
        long firstTime = SystemClock.elapsedRealtime();
        firstTime += 15*1000;
        // Schedule the alarm!
        AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
        am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
                firstTime, 15*1000, sender);
        // register to listen to the Alarm Manager
        if (mPingConnectionReceiver == null) {
            mPingConnectionReceiver = new PingConnection();
            getApplicationContext().registerReceiver(mPingConnectionReceiver,
             new IntentFilter("KEEP_CONNECTION_ALIVE"));
        }
    }

    // ...

    public class PingConnection extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (dBug) Log.i("PingConnection", "Pinging Controller");
            // do real work here
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Com*_*are 5

手机进入睡眠状态时手机是否会减速?

手机在进入睡眠状态时关闭其处理器.这就是"睡眠"的定义.

我认为它是AlarmManger,但是我无法在服务中使用内部类.我尝试使用API​​演示作为起点,但我似乎无法弄清楚如何注册广播接收器.我试图以编程方式注册接收器,而不更改清单.

这是一种不寻常的方法AlarmManager.话虽这么说,因为你拒绝在任何细节中描述"有麻烦",所以很难帮助你.

摆脱getApplicationContext()(你不需要它,在这种情况下真的不想要它).我会在触摸之前注册接收器AlarmManager.在开始制作之前,请选择包含您的包名称的操作名称(例如,com.something.myapp.KEEP_CONNECTION_ALIVE).

除此之外,请检查LogCat是否有警告.


UPDATE

在您的LogCat中,您应该发出警告,AlarmManager抱怨无法与您交谈BroadcastReceiver.

更换:

Intent intent = new Intent(this, PingConnection.class);
intent.setAction("KEEP_CONNECTION_ALIVE");
Run Code Online (Sandbox Code Playgroud)

有:

Intent intent = new Intent("KEEP_CONNECTION_ALIVE");
Run Code Online (Sandbox Code Playgroud)

你可能会有更好的运气.