很久没有做小项目了,今天有空就顺便做了个简单的扫描二维码并解析跳转。
1.在app里面的libs文件中集成lib-zxing包
2.在app文件中的build添加红色框类包名
3.在activity_main.xml中添加按钮
<Button android:id="@+id/btn" android:layout_width="150dp" android:layout_height="100dp" android:text="扫描二维码跳转" />
4.在MainActivity.java中添加运行解析代码
package com.example.zx; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.Toast; import com.uuzuche.lib_zxing.activity.CaptureActivity; import com.uuzuche.lib_zxing.activity.CodeUtils; public class MainActivity extends AppCompatActivity { /** * 扫描跳转Activity RequestCode */ public static final int REQUEST_CODE = 111; /** * 扫描跳转按钮 */ private Button btn=null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); btn=(Button)findViewById(R.id.btn); btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(MainActivity.this, CaptureActivity.class); startActivityForResult(intent,REQUEST_CODE);}});} @Override protected void onActivityResult( int requestCode, int resultCode, Intent data) { /** * 处理二维码扫描结果 */ if (requestCode == REQUEST_CODE) { //处理扫描结果(在界面上显示) if (null != data) { Bundle bundle = data.getExtras(); if (bundle == null) { return;} if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_SUCCESS) { String result = bundle.getString(CodeUtils.RESULT_STRING); //用默认浏览器打开扫描得到的地址 Intent intent = new Intent(); intent.setAction("android.intent.action.VIEW"); Uri content_url = Uri.parse(result.toString()); intent.setData(content_url); startActivity(intent); } else if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_FAILED) { Toast.makeText(MainActivity.this, "解析二维码失败", Toast.LENGTH_LONG).show();}}}}}
5.我们来看下运行效果吧
6.源代码在这 https://github.com/huangweijieGitHub/Quickmark