无论用户何时选择按钮,我都在使用后台服务来播放音频。但是我想做的是每60分钟播放一次音频。我将如何去做呢?
我已经尝试使用处理程序并将计时器设置为60分钟,然后执行播放音频的代码行,但是只要用户选择按钮,它就会自动播放音频。
public class BackgroundService extends Service {
private MediaPlayer player;
private Boolean state = false;
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
//i would like to play this audio every 60minute in the background
player = MediaPlayer.create(BackgroundService.this, Settings.System.DEFAULT_RINGTONE_URI);
//this will make the ringtone continuously playing
player.setLooping(true);
//staring the player
player.start();
return START_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
//stopping the player when service is destroyed
player.stop();
}
}
答案 0 :(得分:1)
BroadcastReceiver
设置您的时间间隔AlarmManager
Intent intent = new Intent("Your Broadcast Receiver");
PendingIntent pendingIntent = PendingIntent.getBroadcast(mContext, 0, intent, 0);
AlarmManager alarmManager = (AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, time_interval, pendingIntent);
在BroadcastReceiver
中指定您的Manifest.xml
<receiver android:name="com.package.YourReceiver">
<intent-filter>
<action android:name="Your Broadcast Receiver" />
</intent-filter>
</receiver>
答案 1 :(得分:0)
尝试循环处理程序
final Handler handler = new Handler();
int count = 0;
final Runnable runnable = new Runnable() {
public void run() {
// do the task here
Log.d(TAG, "runn test");
if (count++ < 5)
//will continue to loop 5 times
handler.postDelayed(this, 5000);
}
};
// trigger first time
handler.post(runnable);