可以使用以下代码示例获取设备ID:
import android.os.Build;
String deviceId = Build.SERIAL;
然而,从Android 10开始,应用程序无法访问非resettable标识符,例如设备ID。因此,建议您使用Android管理API的设备详细信息来获取唯一标识符。您可以使用以下代码示例:
import com.google.android.gms.common.api.ApiException;
import com.google.android.gms.tasks.Tasks;
import com.google.android.gms.tasks.Task;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnCanceledListener;
import com.google.android.gms.tasks.CancellationTokenSource;
import com.google.android.gms.tasks.CancellationToken;
import com.google.android.gms.awareness.Awareness;
import com.google.android.gms.awareness.fence.AwarenessFence;
import com.google.android.gms.awareness.fence.DetectedActivityFence;
import com.google.android.gms.awareness.fence.FenceQueryResponse;
import com.google.android.gms.awareness.snapshot.DetectedActivityResult;
import com.google.android.gms.awareness.snapshot.GoogleApiClientAwareness;
import com.google.android.gms.tasks.CancellationTokenSource;
import com.google.android.gms.tasks.Tasks;
void getDeviceDetails() {
Task task = Awareness.getSnapshotClient(context)
.getDetectedActivity();
task.addOnSuccessListener(new OnSuccessListener() {
@Override
public void onSuccess(DetectedActivityResult result) {
int activity = result.getActivityRecognitionResult()
.getMostProbableActivity().getType();
// You can use the activity type to generate a unique device ID
}
});
task.addOnFailureListener(new OnFailureListener() {
// Handle errors here
});
}