Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
//License from project: Open Source License 

import java.security.SecureRandom;

import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;

public class Main {
    /**
     * Generates a device ID.
     */
    public synchronized static String getDeviceId(Context context) {
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
        String deviceId = preferences.getString("device_id", null);
        if (deviceId == null) {
            String chars = "123456789ABCDEFGHJKLMNPQRSTUVWXY";
            byte[] randomBytes = new byte[12];
            new SecureRandom().nextBytes(randomBytes);
            StringBuilder builder = new StringBuilder(12);
            for (int i = 0; i < 12; i++) {
                builder.append(chars.charAt((randomBytes[i] & 0xFF) % chars.length()));
            }
            deviceId = builder.toString();
            preferences.edit().putString("device_id", deviceId).apply();
        }
        return deviceId;
    }
}