如何使用QR码扫描在App上打开片段

时间:2018-02-15 23:44:34

标签: android android-fragments zxing

您好我做了健身房应用所以想法是在应用程序中实现QR码扫描仪所以当我扫描QR代码示例为替补直接应用程序打开替补练习时,每个练习都是不同的片段所以我该怎么办呢我需要通过扫描特定于锻炼的QR码来打开一个特定的练习。谢谢你的帮助我也可以发布我的应用程序的源代码。

Android Manifest

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.hristijan.aleksandar.gymworkout.gymworkout">


<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity
        android:name=".Splashscreen"
        android:label="@string/app_name"
        android:screenOrientation="portrait">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
        <intent-filter android:label="@string/app_name">
            <action android:name="android.intent.action.VIEW" />
            <category android:name="android.intent.category.DEFAULT" />
            <category android:name="android.intent.category.BROWSABLE" />
            <data android:scheme="gymassistant" />
        </intent-filter>
    </activity>
    <activity
        android:name=".MainActivity"
        android:label="@string/app_name"
        android:screenOrientation="portrait"
        android:theme="@style/AppTheme.NoActionBar">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>
    </activity>

    <activity android:name="com.journeyapps.barcodescanner.CaptureActivity"
        android:screenOrientation="fullSensor"
        tools:replace="screenOrientation" />
    <activity android:name=".BmiActivity" />
    <activity android:name=".QrActivity"></activity>
</application>

QRActivity

package com.hristijan.aleksandar.gymworkout.gymworkout;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;

public class QrActivity extends AppCompatActivity {
Button scan_btn;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_qr);
    scan_btn = (Button) findViewById(R.id.scan_btn);
    final Activity activity =this;
    scan_btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            IntentIntegrator integrator = new IntentIntegrator(activity);
            integrator.setDesiredBarcodeFormats(IntentIntegrator.QR_CODE_TYPES);
            integrator.setPrompt("Scan");
            integrator.setCameraId(0);
            integrator.setBeepEnabled(false);
            integrator.setBarcodeImageEnabled(false);
            integrator.initiateScan();

        }
    });
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
    if(result != null) {
        if(result.getContents() == null) {
            Toast.makeText(this, "Cancelled", Toast.LENGTH_LONG).show();
        } else {
            Uri url = Uri.parse(result.getContents());
            Intent i = new Intent(Intent.ACTION_VIEW);
            i.setData(url);
            startActivity(i);
        }
    } else {
        super.onActivityResult(requestCode, resultCode, data);
    }
}
}

MainActivity

package com.hristijan.aleksandar.gymworkout.gymworkout;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Handler;
import android.support.v4.app.FragmentTransaction;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.Toast;

import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;

public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {

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


        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.addDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);

        FirstFragment fragment = new FirstFragment();
        FragmentTransaction fragmentTransaction  = getSupportFragmentManager().beginTransaction();
        fragmentTransaction.replace(R.id.frame,fragment,"fragment");
        fragmentTransaction.commit();



    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }



    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();


        return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        if (id == R.id.first_fragment) {
            setTitle("Home");
            FirstFragment fragment = new FirstFragment();
            FragmentTransaction fragmentTransaction  = getSupportFragmentManager().beginTransaction();
            fragmentTransaction.replace(R.id.frame,fragment,"bench");
            fragmentTransaction.commit();
        } else if (id == R.id.second_fragment) {
            setTitle("Bench Press");
            SecondFragment fragment = new SecondFragment();
            FragmentTransaction fragmentTransaction  = getSupportFragmentManager().beginTransaction();
            fragmentTransaction.replace(R.id.frame,fragment,"new1");
            fragmentTransaction.commit();
        } else if (id == R.id.third_fragment) {
            setTitle("Incline Bench Press");
            ThirdFragment fragment = new ThirdFragment();
            FragmentTransaction fragmentTransaction  = getSupportFragmentManager().beginTransaction();
            fragmentTransaction.replace(R.id.frame,fragment,"new2");
            fragmentTransaction.commit();
        } else if (id == R.id.blank_fragment) {
            setTitle("About");
            BlankFragment fragment = new BlankFragment();
            FragmentTransaction fragmentTransaction  = getSupportFragmentManager().beginTransaction();
            fragmentTransaction.replace(R.id.frame,fragment,"new2");
            fragmentTransaction.commit();
        } else if (id == R.id.bmi_calculator) {
            setTitle("Bmi Calculator");
            Intent i = new Intent(MainActivity.this,BmiActivity.class);
            startActivity(i);
        } else if (id == R.id.qr_activity) {
            setTitle("Scan QR Code");
            Intent i = new Intent(MainActivity.this,QrActivity.class);
            startActivity(i);
        }


        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

}

3 个答案:

答案 0 :(得分:0)

在QRActivity.java

更改

Uri url = Uri.parse(result.getContents());
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(url);
startActivity(i);

Intent i = new Intent(QrActivity.this, MainActivity.class);
i.putExtra("qrcode_result", result.getContents());
startActivity(i);

修改:您需要检查snull

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    String s = getIntent().getStringExtra("qrcode_result");


    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
            this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    drawer.addDrawerListener(toggle);
    toggle.syncState();

    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);


    FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();


    if (s != null) {

        if (s.equals("Bench Press")) {
            setTitle("Bench Press");

            SecondFragment fragment = new SecondFragment();
            fragmentTransaction.replace(R.id.frame, fragment, "new1");
            fragmentTransaction.commit();
        } // else if(s.equals("...")){}

         else{
            Toast.makeText(this,"scanned QR code that doesn't exist",Toast.LENGTH_SHORT).show();
            setTitle("Scan QR Code");
            Intent i = new Intent(MainActivity.this, QrActivity.class);
            startActivity(i);

        }

    } else { // not using QR Code scanner
        FirstFragment fragment = new FirstFragment();
        fragmentTransaction.replace(R.id.frame, fragment, "fragment");
        fragmentTransaction.commit();

    }

}

它有效:)

答案 1 :(得分:0)

在QRActivity.java

scan_btn.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
       FragmentManager fragmentManager = getSupportFragmentManager();
       FragmentTransaction fragmentTransaction =fragmentManager.beginTransaction();
       ScanFragment scanFragment = new ScanFragment();
       fragmentTransaction.add(R.id.scan_fragment,scanFragment);
       fragmentTransaction.commit();
 }
});

在R.layout.activity_qr中,     您将添加内容布局以将ScanFragment置于R.id.scan_fragment

之上

添加布局activity_qr

   <LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/scan_fragment"
    android:orientation="horizontal"></LinearLayout>

您将在此处创建ScanFragment.java.Example

public class ScanFragment extends Fragment {
private String codeFormat,codeContent;
private final String noResultErrorMsg = "No scan data received!";

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    IntentIntegrator integrator = new IntentIntegrator(this.getActivity()).forSupportFragment(this);
    // use forSupportFragment or forFragment method to use fragments instead of activity
    integrator.setDesiredBarcodeFormats(IntentIntegrator.ONE_D_CODE_TYPES);
    integrator.setPrompt(this.getString(R.string.scan_bar_code));
    integrator.setResultDisplayDuration(0); // milliseconds to display result on screen after scan
    integrator.setCameraId(0);  // Use a specific camera of the device
    integrator.initiateScan();
}

/**
 * function handle scan result
 * @param requestCode scanned code
 * @param resultCode  result of scanned code
 * @param intent intent
 */
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
    //retrieve scan result
    IntentResult scanningResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);


    if (scanningResult != null) {
        //we have a result
        codeContent = scanningResult.getContents();
        codeFormat = scanningResult.getFormatName();
        // send received data


    }else{
        // send exception

      }
    }
    }

您也可以参考[博客]:http://blog.whomeninja.in/android-barcode-scanner-in-fragment/

答案 2 :(得分:0)

a

Fragment Class中的此代码。我是用户ZXing。

在MainActivity中,我使用FragmentManager在app启动时打开它。

public class CameraFragment extends Fragment implements ZXingScannerView.ResultHandler {

private static final int REQUEST_CAMERA = 1;
private ZXingScannerView scannerView;
private static int camId = Camera.CameraInfo.CAMERA_FACING_BACK;

@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
    getActivity().getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    View v = inflater.inflate(R.layout.camera_fragment, container, false);
    int currentApiVersion = Build.VERSION.SDK_INT;
    if (currentApiVersion >= Build.VERSION_CODES.M) {
        if (checkPermission()) {
            //Toast.makeText(getApplicationContext(), "Permission already granted!", Toast.LENGTH_LONG).show();
            Log.e("SCAN QR CODE", "Permission already granted!");
        } else {
            requestPermission();
        }
    }
    scannerView = new ZXingScannerView(getActivity());
    //getActivity().setContentView( scannerView );
    return scannerView;
}

@Override
public void onResume() {
    super.onResume();

    int currentapiVersion = android.os.Build.VERSION.SDK_INT;
    if (currentapiVersion >= android.os.Build.VERSION_CODES.M) {
        if (checkPermission()) {
            if (scannerView == null) {
                scannerView = new ZXingScannerView( getActivity() );
                getActivity().setContentView( scannerView );
            }
            scannerView.setResultHandler( this );
            scannerView.startCamera();
        } else {
            requestPermission();
        }
    }
}

private boolean checkPermission() {
    return (ContextCompat.checkSelfPermission(getActivity(), CAMERA) == PackageManager.PERMISSION_GRANTED);
}

private void requestPermission() {
    ActivityCompat.requestPermissions(getActivity(), new String[]{CAMERA}, REQUEST_CAMERA);
}

@Override
public void handleResult(Result result) {

    final String myResult = result.getText();
    Toast.makeText(getActivity(), myResult, Toast.LENGTH_SHORT).show();
    onResume();
}

MainActivity Layout中的代码

FragmentManager fm = getFragmentManager();
    FragmentTransaction fragmentTransaction = fm.beginTransaction();
    fragmentTransaction.replace( R.id.fragment_camera, new CameraFragment() );
    fragmentTransaction.commit();