How can I detect when an Android application is running in the emulator?

前端 未结 30 2689
无人及你
无人及你 2020-11-22 16:42

I would like to have my code run slightly differently when running on the emulator than when running on a device. (For example, using 10.0.2.2 instead of a

30条回答
  •  遥遥无期
    2020-11-22 17:34

    Here is my solution (it works only if you run a web server on your debug machine): I have created a background task that starts when the application starts. It looks for http://10.0.2.2 and if it exists it changes a global parameter (IsDebug) to true. It is a silent way to find out where you are running.

    public class CheckDebugModeTask extends AsyncTask {
    public static boolean IsDebug = false;
    
    public CheckDebugModeTask()
    {
    
    }
    
    @Override
    protected String doInBackground(String... params) {     
      try {
        HttpParams httpParameters = new BasicHttpParams();
        int timeoutConnection = 1000;
        HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
        int timeoutSocket = 2000;
        HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
    
        String url2 = "http://10.0.2.2";        
              HttpGet httpGet = new HttpGet(url2);
        DefaultHttpClient client = new DefaultHttpClient(httpParameters);
    
        HttpResponse response2 = client.execute(httpGet);
        if (response2 == null || response2.getEntity() == null || response2.getEntity().getContent() == null)
        return "";
    
        return "Debug";
    
    } catch (Exception e) {
        return "";
    }
    }
    
    @Override
    protected void onPostExecute (String result)
    {       
    if (result == "Debug")
    {
        CheckDebugModeTask.IsDebug = true;
    }
    }
    

    from the main activity onCreate:

    CheckDebugModeTask checkDebugMode = new CheckDebugModeTask();
    checkDebugMode.execute("");
    

提交回复
热议问题