2012-05-12 3 views
0

진저 브레드 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); 
} 

} 

로그 캣 한 오렌지 라인을 갖고, 다른 라인이 녹색 및 청색

W/InputManagerService (132) 이외의 중심 클라이언트 com.android.internal.view.IInputMethodClient $으로부터 입력 스텁 $ 프록시 @ 417ef6e) (uid = 10026 pid = 1160)

제발, 내 수석 프로젝트입니다. 나는 내일 선물 할 것이다.

+0

유용한 질문에 답하기에는 너무 일반적인 질문입니다. 일부 코드를 수정하고 표시하십시오. –

+0

pls 몇 가지 세부 사항, 어떤 종류의 오류/예외, 표시 또는 붙여 넣기 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

관련 문제