2017-09-09 3 views
-2

Ich kopierte/klebte ein Skript, um einen QR-Code-Scanner auf Android zu machen und ich änderte es ein wenig, so dass es in meine App passt. Aber die App hält zu stoppen, und ich weiß nicht, dass FehlerFehler mit QR Code Scanner App

MainActivity.java:

package com.swagdev.app.swagpoints; 

import android.Manifest; 
import android.content.ActivityNotFoundException; 
import android.content.Context; 
import android.content.Intent; 
import android.content.SharedPreferences; 
import android.content.pm.PackageManager; 
import android.graphics.Bitmap; 
import android.graphics.BitmapFactory; 
import android.net.Uri; 
import android.os.Environment; 
import android.preference.PreferenceManager; 
import android.provider.MediaStore; 
import android.support.annotation.NonNull; 
import android.support.v4.app.ActivityCompat; 
import android.support.v7.app.AppCompatActivity; 
import android.os.Bundle; 
import android.util.Log; 
import android.util.SparseArray; 
import android.view.View; 
import android.widget.Button; 
import android.widget.TextView; 
import android.widget.Toast; 

import com.google.android.gms.vision.Frame; 
import com.google.android.gms.vision.barcode.Barcode; 
import com.google.android.gms.vision.barcode.BarcodeDetector; 

import java.io.File; 
import java.io.FileNotFoundException; 

import static android.R.attr.data; 

public class MainActivity extends AppCompatActivity { 
Button button; 
private static final String LOG_TAG = "Barcode Scanner API"; 
private static final int PHOTO_REQUEST = 10; 
private TextView scanResults; 
private BarcodeDetector detector; 
private Uri imageUri; 
private static final int REQUEST_WRITE_PERMISSION = 20; 
private static final String SAVED_INSTANCE_URI = "uri"; 
private static final String SAVED_INSTANCE_RESULT = "result"; 
@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 


    button = (Button) findViewById(R.id.button); 
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext()); 
    boolean previouslyStarted = prefs.getBoolean(getString(R.string.pref_previously_started), false); 
    if (!previouslyStarted) { 
     SharedPreferences.Editor edit = prefs.edit(); 
     edit.putBoolean(getString(R.string.pref_previously_started), Boolean.TRUE); 
     edit.apply(); 
     setContentView(R.layout.activity_first_launch); 
    } 

    scanResults = (TextView) findViewById(R.id.scan_results); 
     if (savedInstanceState != null) { 
      imageUri = Uri.parse(savedInstanceState.getString(SAVED_INSTANCE_URI)); 
      scanResults.setText(savedInstanceState.getString(SAVED_INSTANCE_RESULT)); 
     } 
     button.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View view) { 
       ActivityCompat.requestPermissions(MainActivity.this, new 
         String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_WRITE_PERMISSION); 
      } 
     }); 

     detector = new BarcodeDetector.Builder(getApplicationContext()) 
       .setBarcodeFormats(Barcode.DATA_MATRIX | Barcode.QR_CODE) 
       .build(); 
     if (!detector.isOperational()) { 
      scanResults.setText("Could not set up the detector!"); 
      return; 
     } 
    } 

    @Override 
    public void onRequestPermissionsResult (int requestCode, @NonNull String[] permissions, 
    @NonNull int[] grantResults){ 
     super.onRequestPermissionsResult(requestCode, permissions, grantResults); 
     switch (requestCode) { 
      case REQUEST_WRITE_PERMISSION: 
       if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { 
        takePicture(); 
       } else { 
        Toast.makeText(MainActivity.this, "Permission Denied!", Toast.LENGTH_SHORT).show(); 
       } 
     } 
    } 

    @Override 
    protected void onActivityResult (int requestCode, int resultCode, Intent data){ 
     if (requestCode == PHOTO_REQUEST && resultCode == RESULT_OK) { 
      launchMediaScanIntent(); 
      try { 
       Bitmap bitmap = decodeBitmapUri(this, imageUri); 
       if (detector.isOperational() && bitmap != null) { 
        Frame frame = new Frame.Builder().setBitmap(bitmap).build(); 
        SparseArray<Barcode> barcodes = detector.detect(frame); 
        for (int index = 0; index < barcodes.size(); index++) { 
         Barcode code = barcodes.valueAt(index); 
         scanResults.setText(scanResults.getText() + code.displayValue + "\n"); 

         //Required only if you need to extract the type of barcode 
         int type = barcodes.valueAt(index).valueFormat; 
         switch (type) { 
          case Barcode.CONTACT_INFO: 
           Log.i(LOG_TAG, code.contactInfo.title); 
           break; 
          case Barcode.EMAIL: 
           Log.i(LOG_TAG, code.email.address); 
           break; 
          case Barcode.ISBN: 
           Log.i(LOG_TAG, code.rawValue); 
           break; 
          case Barcode.PHONE: 
           Log.i(LOG_TAG, code.phone.number); 
           break; 
          case Barcode.PRODUCT: 
           Log.i(LOG_TAG, code.rawValue); 
           break; 
          case Barcode.SMS: 
           Log.i(LOG_TAG, code.sms.message); 
           break; 
          case Barcode.TEXT: 
           Log.i(LOG_TAG, code.rawValue); 
           break; 
          case Barcode.URL: 
           Log.i(LOG_TAG, "url: " + code.url.url); 
           break; 
          case Barcode.WIFI: 
           Log.i(LOG_TAG, code.wifi.ssid); 
           break; 
          case Barcode.GEO: 
           Log.i(LOG_TAG, code.geoPoint.lat + ":" + code.geoPoint.lng); 
           break; 
          case Barcode.CALENDAR_EVENT: 
           Log.i(LOG_TAG, code.calendarEvent.description); 
           break; 
          case Barcode.DRIVER_LICENSE: 
           Log.i(LOG_TAG, code.driverLicense.licenseNumber); 
           break; 
          default: 
           Log.i(LOG_TAG, code.rawValue); 
           break; 
         } 
        } 
        if (barcodes.size() == 0) { 
         scanResults.setText("Scan Failed: Found nothing to scan"); 
        } 
       } else { 
        scanResults.setText("Could not set up the detector!"); 
       } 
      } catch (Exception e) { 
       Toast.makeText(this, "Failed to load Image", Toast.LENGTH_SHORT) 
         .show(); 
       Log.e(LOG_TAG, e.toString()); 
      } 
     } 
    } 

    private void takePicture() { 
     Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); 
     File photo = new File(Environment.getExternalStorageDirectory(), "picture.jpg"); 
     imageUri = Uri.fromFile(photo); 
     intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri); 
     startActivityForResult(intent, PHOTO_REQUEST); 
    } 

    @Override 
    protected void onSaveInstanceState(Bundle outState) { 
     if (imageUri != null) { 
      outState.putString(SAVED_INSTANCE_URI, imageUri.toString()); 
      outState.putString(SAVED_INSTANCE_RESULT, scanResults.getText().toString()); 
     } 
     super.onSaveInstanceState(outState); 
    } 

    private void launchMediaScanIntent() { 
     Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE); 
     mediaScanIntent.setData(imageUri); 
     this.sendBroadcast(mediaScanIntent); 
    } 

    private Bitmap decodeBitmapUri(Context ctx, Uri uri) throws FileNotFoundException { 
     int targetW = 600; 
     int targetH = 600; 
     BitmapFactory.Options bmOptions = new BitmapFactory.Options(); 
     bmOptions.inJustDecodeBounds = true; 
     BitmapFactory.decodeStream(ctx.getContentResolver().openInputStream(uri), null, bmOptions); 
     int photoW = bmOptions.outWidth; 
     int photoH = bmOptions.outHeight; 

     int scaleFactor = Math.min(photoW/targetW, photoH/targetH); 
     bmOptions.inJustDecodeBounds = false; 
     bmOptions.inSampleSize = scaleFactor; 

     return BitmapFactory.decodeStream(ctx.getContentResolver() 
       .openInputStream(uri), null, bmOptions); 
    } 
} 

nun die ganze Zeit über diesen Fehler Ich erhalte:

E/AndroidRuntime: FATAL EXCEPTION: main 
        Process: com.swagdev.app.swagpoints, PID: 19339 
        java.lang.RuntimeException: Failure delivering result ResultInfo{[email protected]:requestPermissions:, request=1, result=-1, data=Intent { act=android.content.pm.action.REQUEST_PERMISSIONS launchParam=MultiScreenLaunchParams { mDisplayId=0 mBaseDisplayId=0 mFlags=0 } (has extras) }} to activity {com.swagdev.app.swagpoints/com.swagdev.app.swagpoints.MainActivity}: android.os.FileUriExposedException: file:///storage/emulated/0/picture.jpg exposed beyond app through ClipData.Item.getUri() 
         at android.app.ActivityThread.deliverResults(ActivityThread.java:4520) 
         at android.app.ActivityThread.handleSendResult(ActivityThread.java:4563) 
         at android.app.ActivityThread.-wrap22(ActivityThread.java) 
         at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1698) 
         at android.os.Handler.dispatchMessage(Handler.java:102) 
         at android.os.Looper.loop(Looper.java:154) 
         at android.app.ActivityThread.main(ActivityThread.java:6776) 
         at java.lang.reflect.Method.invoke(Native Method) 
         at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1520) 
         at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1410) 
        Caused by: android.os.FileUriExposedException: file:///storage/emulated/0/picture.jpg exposed beyond app through ClipData.Item.getUri() 
         at android.os.StrictMode.onFileUriExposed(StrictMode.java:1799) 
         at android.net.Uri.checkFileUriExposed(Uri.java:2346) 
         at android.content.ClipData.prepareToLeaveProcess(ClipData.java:832) 
         at android.content.Intent.prepareToLeaveProcess(Intent.java:9530) 
         at android.content.Intent.prepareToLeaveProcess(Intent.java:9515) 
         at android.app.Instrumentation.execStartActivity(Instrumentation.java:1525) 
         at android.app.Activity.startActivityForResult(Activity.java:4403) 
         at android.support.v4.app.BaseFragmentActivityJB.startActivityForResult(BaseFragmentActivityJB.java:50) 
         at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:79) 
         at android.app.Activity.startActivityForResult(Activity.java:4362) 
         at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:859) 
         at com.swagdev.app.swagpoints.MainActivity.takePicture(MainActivity.java:173) 
         at com.swagdev.app.swagpoints.MainActivity.onRequestPermissionsResult(MainActivity.java:90) 
         at android.app.Activity.dispatchRequestPermissionsResult(Activity.java:7460) 
         at android.app.Activity.dispatchActivityResult(Activity.java:7286) 
         at android.app.ActivityThread.deliverResults(ActivityThread.java:4516) 
         at android.app.ActivityThread.handleSendResult(ActivityThread.java:4563)  
         at android.app.ActivityThread.-wrap22(ActivityThread.java)  
         at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1698)  
         at android.os.Handler.dispatchMessage(Handler.java:102)  
         at android.os.Looper.loop(Looper.java:154)  
         at android.app.ActivityThread.main(ActivityThread.java:6776)  
         at java.lang.reflect.Method.invoke(Native Method)  
         at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1520)  
         at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1410)  
Disconnected from the target VM, address: 'localhost:8600', transport: 'socket' 
+0

Sie kennen den Fehler oder nicht? Bitte lesen Sie, bevor Sie mehr posten: https://stackoverflow.com/help/mcve –

Antwort

0

Sie müssen hinzufügen die permission, um die Telefonkamera zu verwenden.

Um auf die Gerätekamera zugreifen zu können, müssen Sie die CAMERA-Berechtigung in Ihrem>> Android Manifest angeben. Stellen Sie außerdem sicher, dass Sie das Manifestelement> hinzufügen, um Kamerafunktionen zu deklarieren, die von Ihrer Anwendung verwendet werden.

zu Ihrer "manifest.xml" Go-Datei und diese Zeile hinzu:

<uses-permission android:name="android.permission.CAMERA" /> 

Click here, um weitere Informationen über die Kamera.

Verwandte Themen