2013-04-04 76 views
1

我想在我的Android应用程序中有2件事。如何在Android中获取设备ID?

获取设备ID,然后用此ID打开一个网页。例如myserver.com/deviceId

我主要的Java类看起来是这样的:

package es.unican.CityInfo; 

import android.os.Bundle; 
import android.app.Activity; 
import android.webkit.WebSettings; 
import android.webkit.WebView; 
import android.webkit.WebViewClient; 
import android.provider.Settings.Secure; 

public class MainActivity extends Activity { 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 


     WebView mywebview = (WebView) findViewById(R.id.webview); 
     mywebview.loadUrl("http://www.google.com"); 

     //enabling Javascript 
     WebSettings webSettings = mywebview.getSettings(); 
     webSettings.setJavaScriptEnabled(true); 

     //opening links in my webview. if you delete this line , any link pressed will cause the browser to start 
     mywebview.setWebViewClient(new WebViewClient()); 

    } 


} 

为了获取设备ID,我读了我应该做这样的事情:

import android.provider.Settings.Secure; 

private String android_id = Secure.getString(getContext().getContentResolver(), 
                 Secure.ANDROID_ID); 

但是我不明白的地方我应该放置android_id代码,因为我总是遇到错误。

的错误是:

Multiple markers at this line: 

- The method getcontext() is undefined for the type MainActivity 
- Illegal modifier for parameter android_id; only final is permitted 
+0

你在哪里调用这个方法(Secure.getString(...))?尝试在setContentView(R.layout.activity_main)后调用它; – Gorets 2013-04-04 09:22:11

+0

我确实在那里调用它。 – donparalias 2013-04-04 09:26:03

回答

2

替换这是你的错误行:

String android_id = Secure.getString(this.getContentResolver(),Secure.ANDROID_ID); 
+0

非常感谢您 – donparalias 2013-04-04 09:27:59

+0

您知道如何直接从我的手机获取由此输出的相同ID? (例如,我想获得IMEI,我只需键入:*#06#) – AnixPasBesoin 2016-03-14 16:45:16

2
private String android_id; // declared on top of class 

android_id = Secure.getString(getContentResolver(), Secure.ANDROID_ID); // called inside onCreate 
1

使用此行

String android_id = Secure.getString(this.getContentResolver(), Secure.ANDROID_ID); 

既然你宣布它将在其内部范围的一个方法中的字符串。 你可以通过使用这个获得Activity上下文。

+0

你知道我怎么才能直接从我的手机中获得这个输出的相同ID? (例如,我想获得IMEI,我只需键入:*#06#) – AnixPasBesoin 2016-03-14 16:45:02

1

更改行代码:

getContext to getBaseContext 
+0

我试过这个,它没有修复错误。谢谢你的回答,尽管 – donparalias 2013-04-04 09:29:00

+0

然后使用android_id = Secure.getString(this.getContentResolver(),Secure.ANDROID_ID); – 2013-04-04 09:40:22

2

删除private修饰,也没有使用的getContext(),而不是使用getApplicationContext() 或只需在您的onCreate()方法中获取ContentConolver()

String android_id = Secure.getString(getContentResolver(),Secure.ANDROID_ID); 
+0

你知道我怎样才能直接从我的手机上获得由此输出的相同ID? (例如,我想获得IMEI,我只需键入:*#06#) – AnixPasBesoin 2016-03-14 16:44:54

0
import android.provider.Settings.Secure; 

    String android_id = Secure.getString(getApplicationContext().getContentResolver(),Secure.ANDROID_ID);