2012-05-12 20 views
0

在Gingerbread 2.3上,我的应用程序可以运行并可以连接到服务器。我无法连接到ICS 4.0.4上的服务器?

但是在ICS 4.0.4上,可以运行但不能连接到服务器。我可以在ICS上的浏览器上连接到服务器。

原因是什么以及如何解决。

public class NFC_readerActivity extends Activity { 

private NfcAdapter mAdapter; 
private PendingIntent mPendingIntent; 
private NdefMessage mNdefPushMessage; 
private AlertDialog mDialog; 

// New methods in Android 2.3.3 
private static Method sAdapter_enableForegroundDispatch; 
private static Method sAdapter_enableForegroundNdefPush; 
private static Method sAdapter_disableForegroundDispatch; 
private static Method sAdapter_disableForegroundNdefPush; 

final static String url = "http://10.204.3.112/getpos.php"; 
static String result = "0"; 
String a = ""; 

static { 
    try { 
     sAdapter_enableForegroundDispatch = NfcAdapter.class.getMethod(
       "enableForegroundDispatch", new Class[] { Activity.class, 
         PendingIntent.class, IntentFilter[].class, 
         String[][].class }); 
     sAdapter_enableForegroundNdefPush = NfcAdapter.class.getMethod(
       "enableForegroundNdefPush", new Class[] { Activity.class, 
         NdefMessage.class }); 
     sAdapter_disableForegroundDispatch = NfcAdapter.class 
       .getMethod("disableForegroundDispatch", 
         new Class[] { Activity.class }); 
     sAdapter_disableForegroundNdefPush = NfcAdapter.class 
       .getMethod("disableForegroundNdefPush", 
         new Class[] { Activity.class }); 
    } catch (NoSuchMethodException e) { 
     // failure, i.e Android 2.3-2.3.2 
    } 
} 

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

    boolean checkConnect = isConnectedToServer(url, 30000); 
    if(checkConnect){ 
     Toast.makeText(getApplicationContext(), "connected", 
       Toast.LENGTH_SHORT).show(); 
    }else{ 
     Toast.makeText(getApplicationContext(), "not connect", 
       Toast.LENGTH_SHORT).show(); 
    } 
    resolveIntent(getIntent()); 

    mDialog = new AlertDialog.Builder(this).setNeutralButton("Ok", null) 
      .create(); 

    mAdapter = NfcAdapter.getDefaultAdapter(this); 
    if (mAdapter == null) { 
     showMessage(R.string.error, R.string.no_nfc); 
    } 

    mPendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, 
      getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0); 
    mNdefPushMessage = new NdefMessage(new NdefRecord[] { newTextRecord(
      "Message from NFC Reader :-)", Locale.ENGLISH, true) }); 
} 

private void showMessage(int title, int message) { 
    mDialog.setTitle(title); 
    mDialog.setMessage(getText(message)); 
    mDialog.show(); 
} 

private NdefRecord newTextRecord(String text, Locale locale, 
     boolean encodeInUtf8) { 
    byte[] langBytes = locale.getLanguage().getBytes(
      Charset.forName("US-ASCII")); 

    Charset utfEncoding = encodeInUtf8 ? Charset.forName("UTF-8") : Charset 
      .forName("UTF-16"); 
    byte[] textBytes = text.getBytes(utfEncoding); 

    int utfBit = encodeInUtf8 ? 0 : (1 << 7); 
    char status = (char) (utfBit + langBytes.length); 

    byte[] data = new byte[1 + langBytes.length + textBytes.length]; 
    data[0] = (byte) status; 
    System.arraycopy(langBytes, 0, data, 1, langBytes.length); 
    System.arraycopy(textBytes, 0, data, 1 + langBytes.length, 
      textBytes.length); 

    return new NdefRecord(NdefRecord.TNF_WELL_KNOWN, NdefRecord.RTD_TEXT, 
      new byte[0], data); 
} 

@Override 
protected void onResume() { 
    super.onResume(); 
    if (mAdapter != null) { 
     if (!mAdapter.isEnabled()) { 
      showMessage(R.string.error, R.string.nfc_disabled); 
     } 
     try { 
      sAdapter_enableForegroundDispatch.invoke(mAdapter, this, 
        mPendingIntent, null, null); 
      sAdapter_enableForegroundNdefPush.invoke(mAdapter, this, 
        mNdefPushMessage); 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
    } 
} 

@Override 
protected void onPause() { 
    super.onPause(); 
    if (mAdapter != null) { 
     try { 
      sAdapter_disableForegroundDispatch.invoke(mAdapter, this); 
      sAdapter_disableForegroundNdefPush.invoke(mAdapter, this); 
     } catch (Exception e) { 
      // ignore 
     } 
    } 
} 

private void resolveIntent(Intent intent) { 
    String action = intent.getAction(); 
    if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(action) 
      || NfcAdapter.ACTION_NDEF_DISCOVERED.equals(action)) { 
     Parcelable[] rawMsgs = intent 
       .getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES); 
     NdefMessage[] msgs; 

     msgs = new NdefMessage[rawMsgs.length]; 
     for (int i = 0; i < rawMsgs.length; i++) { 
      msgs[i] = (NdefMessage) rawMsgs[i]; 
     } 

     getCode(msgs); 
    } 
} 

public boolean isConnectedToServer(String url, int timeout) { 
    try { 
     URL myUrl = new URL(url); 
     URLConnection connection = myUrl.openConnection(); 
     connection.setConnectTimeout(timeout); 
     connection.connect(); 
     return true; 
    } catch (Exception e) { 
     return false; 
    } 
} 


private static void getCodeServer(final String key) { 
    Thread thread = new Thread() { 

     public void run() { 

      Looper.prepare(); 
      DefaultHttpClient client = new DefaultHttpClient(); 
      HttpParams params = client.getParams(); 
      HttpConnectionParams.setConnectionTimeout(params, 10000); 
      HttpConnectionParams.setSoTimeout(params, 10000); 
      HttpClientParams.setRedirecting(params, false); 

      HttpPost post = new HttpPost(url); 

      List<NameValuePair> valuePairs = new ArrayList<NameValuePair>(1); 
      valuePairs.add(new BasicNameValuePair("code", key)); 

      try { 
       post.setEntity(new UrlEncodedFormEntity(valuePairs)); 

      } catch (UnsupportedEncodingException e1) { 
       // TODO Auto-generated catch block 
       e1.printStackTrace(); 
      } catch (Exception e) { 
       Log.e("log_tag", "Error in http connection" + e.toString()); 
      } 

      HttpResponse response = null; 
      try { 

       response = client.execute(post); 
       ByteArrayOutputStream output = new ByteArrayOutputStream(); 
       response.getEntity().writeTo(output); 
       result = output.toString(); 

       client.getConnectionManager().shutdown(); 

      } catch (ClientProtocolException e1) { 
       // TODO Auto-generated catch block 
       e1.printStackTrace(); 
      } catch (IOException e1) { 
       // TODO Auto-generated catch block 
       e1.printStackTrace(); 
      } 

      Looper.loop(); 

     } 

    }; 

    thread.start(); 

    try { 
     Thread.sleep(3000); 
    } catch (InterruptedException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 
} 

void getCode(NdefMessage[] msgs) { 
    if (msgs == null || msgs.length == 0) { 
     return; 
    } 

    List<ParsedNdefRecord> records = MsgParser.parse(msgs[0]); 
    Toast.makeText(getApplicationContext(), TextRecord.tRecord, 
      Toast.LENGTH_SHORT).show(); 

    if (isConnectedToServer(url, 10000000)) { 
     Toast.makeText(getApplicationContext(), "Connected.", 
       Toast.LENGTH_SHORT).show(); 
     getCodeServer(TextRecord.tRecord); 
     if (result.equals("1")) { 
      Toast.makeText(getApplicationContext(), "You are teacher.", 
        Toast.LENGTH_SHORT).show(); 
     } else if (result.equals("2")) { 
      Toast.makeText(getApplicationContext(), "You are staff.", 
        Toast.LENGTH_SHORT).show(); 
     } else if (result.equals("3")) { 
      Toast.makeText(getApplicationContext(), "You are student.", 
        Toast.LENGTH_SHORT).show(); 
     } else { 
      Toast.makeText(getApplicationContext(), "Somtring wrong.", 
        Toast.LENGTH_SHORT).show(); 
     } 
    } else { 
     Toast.makeText(getApplicationContext(), "not Connect.", 
       Toast.LENGTH_SHORT).show(); 
    } 

} 

@Override 
public void onNewIntent(Intent intent) { 
    setIntent(intent); 
    resolveIntent(intent); 
} 

} 

logcat的有一个橙色线和其他线路是绿色和蓝色

W/InputManagerService(132):对非重点客户com.android.internal.view.IInputMethodClient $开始输入存根$ Proxy @ 417ef6e)(uid = 10026 pid = 1160)

请帮助我,这是我的高级项目。我明天将出席。

+0

你的问题太泛泛,不能给出任何有用的答案。请细化并可能显示一些代码。 –

+0

请提供一些细节,什么样的错误/例外,它显示或粘贴logcat在这里。 –

+0

您是否收到任何错误。提供更多信息 – sachy

回答

1

我怀疑你是在UI线程上连接到服务器并得到NetworkOnMainThreadException。您可以通过在LogCat视图中查看日志来验证此情况。如果是这种情况,您应该在后台线程上替换do it asynchronously

+0

使用AsyncTask可能是最简单的方法来做这个BTW。 –

+0

极有可能,2.3中不存在此异常,请参阅http://developer.android.com/reference/android/os/NetworkOnMainThreadException.html – NickT