스마트기기개발관련/안드로이드 개발

Android 디바이스의 고유 번호 (Identifier) 획득 시 고려 해야 할 점, air 액션스크립트 안드로이드 개발 고유 밴더 아이디 얻기 관련

AlrepondTech 2014. 11. 20. 16:19
반응형

 

 

 

=================================

=================================

=================================

 

 

 

 

 

출처: http://stunstun.tistory.com/184

 

안드로이드 개발 시에 디바이스 정보를 획득 하는 일들이 있는데, 그 중 에서도 디바이스의 고유한 번호를 획득 하는 일은 빈번 하게 발생 한다. 예를 들면 고유한 디바이스의 정보를 저장 해 어플리케이션의 설치 상태를 확인 한다 던가

다양한 인증 서비스를 제공 할 때 보다 쉽게 서비스를 이용 할 수 있도록 게스트 로그인 같은 기능을 제공 할 때 디바이스에 대한 식별이 필요 할 때가 있다.

 

하지만 Android SDK 는 API Level 이 업데이트 되면서 이에 대한 정보를 획득 하는 데에 대한 이슈가 있는데, 간단 하게 나마 정리 해보고자 한다.

 

TelephonyManager

 

 

지난 시간 동안 일반적인 경우에는 Hardware 단위로 제공 하는 identifier 를 통해 디바이스의 고유 번호를 획득 하고는 했다. TelephonyManager 클래스를 통해 Phone의 IMEI, MEID 또는 ESN 값을 획득 한다.

예를 들면 아래와 같다.

 

TelephonyManager manager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
manager.getDeviceId();

하지만 TelephonyManager  를 통한 방법은 아래와 같은  이슈가 있다.


| Non - Phone : 핸드폰 번호를 갖고 있지 않는 태블릿 이나 Wifi 만을 제공 하는 디바이스는 TelephonyManager 를 통한 디바이스 번호를 획득 하지 못 할 수도 있다.

 

| Persistence : 한번 생성된 번호에 대한 지속 여부를 보장 할 수 가 없다. 디바이스가 공장 초기화 될 경우를 예로 들 수 있다. 뿐만 아니라, 현재 까지 몇몇 버그들이 report 되어 왔다. 안드로이드 디바이스는 제조사 마다 다양하게 커스터마이징 하기 때문에 000000000000000 같이 의미 없는 값이나 null 이 반환 되기도 한다.

 

| Privilege : 디바이스에 접근 하기 위해  READ_PHONE_STATE  권한 설정이 필요 하다.



Mac address

 

Wifi 나 blue-tooth 를 사용 하는 디바이스에서 획득 가능 하다. 하지만 디바이스의 고유 번호를 획득 하기 위한 용도로는 추천 되지 않는다. Wifi 가 항상 켜져 있다고 보장 할 수 없을 뿐만 아니라 모든 기기가 고유번호를 반환 하는 것이 아니기 때문이다.

 

 

Serial Number

 

안드로이드의 API Level 9 (진저브레드 2.3) 이후 부터 제공 하는 고유 번호 로서 TelephonyManager 클래스를 통한 획득 보다는 안전 하다고 할 수 있지만 2.3 미만의 Version 에서는 문제가 발생 할 수 가 있다.

 

API Level 9 부터 제공 하기 때문에 @SuppressLint("NewApi") 를 추가 해야 되기 때문에 아래와 같이 Java reflection을 통해 획득 하는 것이 좋다.

 

private static String getDeviceSerialNumber() {
 try {
   return (String) Build.class.getField("SERIAL").get(null);
 } catch (Exception ignored) {
   return null;
 }
}



ANDROID_ID

 

가장 명확한 방법이며, 디바이스가 최초 Boot 될때 생성 되는 64-bit 값이다. ANDROID_ID는 디바이스의 고유한 번호를 획득 하기 위해 가장 좋은 선택이 될 수 있다.

 

Settings.Secure.ANDROID_ID

하지만 ANDROID_ID 또한 단점이 있는데, Proyo 2.2 이전 Version 에는 100% 디바이스 고유 번호를 획득 한다고는 보장 할 수 없으며, 몇몇 Vendor 에서 출하된 디바이스에 동일한 고유 번호가 획득 된다는 버그가 report 됐다는 것이다.

 

 

 

결론

 

지금 까지 안드로이드 플랫폼에서 디바이스를 구별하기 위한 고유한 번호를 획득 하는 방법을 알아 보았는데, 물리적으로 100% 보장 할 수 없다는 것이고, 이로 인해 결코 쉽지 않은 일이라는 것을 알 수 있었다. 가장 좋은 방법은 ANDROID_ID를 통해 획득 하는 방법이며, 다른 해결책을 혼용 해 사용하는 것도 좋을 방법 일 것이다. 여기에 위에 나열된 예상 되는 이슈 들과 같은 만일의 사태에 대한 대비책을 만들어 놓는 것도 좋을 것 이다.

 

참조 : http://android-developers.blogspot.kr/2011/03/identifying-app-installations.html#uds-search-results

 

 

 

=================================

=================================

=================================

 

 

 

 

출처: http://android-developers.blogspot.kr/2011/03/identifying-app-installations.html#uds-search-results

Identifying App Installations

 

[The contents of this post grew out of an internal discussion featuring many of the usual suspects who’ve been authors in this space. — Tim Bray]

In the Android group, from time to time we hear complaints from developers about problems they’re having coming up with reliable, stable, unique device identifiers. This worries us, because we think that tracking such identifiers isn’t a good idea, and that there are better ways to achieve developers’ goals.

Tracking Installations


It is very common, and perfectly reasonable, for a developer to want to track individual installations of their apps. It sounds plausible just to call TelephonyManager.getDeviceId() and use that value to identify the installation. There are problems with this
: First, it doesn’t work reliably (see below). Second, when it does work, that value survives device wipes (“Factory resets”) and thus you could end up making a nasty mistake when one of your customers wipes their device and passes it on to another person.

To track installations, you could for example use a UUID as an identifier, and simply create a new one the first time an app runs after installation. Here is a sketch of a class named “Installation” with one static method Installation.id(Context context). You could imagine writing more installation-specific data into the INSTALLATION file.

public class Installation {
    private static String sID = null;
    private static final String INSTALLATION = "INSTALLATION";

    public synchronized static String id(Context context) {
        if (sID == null) {  
            File installation = new File(context.getFilesDir(), INSTALLATION);
            try {
                if (!installation.exists())
                    writeInstallationFile(installation);
                sID = readInstallationFile(installation);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
        return sID;
    }

    private static String readInstallationFile(File installation) throws IOException {
        RandomAccessFile f = new RandomAccessFile(installation, "r");
        byte[] bytes = new byte[(int) f.length()];
        f.readFully(bytes);
        f.close();
        return new String(bytes);
    }

    private static void writeInstallationFile(File installation) throws IOException {
        FileOutputStream out = new FileOutputStream(installation);
        String id = UUID.randomUUID().toString();
        out.write(id.getBytes());
        out.close();
    }
}

Identifying Devices

Suppose you feel that for the needs of your application, you need an actual hardware device identifier. This turns out to be a tricky problem.

In the past, when every Android device was a phone, things were simpler: TelephonyManager.getDeviceId() is required to return (depending on the network technology) the IMEI, MEID, or ESN of the phone, which is unique to that piece of hardware.

However, there are problems with this approach:

  • Non-phones: Wifi-only devices or music players that don’t have telephony hardware just don’t have this kind of unique identifier.
  • Persistence: On devices which do have this, it persists across device data wipes and factory resets. It’s not clear at all if, in this situation, your app should regard this as the same device.
  • Privilege:It requires READ_PHONE_STATE permission, which is irritating if you don’t otherwise use or need telephony.
  • Bugs: We have seen a few instances of production phones for which the implementation is buggy and returns garbage, for example zeros or asterisks.

Mac Address

It may be possible to retrieve a Mac address from a device’s WiFi or Bluetooth hardware. We do not recommend using this as a unique identifier. To start with, not all devices have WiFi. Also, if the WiFi is not turned on, the hardware may not report the Mac address.

Serial Number

Since Android 2.3 (“Gingerbread”) this is available via android.os.Build.SERIAL. Devices without telephony are required to report a unique device ID here; some phones may do so also.

ANDROID_ID

More specifically, Settings.Secure.ANDROID_ID. This is a 64-bit quantity that is generated and stored when the device first boots. It is reset when the device is wiped.

ANDROID_ID seems a good choice for a unique device identifier. There are downsides: 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.

Conclusion

For the vast majority of applications, the requirement is to identify a particular installation, not a physical device. Fortunately, doing so is straightforward.

There are many good reasons for avoiding the attempt to identify a particular device. For those who want to try, the best approach is probably the use of ANDROID_ID on anything reasonably modern, with some fallback heuristics for legacy devices.

 

 

 

 

 

=================================

=================================

=================================

 

 

 

 

출처: http://siakak.wordpress.com/2014/07/14/%EC%8B%9C%EA%B0%84%EC%9D%84-%EC%95%84%EB%81%BC%EB%8A%94-%EC%95%88%EB%93%9C%EB%A1%9C%EC%9D%B4%EB%93%9C-%EA%B0%9C%EB%B0%9C-%EC%B9%B4%ED%86%A1-sdk-%EC%9D%98-%EC%95%88%EB%93%9C%EB%A1%9C%EC%9D%B4/

 

안녕하세요? 시간을 아껴주고 아끼는 블로그 쥔장입니다.

모든 정보들이 인터넷을 통해 연결되면서 오히려 양질의 컨텐츠를 얻는 데에 너무 많은 시간이 걸리곤 합니다.

그래서 저는 저와 독자들의 시간을 아껴주는 블로깅을 하고자 합니다.

아마 주요 주제는 프로그래밍, 맛집, 게임, 여행, 교육 등이 될 것 같습니다.

개발 쪽으로는 첫 글입니다~ 안드로이드 기기에서 TelephonyManager.getDeviceId() 가 넘어오지 않을 때가 있어서 알아본 자료입니다.

많은 도움 되시기를!!

—————-

TelephonyManager.getDeviceId() 가 참 유용하기는 한데, 핸드폰에서만 되지 태블릿이나 웨어러블 기기에서는 null 값을 넘긴다고 합니다.

그러면 도대체 어떻게 디바이스를 정확하게 구분할 수 있을까요? 여러 자료들을 찾아보던 중, 카톡 SDK 에 다음 함수가 있음을 알 수 있었습니다.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
public static String getDeviceUUID(final Context context) {
    final SharedPreferencesCache cache = Session.getAppCache();
    final String id = cache.getString(PROPERTY_DEVICE_ID);
 
    UUID uuid = null;
    if (id != null) {
        uuid = UUID.fromString(id);
    } else {
        final String androidId = Secure.getString(context.getContentResolver(), Secure.ANDROID_ID);
        try {
            if (!"9774d56d682e549c".equals(androidId)) {
                uuid = UUID.nameUUIDFromBytes(androidId.getBytes("utf8"));
            } else {
                final String deviceId = ((TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE)).getDeviceId();
                uuid = deviceId != null ? UUID.nameUUIDFromBytes(deviceId.getBytes("utf8")) : UUID.randomUUID();
            }
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
 
        Bundle bundle = new Bundle();
        bundle.putString(PROPERTY_DEVICE_ID, uuid.toString());
        cache.save(bundle);
    }
 
    return uuid.toString();
}

내용은 다음과 같습니다.

 

  1. 먼저 가장 정확하다고 알려진 ANDROID_ID 를 가져옵니다.
  2. 하지만 예전 어떤 기기에서 특정 번호로만 나오던 버그가 있었다고 합니다. 이에 대한 예외처리를 해줍니다.
  3. ANDROID_ID 가 없으면 getDeviceID() 를 사용합니다.
  4. 둘 다 실패하면, 랜덤하게 UUID 를 발생시킵니다.
  5. 4번은 랜덤한 값이지만 preference 에 저장해두고 사용하기 때문에 삭제하고 재설치하지 않는 이상 랜덤한 넘버를 두번 만들지는 않습니다.

 

(참고자료 1) 안드로이드 개별 디바이스를 번역하는 방법 (안드로이드 공식 블로그의 번역)http://huewu.blog.me/110107222113

(참고자료 2) IMEI, MEID, ESN, IMSI 등에 대해 자세히 나옴 http://www.webs.co.kr/index.php?mid=adnroid&sort_index=readed_count&order_type=asc&page=2&document_srl=38470

(참고자료 3) Stack Overflow 의 방대한 문답들 http://stackoverflow.com/questions/2785485/is-there-a-unique-android-device-id

(참고자료 4) 카카오톡 안드로이드 SDK https://developers.kakao.com/docs/android

 

 

 

=================================

=================================

=================================

 

 

 

 

출처: http://stackoverflow.com/questions/7320473/get-udid-of-android-device-via-adobe-air

 

 

How can I get UDID of Android device via adobe air? I want to get UDID of my device with Android OS installed on it via Adobe AIR. How can I do it? Thanx!
share|improve this question
 

2 Answers

It doesn't look like it's in the APIs. You can try generating a random code and storing it on the device. This has been asked before here: Get unique identifier (MAC address, UDID, etc...) in Adobe AIR for iOSand recently here: http://www.flexdeveloper.eu/forums/actionscript-3-0/detecting-unique-device-number-in-adobe-flex-like-udid-of-iphone-device/
share|improve this answer
 
    
so, I can only get MAC address but not UDID?? –  yozhik Sep 6 '11 at 13:32
    
Through the Adobe Flex platform, yes. You can generate and store your own random value, though, which accomplishes just about the same thing in most cases. –  Rob Sep 6 '11 at 13:42
you can use TelephonyManager.getDeviceId() to get udid of a device.
Add this permission:
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
you can refer this doc:
http://developer.android.com/reference/android/telephony/TelephonyManager.html#getDeviceId%28%29
also check:
Unique ID of Android Device

 

 

=================================

=================================

=================================

 

 

 

 

안드로이드 유니크 아이디 알아내기...

1. IMEI : 전화가 있는 안드로이드 기기일 경우, 아닌 경우는 00000000 이거나 null 이거나... Tizz에선 null...

TelephonyManager TelephonyMgr = (TelephonyManager)getSystemService(TELEPHONY_SERVICE);

String m_szImei = TelephonyMgr.getDeviceId(); // Requires READ_PHONE_STATE

 

2. DEVICE ID : IMEI 처럼 만들기.. 대부분의 경우 유효

String m_szDevIDShort = "35" + //we make this look like a valid IMEI

         Build.BOARD.length()%10+ Build.BRAND.length()%10 + 

         Build.CPU_ABI.length()%10 + Build.DEVICE.length()%10 + 

         Build.DISPLAY.length()%10 + Build.HOST.length()%10 + 

         Build.ID.length()%10 + Build.MANUFACTURER.length()%10 + 

         Build.MODEL.length()%10 + Build.PRODUCT.length()%10 + 

         Build.TAGS.length()%10 + Build.TYPE.length()%10 + 

         Build.USER.length()%10 ; //13 digits


3.  Android ID : 신뢰할 수 없음

String m_szAndroidID = Secure.getString(getContentResolver(), Secure.ANDROID_ID);

 

4. MAC 주소 이용 : 에뮬레이터에선 null...

WifiManager wm = (WifiManager)getSystemService(Context.WIFI_SERVICE);

String m_szWLANMAC = wm.getConnectionInfo().getMacAddress();

 

5. Bluetooth MAC 주소 이용 : android.permission.ACCESS_WIFI_STATE 필요... 없으면 null

BluetoothAdapter m_BluetoothAdapter = null; // Local Bluetooth adapter

m_BluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

String m_szBTMAC;

try  {

m_szBTMAC = m_BluetoothAdapter.getAddress();

} catch (Exception e)  {

m_szBTMAC = null;

}

 

6. 위의 것을 모두 합쳐 만든 ID : MD5 이용

String m_szLongID = m_szImei + m_szDevIDShort + m_szAndroidID+ m_szWLANMAC + m_szBTMAC;

MessageDigest m = null;

try {

m = MessageDigest.getInstance("MD5");

} catch (NoSuchAlgorithmException e) {

e.printStackTrace();

m.update(m_szLongID.getBytes(),0,m_szLongID.length());

byte p_md5Data[] = m.digest();

 

String m_szUniqueID = new String();

for (int i=0;i<p_md5Data.length;i++) {

int b =  (0xFF & p_md5Data[i]);

// if it is a single digit, make sure it have 0 in front (proper padding)

if (b <= 0xF) m_szUniqueID+="0";

// add number to string

m_szUniqueID+=Integer.toHexString(b); 

}

m_szUniqueID = m_szUniqueID.toUpperCase();

 

출처 : http://www.pocketmagic.net/?p=1662

 

 

 

=================================

=================================

=================================

 

 

 

안드로이드 유니크 ID를 얻기 위한 매니패스트 설정 또는 air 개발씨 xml 설정

 

출처: https://gist.github.com/sessionm-docs/720f437f9a6a77bd2ffe

 

Android manifest file for Adobe AIR Native Extension

 

123456789101112131415161718192021222324252627282930313233343536
 
<manifest android:installLocation="auto">
<!-- SessionM NOTE: These permissions are required for SessionM -->
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<!-- SessionM NOTE: These permissions are optional -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
 
<uses-feature android:required="true" android:name="android.hardware.touchscreen.multitouch"/>
<application android:enabled="true" android:debuggable="true" >
<activity android:excludeFromRecents="false">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<activity android:theme="@android:style/Theme.Translucent"
android:name="sessionm.flex.InitActivityActivity">
</activity>
<activity android:name="com.sessionm.ui.SessionMActivity"
android:configChanges="keyboard|orientation|screenSize"
android:theme="@android:style/Theme.Black.NoTitleBar.Fullscreen"
android:windowSoftInputMode="adjustPan" >
</activity>
<receiver android:name="com.sessionm.api.ConnectionReceiver">
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE">
</action>
</intent-filter>
</receiver>
</application>
</manifest>

 

 

=================================

=================================

=================================

 

 

 

출처: https://github.com/freshplanet/ANE-DeviceId

 

 

Provides access to the device unique id.
 branch: master 

 README.md

Air Native Extension to access a device unique id (iOS + Android)

This is an Air native extension that gives you access to a device unique id and an advertiser unique id. It has been developed by FreshPlanet.

Build script

Should you need to edit the extension source code and/or recompile it, you will find an ant build script (build.xml) in the build folder:

cd /path/to/the/ane/build #edit the build.properties file to provide your machine-specific paths ant 

Reference

Authors

This ANE has been written by Arnaud Bernard. It belongs to FreshPlanet Inc. and is distributed under the Apache Licence, version 2.0.

Join the FreshPlanet team - GAME DEVELOPMENT in NYC

We are expanding our mobile engineering teams.

FreshPlanet is a NYC based mobile game development firm and we are looking for senior engineers to lead the development initiatives for one or more of our games/apps. We work in small teams (6-9) who have total product control. These teams consist of mobile engineers, UI/UX designers and product experts.

Please contact Tom Cassidy (tcassidy@freshplanet.com) or apply at http://freshplanet.com/jobs/

 

 

 

=================================

=================================

=================================

 

 

 

 

출처: http://stackoverflow.com/questions/2480288/how-can-i-programmatically-obtain-the-number-of-the-android-phone-with-the-api

TelephonyManager tMgr = (TelephonyManager)mAppContext.getSystemService(Context.TELEPHONY_SERVICE); String mPhoneNumber = tMgr.getLine1Number();
Required Permission:
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
share|improve this answer
 
22  
Requires permission READ_PHONE_STATE, but otherwise perfect –  jkap Mar 19 '10 at 20:29
81  
Actually, not so perfect. Last time I tried this method, it reported the phone number that my phone originally had, before my old mobile number was ported over to it. It probably still does, as the Settings app still shows that defunct number. Also, there are reports that some SIMs cause this method to return null. That being said, I'm not aware of a better answer. –  CommonsWare Mar 19 '10 at 20:37
4  
Mark is right. If the intent to use something that uniquely identifies phone i'd use getDeviceId() which will return IMEA for GSM. –  Alex Volovoy Mar 19 '10 at 20:40
13  
(I think you mean IMEI...?) –  ChaimKut Jan 27 '11 at 14:11
13  
Well, i tested it on Nexus One with Android OS 2.2 and it returns null –  Omar Rehman May 21 '11 at 10:50
 
There is no guaranteed solution to this problem because the phone number is not physically stored on all SIM-cards, or broadcasted from the network to the phone. This is especially true in some countries which requires physical address verification, with number assignment only happening afterwards. Phone number assignment happens on the network - and can be changed without changing the SIM card or device (e.g. this is how porting is supported).
I know it is pain, but most likely the best solution is just to ask the user to enter his/her phone number once and store it.
share|improve this answer
 
8  
In order to verify the taken number, you can send an sms (containing a code) to the number and control the response by putting a listener on "android.provider.Telephony.SMS_RECEIVED". that way you can make sure that the number is correct and working –  Hossein Shahdoost Jun 29 '13 at 12:02
    
Creative solution, but you might want to let the user know that you are doing it just in case they are being charged for that. –  Norman H Dec 18 '13 at 20:17
1  
Is there any provider that charges for receiving simple text messages?! –  ThiefMaster Mar 29 at 20:01
2  
Yes, absolutely. Before I added texting to my plan, I was charged $0.30 per received text message. Rogers in Canada. –  John Kroetch Apr 7 at 17:34
Update: This answer is no longer available as Whatsapp had stopped exposing the phone number as account name, kindly disregard this answer. =================================================================================
There is actually an alternative solution you might want to consider, if you can't get it through telephony service.
As of today, you can rely on another big application Whatsapp, using AccountManager. Millions of devices have this application installed and if you can't get the phone number via TelephonyManager, you may give this a shot.
Permission:
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
Code:
AccountManager am = AccountManager.get(this); Account[] accounts = am.getAccounts(); for (Account ac : accounts) { String acname = ac.name; String actype = ac.type; // Take your time to look at all available accounts System.out.println("Accounts : " + acname + ", " + actype); }
Check actype for whatsapp account
if(actype.equals("com.whatsapp")){ String phoneNumber = ac.name; }
Of course you may not get it if user did not install Whatsapp, but its worth to try anyway. And remember you should always ask user for confirmation.
share|improve this answer
 
    
I just saw this today when I was messing around with accounts. It's pretty bad that the number is exposed like that. Of course, you need the GET_ACCOUNTS permission and at that point the user probably doesn't care what permissions the app has. –  jargetz Feb 28 at 0:09
4  
This solution is out of date, Whatsapp doesn't save the phone number on the acount name anymore, do you know where whatsapp saving the phone number after the new update? –  Cohelad Mar 17 at 11:47
    
@Cohelad thanks for updating me, i'll have a check later and cross this answer out after confirmation, meanwhile i've no idea where do they save the number –  Chor WaiChun Mar 18 at 1:27
private String getMyPhoneNumber(){ TelephonyManager mTelephonyMgr; mTelephonyMgr = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE); return mTelephonyMgr.getLine1Number(); } private String getMy10DigitPhoneNumber(){ String s = getMyPhoneNumber(); return s != null && s.length() > 2 ? s.substring(2) : null; }
Code taken from http://www.androidsnippets.com/get-my-phone-number
share|improve this answer
 
    
@JaredBurrows because of "s.substring(2)". –  Cookie Monster Feb 13 at 10:35
6  
I don't understand why people vote up because this solution isn't helpful because getLine1Number() can send NULL if your number is not stored so substring(2) will throws an exception!!!! –  Rafael Ruiz Tabares Apr 29 at 16:03
This is a more simplified answer:
public String getMyPhoneNumber() { return ((TelephonyManager) getSystemService(TELEPHONY_SERVICE)) .getLine1Number(); }
share|improve this answer
 
11  
nothing in some phone! –  thecr0w Aug 7 '12 at 6:55
Just want to add a bit here to above explanations in the above answers. Which will save time for others as well.
In my case this method didn't returned any mobile number, an empty string was returned. It was due to the case that I had ported my number on the new sim. So if I go into the Settings>About Phone>Status>My Phone Number it shows me "Unknown".
share|improve this answer
 
Although it's possible to have multiple voicemail accounts, when calling from your own number, carriers route you to voicemail. So, TelephonyManager.getVoiceMailNumber() or TelephonyManager.getCompleteVoiceMailNumber(), depending on the flavor you need.
Hope this helps.
share|improve this answer
 
3  
there is no "getCompleteVoiceMailNumber" function , plus the getVoiceMailNumber() returns a number that is different from the real number of the phone. –  android developer Jan 8 '13 at 21:40
As posted in my earlier answer
Use below code :
TelephonyManager tMgr = (TelephonyManager)mAppContext.getSystemService(Context.TELEPHONY_SERVICE); String mPhoneNumber = tMgr.getLine1Number();
In AndroidManifest.xml, give the following permission:
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
But remember, this code does not always work, since Cell phone number is dependent on the SIM Card and the Network operator / Cell phone carrier.
Also, try checking in Phone--> Settings --> About --> Phone Identity, If you are able to view the Number there, the probability of getting the phone number from above code is higher. If you are not able to view the phone number in the settings, then you won't be able to get via this code!
Suggested Workaround:
  1. Get the user's phone number as manual input from the user.
  2. Send a code to the user's mobile number via SMS.
  3. Ask user to enter the code to confirm the phone number.
  4. Save the number in sharedpreference.
Do the above 4 steps as one time activity during the app's first launch. Later on, whenever phone number is required, use the value available in shared preference.
share|improve this answer
 

TelephonyManager is not the right Solution,Because in some cases the number is not stored in the SIM, Due to my suggestion,You should use Shared Preference to store user's Phone number first time the application is open, and after that the number will used whenever you need in application.
share|improve this answer
 
    
But this method is error prone.User can enter wrong number. –  Zohra Khan Mar 12 at 15:31
1  
yes so for this purpose I used a text Message, When User enter a number, so from SmsManager the app message itself, and through this we can use smsReciever to Get the original number –  naveed ahmad Mar 12 at 16:23
1  
I have one more question.. with this method there will be a SMS charge given by user( If it is not a toll free number).. Is there any other method which which I can get phone no of the user? –  Zohra Khan Mar 13 at 7:08
    
Yes off course there will be some charge on that SMS if the number is not a toll free number. – naveed ahmad May 19 at 6:31
    
Nope I think there is no such method without TelephonyManager until now. and I point out the problem of TelephoneManager in my answer. –  naveed ahmad May 19 at 6:33

 

 

 

=================================

=================================

=================================

 

 

 

 

출처: http://help.adobe.com/en_US/air/build/WSfffb011ac560372f-5d0f4f25128cc9cd0cb-7ffc.html

Android settings

 
On the Android platform, you can use the 
android element of the application descriptor to add information to the Android application manifest, which is an application properties file used by the Android operating system. ADT automatically generates the Android Manifest.xml file when you create the APK package. AIR sets a few properties to the values required for certain features to work. Any other properties set in the android section of the AIR application descriptor are added to the corresponding section of the Manifest.xml file.
Note: For most AIR applications, you must set the Android permissions needed by your application within the android element, but you generally will not need to set any other properties.
You can only set attributes that take string, integer, or boolean values. Setting references to resources in the application package is not supported.
Note: The runtime requires a minimum SDK version greater than 9. You should ensure that the Manifest includes <uses-sdk android:minSdkVersion="9"></uses-sdk>.

Reserved Android manifest settings

AIR sets several manifest entries in the generated Android manifest document to ensure that application and runtime features work correctly. You cannot define the following settings:

manifest element

You cannot set the following attributes of the manifest element:
  • package
  • android:versionCode
  • android:versionName
  • xmlns:android

activity element

You cannot set the following attributes for the main activity element:
  • android:label
  • android:icon

application element

You cannot set the following attributes of the application element:
  • android:theme
  • android:name
  • android:label
  • android:windowSoftInputMode
  • android:configChanges
  • android:screenOrientation
  • android:launchMode

Android permissions

The Android security model requires that each app request permission in order to use features that have security or privacy implications. These permissions must be specified when the app is packaged, and cannot be changed at runtime. The Android operating system informs the user which permissions an app is requesting when the user installs it. If a permission required for a feature is not requested, the Android operating system might throw an exception when your application access the feature, but an exception is not guaranteed. Exceptions are transmitted by the runtime to your application. In the case of a silent failure, a permission failure message is added to the Android system log.
In AIR, you specify the Android permissions inside the 
android element of the application descriptor. The following format is used for adding permissions (where PERMISSION_NAME is the name of an Android permission):
<android> <manifestAdditions> <![CDATA[ <manifest> <uses-permission android:name="android.permission.PERMISSION_NAME" /> </manifest> ]]> </manifestAdditions> </android>
The uses-permissions statements inside the 
manifest element are added directly to the Android manifest document.
The following permissions are required to use various AIR features:
ACCESS_COARSE_LOCATION
 
Allows the application to access WIFI and cellular network location data through the Geolocation class.


ACCESS_FINE_LOCATION
 
Allows the application to access GPS data through the Geolocation class.


ACCESS_NETWORK_STATE and ACCESS_WIFI_STATE
 
Allows the application to access network information the NetworkInfo class.


CAMERA
 
Allows the application to access the camera.
Note: When you ask for permission to use the camera feature, Android assumes that your application also requires the camera. If the camera is an optional feature of your application, then you should add a uses-feature element to the manifest for the camera, setting the required attribute to false. See Android compatibility filtering.


INTERNET
 
Allows the application to make network requests. Also allows remote debugging.


READ_PHONE_STATE
 
Allows the AIR runtime to mute audio during phone calls. You should set this permission if your app plays audio while in the background.


RECORD_AUDIO
 
Allows the application to access the microphone.


WAKE_LOCK and DISABLE_KEYGUARD
 
Allows the application to prevent the device from going to sleep using the SystemIdleMode class settings.


WRITE_EXTERNAL_STORAGE
 
Allows the application to write to the external memory card on the device.


For example, to set the permissions for an app that impressively requires every permission, you could add the following to the application descriptor:
<android> <manifestAdditions> <![CDATA[ <manifest> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" /> <uses-permission android:name="android.permission.CAMERA" /> <uses-permission android:name="android.permission.DISABLE_KEYGUARD" /> <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.READ_PHONE_STATE" /> <uses-permission android:name="android.permission.RECORD_AUDIO" /> <uses-permission android:name="android.permission.WAKE_LOCK" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> </manifest> ]]> </manifestAdditions> </android>

Android custom URI schemes

You can use a custom URI scheme to launch an AIR application from a web page or a native Android application. Custom URI support relies on intent filters specified in the Android manifest, so this technique cannot be used on other platforms.
To use a custom URI, add an intent-filter to the application descriptor within the 
<android> block. Both 
intent-filter elements in the following example must be specified. Edit the 
<data android:scheme="my-customuri"/> statement to reflect the URI string for your custom scheme.
<android> <manifestAdditions> <![CDATA[ <manifest> <application> <activity> <intent-filter> <action android:name="android.intent.action.MAIN"/> <category android:name="android.intent.category.LAUNCHER"/> </intent-filter> <intent-filter> <action android:name="android.intent.action.VIEW"/> <category android:name="android.intent.category.BROWSABLE"/> <category android:name="android.intent.category.DEFAULT"/> <data android:scheme="my-customuri"/> </intent-filter> </activity> </application> </manifest> ]]> </manifestAdditions> </android>
An intent filter informs the Android operating system that your application is available to perform a given action. In the case of a custom URI, this means that the user has clicked a link using that URI scheme (and the browser does not know how to handle it).
When your application is invoked through a custom URI, the NativeApplication object dispatches an 
invoke event. The URL of the link, including query parameters, is placed in the 
arguments array of the InvokeEvent object. You can use any number of intent-filters.
Note: Links in a StageWebView instance cannot open URLs that use a custom URI scheme.

Android compatibility filtering

The Android operating system uses a number of elements in the application manifest file to determine whether your application is compatible with a given device. Adding this information to the manifest is optional. If you do not include these elements, your application can be installed on any Android device. However, it may not operate properly on any Android device. For example, a camera app will not be very useful on a phone that does not have a camera.
The Android manifest tags that you can use for filtering include:
  • supports-screens
  • uses-configuration
  • uses-feature
  • uses-sdk (in AIR 3+)

Camera applications

If you request the camera permission for your application, Android assumes that the app requires all available camera features, including auto-focus and flash. If your app does not require all camera features, or if the camera is an optional feature, you should set the various 
uses-feature elements for the camera to indicate that these are optional. Otherwise, users with devices that are missing one feature or that do not have a camera at all, will not be able to find your app on the Android Market.
The following example illustrates how to request permission for the camera and make all camera features optional:
<android> <manifestAdditions> <![CDATA[ <manifest> <uses-permission android:name="android.permission.CAMERA" /> <uses-feature android:name="android.hardware.camera" android:required="false"/> <uses-feature android:name="android.hardware.camera.autofocus" android:required="false"/> <uses-feature android:name="android.hardware.camera.flash" android:required="false"/> </manifest> ]]> </manifestAdditions> </android>

Audio recording applications

If you request the permission to record audio, Android also assumes that the app requires a microphone. If audio recording is an optional feature of your app, you can add a uses-feature tag to specify that the microphone is not required. Otherwise, users with devices that do not have a microphone, will not be able to find your app on the Android Market.
The following example illustrates how to request permission to use the microphone while still making the microphone hardware optional:
<android> <manifestAdditions> <![CDATA[ <manifest> <uses-permission android:name="android.permission.RECORD_AUDIO" /> <uses-feature android:name="android.hardware.microphone" android:required="false"/> </manifest> ]]> </manifestAdditions> </android>

Android 3 menu button

In Android 3, which runs on tablet devices, applications are expected to provide their own button for opening an options menu. The Android SDK now provides an ActionBar component that displays a menu button. The menu button displayed by the OS at the bottom of the tablet screen (next to the Back, Home, and Recent Apps buttons) is no longer shown for applications that target Android SDK level 11+.

Install location

You can permit your application to be installed or moved to the external memory card by setting the 
installLocation attribute of the Android 
manifest element to either 
auto or 
preferExternal:
<android> <manifestAdditions> <![CDATA[ <manifest android:installLocation="preferExternal"/> ]]> </manifestAdditions> </android>
The Android operating system doesn’t guarantee that your app will be installed to the external memory. A user can also move the app between internal and external memory using the system settings app.
Even when installed to external memory, application cache and user data, such as the contents of the app-storage directory, shared objects, and temporary files, are still stored in the internal memory. To avoid using too much internal memory, be selective about the data you save to the application storage directory. Large amounts of data should be saved to the SDCard using the 
File.userDirectory or 
File.documentsDirectory locations (which both map to the root of the SD card on Android).

Enabling Flash Player and other plug-ins in a StageWebView object

In Android 3.0+, an application must enable hardware acceleration in the Android application element in order for plug-in content to be displayed in a StageWebView object. To enable plug-in rendering, set the 
android:hardwareAccelerated attribute of the
application element to 
true:
<android> <manifestAdditions> <![CDATA[ <manifest> <application android:hardwareAccelerated="true"/> </manifest> ]]> </manifestAdditions> </android>
AIR validates the elements and attributes included in the Android portion of the application descriptor. By default, AIR validates against the Android 2.3 SDK. Since the 
android:hardwareAccelerated attribute was added in Android 3.0, you must set the AIR ADT utility to validate against the Android 3.0 SDK (or later).
First, download the Android 3 SDK: Android Developers: Installing the SDK . When packaging, set the 
-platformsdk option to the path containing the appropriate Android SDK (set the path to the directory containing the Android tools folder). For example:
adt -package -target apk -storetype pkcs12 -keystore cert.p12 -storepass foo myApp.apk myApp-app.xml -platformsdk c:\androidSDK myApp.swf other.files
You can also set the AIR_ANDROID_SDK_HOME environment variable to the path containing the Android SDK. Since Flash Builder and Flash Professional do not allow you to add extra parameters when packaging, setting this environment variable allows you to use Android SDK settings that were not available when the AIR SDK you are using was released. See ADT environment variables.

Color depth

In AIR 3 and later, the runtime sets the display to render 32-bit colors. In earlier versions of AIR, the runtime uses 16-bit color. You can instruct the runtime to use 16-bit color using the <colorDepth> element of the application descriptor:
<android> <colorDepth>16bit</colorDepth> <manifestAdditions>...</manifestAdditions> </android>
Using the 16-bit color depth can increase rendering performance, but at the expense of color fidelity.
 

 

 

=================================

=================================

=================================

 

 

 

출처: https://forums.adobe.com/thread/803428

 

Mobile Device Unique id

이 질문은 답변 안 됨 상태입니다.

curtis33321Community Member

Hey all,

 

I am starting down the path of creating a mobile application and I have a need for a deviceid (something unique to the particular mobile device.) so that I can register the application for use with Multi-Factored Authentication.  Is there an API somewhere in the Flex Framework or the upcoming mobile release where I can access a unique id for the device the app is running on?

 
평균 사용자 등급: 평가 없음 (0 등급)
평균 사용자 등급
평가 없음
(0 등급)

     

     

     

     

    =================================

    =================================

    =================================

     

     

     

     

    반응형