我的主要活动有一个按钮,用于打开您提交数据的表单活动。提交数据后,Button将消失。如何让它在当天的每个小时开始出现?
例如,如果我在晚上7:05提交数据,该按钮将消失,直到晚上8点。当我按下按钮再次提交数据时,该按钮将消失,直到晚上9点,依此类推。
答案 0 :(得分:0)
提交数据时获取当前时间戳并将其存储在sharedPref中。当您启动活动时,请检查sharedPref并将其与设备的当前时间进行比较。
答案 1 :(得分:0)
尝试使用后台服务并在1小时后设置通知间隔 按钮单击后按钮启动服务,而不是使用此后台服务进行任何操作
BackgroundService.java
public class BackgroundService extends Service {
public static final int notify = 100000; //interval between two services(Here Service run every 1 Minute)
private Timer mTimer = null; //timer handling
Context context;
ScheduledExecutorService scheduleTaskExecutor;
View view;
Handler mHandler = new Handler();
/** indicates how to behave if the service is killed */
int mStartMode;
/** interface for clients that bind */
IBinder mBinder;
/** indicates whether onRebind should be used */
boolean mAllowRebind;
/** Called when the service is being created. */
@Override
public void onCreate() {
super.onCreate();
context = getApplicationContext();
Toast.makeText(this, "Service is created", Toast.LENGTH_SHORT).show();
if (mTimer != null) // Cancel if already existed
mTimer.cancel();
else
mTimer = new Timer(); //recreate new
mTimer.scheduleAtFixedRate(new TimeDisplay(), 0, notify); //Schedule task
}
/** The service is starting, due to a call to startService() */
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return super.onStartCommand(intent, flags, startId);
}
@Override
public IBinder onBind(Intent intent){
return null;
}
/** Called when all clients have unbound with unbindService() */
@Override
public boolean onUnbind(Intent intent) {
return mAllowRebind;
}
/** Called when a client is binding to the service with bindService()*/
@Override
public void onRebind(Intent intent) {
}
/** Called when The service is no longer used and is being destroyed */
@Override
public void onDestroy() {
super.onDestroy();
mTimer.cancel(); //For Cancel Timer
Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show();
}
//class TimeDisplay for handling task
class TimeDisplay extends TimerTask {
@Override
public void run() {
// run on another thread
mHandler.post(new Runnable() {
@Override
public void run() {
// Toast.makeText(this, "Service Start",Toast.LENGTH_LONG).show();
}
});
}
}
}
AndroidManifest.xml
<service android:name=".BackgroundService.KametSportsEventsService" android:enabled="true" />
//开始后台服务
startService(new Intent(getBaseContext(),BackgroundService.class));
//停止后台服务
stopService(new Intent(getBaseContext(),BackgroundService.class));