1

出于测试目的,我提供了每 1 分钟发出一次哔声的服务。(还没有客户端-服务器接口)。开机时会发出哔哔声,但是当它进入睡眠状态时,哔哔声会停止。

我正在制作一个必须定期轮询服务器的应用程序。

为此,我正在尝试创建一个将在后台持续运行的服务,每 1 分钟轮询一次服务器,然后根据服务器的回复生成任务栏通知。

我有一个带有两个按钮的测试活动,一个用于启动,另一个用于停止服务。还有一个名为 S_PS_PollService 的服务类

'Start Activity' 按钮的 setOnClickListener 包含:

Thread pollServiceThread = new Thread() {
  public void run() {
    startService(new Intent(MM_MainMenu.this,
    S_PS_PollService.class));
  }
};

pollServiceThread.start();

“停止活动”按钮只有:

stopService(new Intent(MM_MainMenu.this, S_PS_PollService.class));

以下是 S_PS_PollService 类中的方法:

public void onCreate() {
 pollSound = MediaPlayer.create(this, R.raw.chirp);
 alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
 Intent myIntent = new Intent(this, S_PS_PollService.class);
 pendingIntent = PendingIntent.getService(this, 0, myIntent, 0);
 // for wake lock
 pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
 wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "My Tag")
 // for calendar
 calendar = Calendar.getInstance();
}

开始:

public void onStart(Intent intent, int startId) {
 super.onStart(intent, startId);

 wl.acquire();

 pollSound.start();

 calendar.setTimeInMillis(System.currentTimeMillis());
 calendar.add(Calendar.MILLISECOND, 60000);
 alarmManager.set(AlarmManager.RTC_WAKEUP,
 calendar.getTimeInMillis(), pendingIntent);

 wl.release();
}

每当警报启动时,就会执行 onStart() 方法,发出哔声并设置新警报。但它只有在屏幕打开时才有效。

我已经尝试过https://github.com/commonsguy/cwac-wakeful但没有得到它。对安卓来说比较新...

请帮助我,我非常绝望:) 谢谢,!

4

3 回答 3

0

这终于对我有用。从https://github.com/commonsguy/cwac-wakeful下载 CWAC-WakefulIntentService.jar

在您的项目中添加一个类

import com.commonsware.cwac.wakeful.WakefulIntentService;

public class WakeService extends WakefulIntentService {

    public WakeService(String name) {

        super(name);

    }
    @Override
    protected void doWakefulWork(Intent intent) {
    }
}

现在在您想要重复循环并唤醒设备的代码中添加以下行

WakefulIntentService.sendWakefulWork(this, S_WS_WakeService.class);

于 2012-03-30T08:29:44.137 回答
0

您希望按照代码的建议获取部分唤醒锁(只要在设备上进入睡眠状态,就让 CPU 继续运行)。

问题是您可能在启动时被覆盖会释放唤醒锁。你想在 onDestroy 中释放你的wakeLock .. 一旦你的服务完成运行。

于 2012-03-06T22:18:04.933 回答
0

你必须使用 AlarmManager,stackoverflow 上有很多帖子。

于 2012-02-17T14:37:04.450 回答