服务暂停屏幕锁定

时间:2012-02-16 09:56:28

标签: android android-service alarmmanager wakelock

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

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

为此,我正在努力创建一个不断发展的服务 在后台运行,每隔1分钟轮询一次服务器,然后再根据 在服务器的回复中,它应生成一个任务栏通知。

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

“开始活动”按钮的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();
}

ONSTART:

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,但没有 得到它。 Android的相对较新...

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

3 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

您希望获取部分唤醒锁定(在设备上输入睡眠时让CPU保持运行),如代码所示。

问题是您可能会在启动时重写唤醒锁定。你想在服务运行完毕后在onDestroy中释放你的wakeLock。

答案 2 :(得分: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);