Android SharedPreference的用法及获得系统当前时间


Android SharedPreference的用法及获得系统当前时间

  1. package lxy.litsoft;  
  2.   
  3. import java.sql.Date;  
  4. import java.text.SimpleDateFormat;  
  5. import android.app.Activity;  
  6. import android.content.SharedPreferences;  
  7. import android.os.Bundle;  
  8. import android.util.Log;  
  9. import android.widget.Toast;  
  10.   
  11. public class AppMain extends Activity {  
  12.     private String currentTime;  
  13.     public void onCreate(Bundle savedInstanceState) {  
  14.         super.onCreate(savedInstanceState);  
  15.         setContentView(R.layout.main);  
  16.     }  
  17.   
  18.     protected void onResume() {  
  19.         super.onResume();  
  20.         //读取数据信息   
  21.           
  22.         //1.获取Preferences   
  23.         SharedPreferences prefrence = getSharedPreferences("configuration"0);  
  24.         //2.取出数据,如果没有存过数据,则读出的数据为"the fist time"这个参数   
  25.         String date = prefrence.getString("date","the fist time");  
  26.           
  27.         Log.d("test", date);  
  28.         Toast.makeText(AppMain.this"Last time you login is "+date, Toast.LENGTH_LONG).show();  
  29.   
  30.     }  
  31.       
  32.     protected void onPause() {  
  33.         super.onPause();  
  34.         /** 获得系统当前时间 **/  
  35.         SimpleDateFormat formatter = new SimpleDateFormat ("yyyy年MM月dd日 HH:mm:ss");      
  36.         Date curDate = new Date(System.currentTimeMillis());//获取当前时间     
  37.         currentTime = formatter.format(curDate);    
  38.           
  39.         /** 存放数据信息 **/  
  40.         //1.打开Preferences,名称为configuration,如果存在则打开它,否则创建新的Preferences   
  41.         SharedPreferences prefrence = getSharedPreferences("configuration"0);  
  42.         //2.让configuration处于编辑状态   
  43.         SharedPreferences.Editor editor = prefrence.edit();  
  44.         //3.存放数据   
  45.         editor.putString("date",currentTime);  
  46.         //4.完成提交   
  47.         editor.commit();  
  48.           
  49.         Toast.makeText(AppMain.this"ByeBye!!", Toast.LENGTH_LONG).show();  
  50.     }  
  51. }  

相关内容