我只需要运行一次函数(当它晚上,更改图像视图的图像),当我在oncreate()中使用它时,它每次启动时都会运行 活性。
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startAnim();
}
}
private void startAnim(){
Date dateNow=new Date();
SimpleDateFormat sdf=new SimpleDateFormat("yy-MM-dd HH:mm:ss");
String night=String.format("%tF",dateNow)+" 19:00:00";
try {
Date dateNight=sdf.parse(night);
if(dateNow.after(dateNight)){
DisplayMetrics metric = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metric);
int width = metric.widthPixels; // 屏幕宽度(像素)
int height = metric.heightPixels; // 屏幕高度(像素)
RotateAnimation ra=new RotateAnimation(0,100,width/2,height/2-80);
ra.setDuration(4000);
sunMoon.startAnimation(ra);
} catch (ParseException e) {
e.printStackTrace();
}
}
}
答案 0 :(得分:1)
记录上次在文件中运行startAnim()
的时间。当您开始活动以决定是否运行startAnim()
时,请阅读此文件。
答案 1 :(得分:1)
共享首选项中的文件或商店。保存方法的示例:
public String reverseString( String str )
{
if(str.length()==1){
return str;
}
return str.charAt( str.length() - 1 ) + reverseString( str.substring( 0, str.length() - 1 ) );
}
// initialize pos to 0
public int getLargest( int[] arr, int pos )
{
int largest = arr[pos];
if ( pos + 1 >= arr.length ) {
return largest;
}
int second = getLargest( arr, pos + 1 );
return largest > second ? largest : second;
}
示例检查:
private void saveLastRanTime(String key, long lastRunTime) {
SharedPreferences prefs = getApplicationContext().getSharedPreferences(getPackageName(), Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putLong(key, lastRunTime); // Store the key somewhere instead of passing in each time
editor.apply();
}
这将使你的startAnim()方法看起来更像:
private boolean wasLastRunToday(String keyOfPreference) {
SharedPreferences prefs = getApplicationContext().getSharedPreferences(getPackageName(), Context.MODE_PRIVATE);
long lastRanAt = prefs.getLong(keyOfPreference, -1); // Save key somewhere..
if (lastRanAt == -1) { // In the event it was never saved before.
return false;
}
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(lastRanAt);
int dayLastRanAt = cal.get(Calendar.DAY_OF_YEAR);
cal.setTimeInMillis(System.currentTimeMillis());
int today = cal.get(Calendar.DAY_OF_YEAR);
return today == dayLastRanAt;
}