Thursday, March 31, 2011

Get Android device ID, Settings.Secure.ANDROID_ID

Settings.Secure.ANDROID_ID is a 64-bit number (as a hex string) that is randomly generated on the device's first boot and should remain constant for the lifetime of the device. (The value may change if a factory reset is performed on the device.)

Settings.Secure.ANDROID_ID on Nexus One
Settings.Secure.ANDROID_ID on Android Emulator

ANDROID_ID seems a good choice for a unique device identifier. There are downsides as stated in Android Developers Blog, Identifying App Installations: First, it is not 100% reliable on releases of Android prior to 2.2 (“Froyo”). Also, there has been at least one widely-observed bug in a popular handset from a major manufacturer, where every instance has the same ANDROID_ID.

package com.exercise.AndroidId;

import android.app.Activity;
import android.os.Bundle;
import android.provider.Settings;
import android.widget.TextView;

public class AndroidId extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

TextView textAndroidId = (TextView)findViewById(R.id.androidid);
String AndroidId = Settings.Secure.getString(getContentResolver(),
Settings.Secure.ANDROID_ID);
textAndroidId.setText("My ID is: " + AndroidId);
}
}


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
<TextView
android:id="@+id/androidid"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>

No comments:

Post a Comment