获得Android手机唯一标识并保存在本地及从本地读出

获得Android手机唯一标识并保存在本地及从本地读出

每台手机的唯一AndroidId

String AndroIdKey = Settings.System.getString(getContentResolver(), Settings.System.ANDROID_ID);

保存AndroidId到本地

 public static void saveBitmap() throws IOException {
   // 创建目录
   //获取内部存储状态  
   String state = Environment.getExternalStorageState();
   //如果状态不是mounted,无法读写  
   if (!state.equals(Environment.MEDIA_MOUNTED)) {
     return;
   }
   String sdCardDir = Environment.getExternalStorageDirectory().getAbsolutePath();
   File appDir = new File(sdCardDir, "CaChe");
   if (!appDir.exists()) {
     appDir.mkdir();
   }
   String fileName = "dayu3421" + ".txt";
   file = new File(appDir, fileName);
   if (!file.exists()) {
     file.createNewFile();
   }
   //保存android唯一表示符
   try {
     FileWriter fw = new FileWriter(file);
     fw.write(MyApplication.getAndroIdKey());
     fw.flush();
     fw.close();
   } catch (FileNotFoundException e) {
     e.printStackTrace();
   } catch (IOException e) {
     e.printStackTrace();
 }

从本地读出来

public static String readKey() throws IOException {

  // 创建目录
  //获取内部存储状态  
  String state = Environment.getExternalStorageState();
  //如果状态不是mounted,无法读写  
  if (!state.equals(Environment.MEDIA_MOUNTED)) {
    return null;
  }
  String sdCardDir = Environment.getExternalStorageDirectory().getAbsolutePath();
  File appDir = new File(sdCardDir, "CaChe");
  if (!appDir.exists()) {
    appDir.mkdir();
  }
  String fileName = "dayu3421" + ".txt";
  file = new File(appDir, fileName);
  if (!file.exists()) {
    file.createNewFile();
  }
   BufferedReader reader = null;
  StringBuilder content=null;
  try {
    FileReader fr = new FileReader(file);
    content= new StringBuilder();
    reader = new BufferedReader(fr);
    String line;
    while ((line= reader.readLine())!=null){
      content.append(line);
    }
  } catch (Exception e) {
    e.printStackTrace();
  }finally {
    if (reader!=null){
      try {
        reader.close();
      }catch (IOException e){
        e.printStackTrace();
      }
    }
  }
 
  return content.toString();
}

你可能感兴趣的:(获得Android手机唯一标识并保存在本地及从本地读出)