Java tutorial
//package com.java2s; //License from project: LGPL import android.content.Context; import android.content.SharedPreferences; import android.net.wifi.WifiInfo; import android.net.wifi.WifiManager; import android.preference.PreferenceManager; import android.telephony.TelephonyManager; public class Main { /** * @Thach * @Description: get and save deviceId into sharePreference * @param context * @return deviceId */ public static String getDeviceId(Context context, String keyPref) { String deviceId = null; if (context != null) { // Get from sharePref first deviceId = onGetPref(context, keyPref); // If this is first time if (deviceId == null) { TelephonyManager telephonyManager; telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); deviceId = telephonyManager.getDeviceId(); // Get deviceId with other method - MAC address if (deviceId == null) { deviceId = initMacAddress(context); } } // save to preference onSavePref(context, keyPref, deviceId); } return deviceId; } /** * @Thach * @Description: on get data to SharedPref with given key * @param context * @param key * @param msg data will be save */ public static String onGetPref(Context context, String key) { SharedPreferences pre = PreferenceManager.getDefaultSharedPreferences(context); return pre.getString(key, null); } /** * @Thach @SK29 * @Init MAC address and save to preference * @param context * @return */ private static String initMacAddress(Context context) { // INIT macAddress String macAddress; WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); if (wifiManager.isWifiEnabled()) { // WIFI ALREADY ENABLED. GRAB THE MAC ADDRESS HERE WifiInfo info = wifiManager.getConnectionInfo(); macAddress = info.getMacAddress(); } else { // ENABLE THE WIFI FIRST wifiManager.setWifiEnabled(true); // WIFI IS NOW ENABLED. GRAB THE MAC ADDRESS HERE WifiInfo info = wifiManager.getConnectionInfo(); macAddress = info.getMacAddress(); // NOW DISABLE IT AGAIN wifiManager.setWifiEnabled(false); } if (macAddress == null) { macAddress = android.os.Build.ID; } return macAddress; } /** * @Thach * @Description: on save data to SharedPref with given key * @param context * @param key * @param msg data will be save */ public static void onSavePref(Context context, String key, String msg) { SharedPreferences pre = PreferenceManager.getDefaultSharedPreferences(context); pre.edit().putString(key, msg).commit(); } }