1. 程式人生 > >android開發之掃描二維碼實現網頁登入

android開發之掃描二維碼實現網頁登入

  • 匯入BarCodeLibrary到Eclipse當中
  • 在Eclipse當中建立新專案並依賴於BarCodeLibrary類庫

    • Code:

      • MainActivity.java
      public class MainActivity extends Activity implements OnClickListener {
      
          private Button btnScan;
          private EditText etUsername;
          private static final String WEB_URL = "http://172.31.19.202/QRLogin/";
      
          @Override
      protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); btnScan = (Button) findViewById(R.id.btnScan); btnScan.setOnClickListener(this); etUsername = (EditText) findViewById(R.id.etUsername); } @Override
      public void onClick(View v) { //掃碼操作 Intent intent = new Intent(this, CaptureActivity.class); startActivityForResult(intent, 0); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if
      (resultCode == Activity.RESULT_OK) { String randnumber = data.getExtras().getString("result"); String username = etUsername.getText().toString(); String url = WEB_URL + "saveUsername.php?randnumber=" + randnumber + "&username=" + username; //訪問url HttpUtils.login(url); } } }
      • 連線網路工具類:
      public class HttpUtils{
          public static void login(final String url){
              new Thread(new Runnable() {
                  @Override
                  public void run() {
                      HttpURLConnection connection;
                      try {
                          connection = (HttpURLConnection) new URL(url).openConnection();
                          connection.setRequestMethod("GET");
                          connection.getInputStream();
                      } catch (Exception e) {
                          e.printStackTrace();
                      }
                  }
              }).start();
          }
      }
      • 在清單檔案中新增節點:
      <activity
          android:name="com.zxing.activity.CaptureActivity"
          android:configChanges="orientation|keyboardHidden"
          android:screenOrientation="portrait"
          android:theme="@android:style/Theme.NoTitleBar.Fullscreen"
          android:windowSoftInputMode="stateAlwaysHidden" >
      </activity>
      • 新增許可權:
      <uses-permission android:name="android.permission.CAMERA"/>
      <uses-permission android:name="android.permission.VIBRATE"/>
      <uses-permission android:name="android.permission.INTERNET"/>