出于测试目的,我制作了一项会发出蜂鸣声的服务
每 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但没有
得到它。对于安卓来说相对较新...
请帮助我,我非常绝望:)谢谢,!