skip to Main Content

I want to uniquely identify a hardware device. How do I get the unique device ID in Flutter? I am using the device-info-plus plugin, but it doesn’t give an Android ID in recent versions. I will have to downgrade to a very old version for Android ID, and it’s causing other dependency issues, so I can’t do that.

This is my current code, but multiple users are getting the same device ID because of this:

if (Platform.isAndroid) {
  AndroidDeviceInfo androidInfo = await deviceInfo.androidInfo;
  deviceId = androidInfo.id;
  print('Running on ${androidInfo.id}');
}

Is there any way to get the unique device ID in Flutter? Please help, as it’s causing a major issue in our live project.

2

Answers


  1. Your approach is good with "https://pub.dev/packages/device_info_plus" however, there is no guarantee that the Id is truly unique and may vary depending on what the phone is going through. The ideal would be to combine this practice with the user’s unique id or the Wifi mac address or something else.

    Login or Signup to reply.
  2. This is not direct way for flutter to get device id. Using native to get user Device ID Get succesfully.

    1. Create new package and add on project

    this is new package android code:

    package com.example.flutter_androidid;
    import android.content.Context;
    import android.content.pm.PackageManager;
    import android.database.Cursor;
    import android.net.Uri;
    import android.os.Build;
    import android.os.Bundle;
    import android.provider.Settings;
    import android.telephony.TelephonyManager;
    import android.util.Log;
    import android.widget.Toast;
    
    import androidx.annotation.NonNull;
    import androidx.core.content.ContextCompat;
    
    import java.util.HashMap;
    import java.util.Map;
    
    import io.flutter.embedding.engine.plugins.FlutterPlugin;
    import io.flutter.plugin.common.MethodCall;
    import io.flutter.plugin.common.MethodChannel;
    import io.flutter.plugin.common.MethodChannel.MethodCallHandler;
    import io.flutter.plugin.common.MethodChannel.Result;
    
    /** FlutterAndroididPlugin */
     public class FlutterAndroididPlugin implements FlutterPlugin, 
      MethodCallHandler {
      private MethodChannel channel;
      private FlutterPluginBinding flutterPluginBinding;
    
      @Override
      public void onAttachedToEngine(@NonNull FlutterPluginBinding 
      flutterPluginBinding) {
        this.flutterPluginBinding = flutterPluginBinding; // Store 
      the 
      reference
        channel = new 
     MethodChannel(flutterPluginBinding.getBinaryMessenger(), 
     "flutter_androidid");
        channel.setMethodCallHandler(this);
      }
    
      @Override
       public void onMethodCall(@NonNull MethodCall call, @NonNull 
        Result 
       result) {
        if (call.method.equals("getPlatformVersion")) {
            result.success("Android " + Build.VERSION.RELEASE);
        } else if (call.method.equals("getSimInfo")) {
            Map<String, String> simInfo = getSimInfo();
            String data = getMyDeviceID(getContext());
            simInfo.put("GSF_ID",data);
            result.success(simInfo);
        } else {
            result.notImplemented();
        }
    }
    
     private Map<String, String> getSimInfo() {
        Map<String, String> simInfo = new HashMap<>();
        try {
            String androidId = 
       Settings.Secure.getString(getContext().getContentResolver(), 
       Settings.Secure.ANDROID_ID);
            simInfo.put("AndroidID", androidId != null ? androidId : "N/A");
            // Add more SIM-related information if needed
        } catch (SecurityException e) {
            handleException("IMEI access not permitted", e);
        } catch (Exception e) {
            handleException("An error occurred", e);
        }
        return simInfo;
    }
    
    private Context getContext() {
        return flutterPluginBinding.getApplicationContext();
    }
    
    private void handleException(String message, Exception e) {
        Toast.makeText(getContext(), message, Toast.LENGTH_SHORT).show();
        Log.e("Error", message, e);
    }
    
     private String getMyDeviceID(Context context) {
        try {
            String uriString = "content://com.google.android.gsf.gservices";
            String ID_KEY = "android_id";
            String params[] = {ID_KEY};
            Uri uri = Uri.parse(uriString);
            Cursor cursor = context.getContentResolver().query(uri, null, 
          null, params, null);
    
            if (cursor != null) {
                if (cursor.moveToFirst() && cursor.getColumnCount() >= 2) {
                    String cursorStr = cursor.getString(1);
                    StringBuilder hexBuilder = new StringBuilder();
                            for (byte b : cursorStr.getBytes()) {
                                String hex = String.format("%02X", b);
                                hexBuilder.append(hex);
                            }
                      Log.d("Cursor", hexBuilder.toString());
                    return hexBuilder.toString();
                } else {
                    return "Error: Unable to retrieve Device ID";
                }
            } else {
                return "Error: Cursor is null";
            }
        } catch (Exception e) {
            handleException("An error occurred", e);
            return "Error: Other Exception";
        }
    }
    
        @Override
       public void onDetachedFromEngine(@NonNull FlutterPluginBinding 
       binding) {
        channel.setMethodCallHandler(null);
        flutterPluginBinding = null; // Release the reference
         }
       }
    

    and this is package Lib file code. Create a method channel.

    import 'package:flutter/services.dart';
    
     class FlutterAndroidid {
     static const MethodChannel _channel = 
     MethodChannel('flutter_androidid');
    
    Future<String> getPlatformVersion() async {
    try {
      final String result = await 
      _channel.invokeMethod('getPlatformVersion');
      return result;
    } catch (e) {
      return 'Failed to get platform version: $e';
       }
     }
    
    Future<Map?> getSimInfo() async {
    try {
      final Map? result = await _channel.invokeMapMethod('getSimInfo');
      return result;
    } catch (e) {
      return {'error': 'Failed to get SIM info: $e'};
         }
       }
     }
    

    This is flutter code.

    Map simInfo = {};
    //get android id
    FlutterAndroidid nativeMethods = FlutterAndroidid();
    getData() async {
    simInfo = await nativeMethods.getSimInfo() ?? {};
    print("device_id": simInfo["AndroidID"] ?? "");
    setState(() {});
     }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search