Java 在后台一小时后如何执行一些代码?
每当用户选择按钮时,我使用后台服务播放音频。但我想做的是每60分钟播放一次音频。我该怎么做呢 我已经尝试过使用处理程序,将计时器设置为60分钟,然后执行播放音频的代码行,但只要用户选择按钮,它就会自动播放音频Java 在后台一小时后如何执行一些代码?,java,android,Java,Android,每当用户选择按钮时,我使用后台服务播放音频。但我想做的是每60分钟播放一次音频。我该怎么做呢 我已经尝试过使用处理程序,将计时器设置为60分钟,然后执行播放音频的代码行,但只要用户选择按钮,它就会自动播放音频 public class BackgroundService extends Service { private MediaPlayer player; private Boolean state = false; @Nullable @Override
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();
}
}
尝试循环处理程序
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);
使用广播接收机是可能的
使用您的时间间隔设置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);
在Manifest.xml中指定您的BroadcastReceiver
请添加更多详细信息,如您当前如何使用该服务来了解情况。您是否已查看以下链接,以了解可能的重复项:
<receiver android:name="com.package.YourReceiver">
<intent-filter>
<action android:name="Your Broadcast Receiver" />
</intent-filter>
</receiver>