2017-07-10 11 views
0

こんにちは、私はこれをたくさん検索し、それを理解していません。このコードを使用して1つのイメージをアップロードし、イメージをサーバーにプッシュすることができます。しかし、問題はギャラリーからの複数の画像選択を許可していないか、画像をクリックすると前の画像に置き換わり、2番目の画像は表示されません。ギャラリーとカメラの両方からwebview androidに複数の画像をアップロードする方法

以下のコード全体をお持ちで、私が逃した可能性のあるものをお勧めします。

public class MainActivity extends Activity { 

WebView mWebView; 

private PendingIntent pendingIntent; 
String tag = "alarm_set_flag"; 
private Boolean alarm_set_flag; 
SharedPreferences mPrefs; 

private static final int INPUT_FILE_REQUEST_CODE = 1; 
private static final int FILECHOOSER_RESULTCODE = 1; 
private static final String TAG = MainActivity.class.getSimpleName(); 
private ValueCallback<Uri> mUploadMessage; 
private Uri mCapturedImageURI = null; 
private ValueCallback<Uri[]> mFilePathCallback; 
private String mCameraPhotoPath; 

@Override 
public void onActivityResult(int requestCode, int resultCode, Intent data) { 
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { 
     if (requestCode != INPUT_FILE_REQUEST_CODE || mFilePathCallback == 
null) { 
      super.onActivityResult(requestCode, resultCode, data); 
      return; 
     } 
     Uri[] results = null; 
     // Check that the response is a good one 
     if (resultCode == Activity.RESULT_OK) { 
      if (data == null) { 
       // If there is not data, then we may have taken a photo 
       if (mCameraPhotoPath != null) { 
        results = new Uri[]{Uri.parse(mCameraPhotoPath)}; 
       } 
      } else { 
       String dataString = data.getDataString(); 
       if (dataString != null) { 
        results = new Uri[]{Uri.parse(dataString)}; 
       } 
      } 
     } 
     mFilePathCallback.onReceiveValue(results); 
     mFilePathCallback = null; 
    } else if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT) { 
     if (requestCode != FILECHOOSER_RESULTCODE || mUploadMessage == null) 
    { 
      super.onActivityResult(requestCode, resultCode, data); 
      return; 
     } 
     if (requestCode == FILECHOOSER_RESULTCODE) { 
      if (null == this.mUploadMessage) { 
       return; 
      } 
      Uri result = null; 
      try { 
       if (resultCode != RESULT_OK) { 
        result = null; 
       } else { 
        // retrieve from the private variable if the intent is 
null 
        result = data == null ? mCapturedImageURI : 
     data.getData(); 
       } 
      } catch (Exception e) { 
       Toast.makeText(getApplicationContext(), "activity :" + e, 
         Toast.LENGTH_LONG).show(); 
      } 
      mUploadMessage.onReceiveValue(result); 
      mUploadMessage = null; 
     } 
    } 
    return; 
} 

private File createImageFile() throws IOException { 
    // Create an image file name 
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()); 
    String imageFileName = "JPEG_" + timeStamp + "_"; 
    File storageDir = Environment.getExternalStoragePublicDirectory(
      Environment.DIRECTORY_PICTURES); 
    File imageFile = File.createTempFile(
      imageFileName, /* prefix */ 
      ".jpg",   /* suffix */ 
      storageDir  /* directory */ 
    ); 
    return imageFile; 
} 


@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); 
    requestWindowFeature(Window.FEATURE_NO_TITLE); 
    setContentView(R.layout.activity_main); 

    mWebView = (WebView) findViewById(R.id.webview); 
    WebSettings webSettings = mWebView.getSettings(); 
    webSettings.setJavaScriptEnabled(true); 

    // This is for the JS Interface 
    mWebView.addJavascriptInterface(new WebViewJavaScriptInterface(this), "app"); 

    mWebView.getSettings().setAllowFileAccess(true); 
    mWebView.setHapticFeedbackEnabled(false); 
    mWebView.loadUrl("my url"); 
    ActivityCompat.requestPermissions(this, new String[]{ 
      Manifest.permission.ACCESS_FINE_LOCATION, 
      Manifest.permission.ACCESS_COARSE_LOCATION 
    }, 0); 

    mPrefs = getSharedPreferences(tag,0); 
    alarm_set_flag = mPrefs.getBoolean(tag,false); 

    mWebView.setWebViewClient(new WebViewClient() { 
     @Override 
     public boolean shouldOverrideUrlLoading(WebView view, String url) { 
      view.loadUrl(url); 
      return false; 
     } 
    }); 


    mWebView.setWebChromeClient(new WebChromeClient() { 
     @Override 
     public void onGeolocationPermissionsShowPrompt(String origin, GeolocationPermissions.Callback callback) { 
      callback.invoke(origin, true, false); 
     } 

     // For Android 5.0 
     public boolean onShowFileChooser(WebView view, ValueCallback<Uri[]> filePath, WebChromeClient.FileChooserParams fileChooserParams) { 
      // Double check that we don't have any existing callbacks 
      if (mFilePathCallback != null) { 
       mFilePathCallback.onReceiveValue(null); 
      } 
      mFilePathCallback = filePath; 
      Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); 
      if (takePictureIntent.resolveActivity(getPackageManager()) != null) { 
       // Create the File where the photo should go 
       File photoFile = null; 
       try { 
        photoFile = createImageFile(); 
        takePictureIntent.putExtra("PhotoPath", mCameraPhotoPath); 
       } catch (IOException ex) { 
        // Error occurred while creating the File 
        Log.e(TAG, "Unable to create Image File", ex); 
       } 
       // Continue only if the File was successfully created 
       if (photoFile != null) { 
        mCameraPhotoPath = "file:" + photoFile.getAbsolutePath(); 
        takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, 
          Uri.fromFile(photoFile)); 
       } else { 
        takePictureIntent = null; 
       } 
      } 
      Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT); 
      contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE); 
      contentSelectionIntent.setType("image/*"); 
      Intent[] intentArray; 
      if (takePictureIntent != null) { 
       intentArray = new Intent[]{takePictureIntent}; 
      } else { 
       intentArray = new Intent[0]; 
      } 
      Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER); 
      chooserIntent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE,true); 
      chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent); 
      chooserIntent.putExtra(Intent.EXTRA_TITLE, "Image Chooser"); 
      chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray); 
      startActivityForResult(chooserIntent, INPUT_FILE_REQUEST_CODE); 
      return true; 
     } 
     // openFileChooser for Android 3.0+ 
     public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) { 
      mUploadMessage = uploadMsg; 
      // Create AndroidExampleFolder at sdcard 
      // Create AndroidExampleFolder at sdcard 
      File imageStorageDir = new File(
        Environment.getExternalStoragePublicDirectory(
          Environment.DIRECTORY_PICTURES) 
        , "AndroidExampleFolder"); 
      if (!imageStorageDir.exists()) { 
       // Create AndroidExampleFolder at sdcard 
       imageStorageDir.mkdirs(); 
      } 
      // Create camera captured image file path and name 
      File file = new File(
        imageStorageDir + File.separator + "IMG_" 
          + String.valueOf(System.currentTimeMillis()) 
          + ".jpg"); 
      mCapturedImageURI = Uri.fromFile(file); 
      // Camera capture image intent 
      final Intent captureIntent = new Intent(
        android.provider.MediaStore.ACTION_IMAGE_CAPTURE); 
      captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, mCapturedImageURI); 
      Intent i = new Intent(Intent.ACTION_GET_CONTENT); 
      i.addCategory(Intent.CATEGORY_OPENABLE); 
      i.setType("image/*"); 
      // Create file chooser intent 
      Intent chooserIntent = Intent.createChooser(i, "Image Chooser"); 
      // Set camera intent to file chooser 
      chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS 
        , new Parcelable[] { captureIntent }); 
      // On select image call onActivityResult method of activity 
      startActivityForResult(chooserIntent, FILECHOOSER_RESULTCODE); 
     } 
     // openFileChooser for Android < 3.0 
     public void openFileChooser(ValueCallback<Uri> uploadMsg) { 
      openFileChooser(uploadMsg, ""); 
     } 
     //openFileChooser for other Android versions 
     public void openFileChooser(ValueCallback<Uri> uploadMsg, 
            String acceptType, 
            String capture) { 
      openFileChooser(uploadMsg, acceptType); 
     } 

    }); 

    mWebView.setOnLongClickListener(new View.OnLongClickListener() { 
     @Override 
     public boolean onLongClick(View v) { 
      return true; 
     } 
    }); 
    mWebView.setLongClickable(false); 

} 
public class WebViewJavaScriptInterface{ 

    private Context context; 

    /* 
    * Need a reference to the context in order to sent a post message 
    */ 
    public WebViewJavaScriptInterface(Context context){ 
     this.context = context; 
    } 

    /* 
    * This method can be called from Android. @JavascriptInterface 
    * required after SDK version 17. 
    */ 
    @JavascriptInterface 
    public void jsBridge(int mints, int hrs, int ampm, int checkbox){ 
     int Min = mints; 
     int Hours = hrs; 
     int AMPM = ampm; 
     int Checkbox = checkbox; 

     if(Checkbox == 1){ 
      if(alarm_set_flag == true){ 
       cancelDailyNotification(); 
       setNotification(Hours,Min,AMPM); 
       SharedPreferences.Editor mEditor = mPrefs.edit(); 
       mEditor.putBoolean(tag, true).commit(); 
       Toast.makeText(getApplicationContext(), "Daily Notification has been set.", Toast.LENGTH_LONG).show(); 
      }else{ 
       setNotification(Hours,Min,AMPM); 
       SharedPreferences.Editor mEditor = mPrefs.edit(); 
       mEditor.putBoolean(tag, true).commit(); 
       Toast.makeText(getApplicationContext(), "Daily Notification has been set.", Toast.LENGTH_LONG).show(); 
      } 
     }else { 
      if(alarm_set_flag == true){ 
       cancelDailyNotification(); 
       SharedPreferences.Editor mEditor = mPrefs.edit(); 
       mEditor.putBoolean(tag, false).commit(); 
       Toast.makeText(getApplicationContext(), "Daily Notification has been turned off.", Toast.LENGTH_LONG).show(); 
      }else{ 
       cancelDailyNotification(); 
       SharedPreferences.Editor mEditor = mPrefs.edit(); 
       mEditor.putBoolean(tag, false).commit(); 
       Toast.makeText(getApplicationContext(), "Daily Notification is already turned off.", Toast.LENGTH_LONG).show(); 
      } 
     } 

    } 
} 
public void setNotification(int hour, int minutes, int ampm){ 

    Calendar calendar = Calendar.getInstance(); 
    calendar.set(Calendar.HOUR_OF_DAY, hour); 
    calendar.set(Calendar.MINUTE, minutes); 
    calendar.set(Calendar.SECOND, 0); 
    if(ampm == 1) { 
     calendar.set(Calendar.AM_PM, Calendar.PM); 
    }else{ 
     calendar.set(Calendar.AM_PM, Calendar.AM); 
    } 
    Intent myIntent = new Intent(MainActivity.this, notificationReceiver.class); 
    pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 0, myIntent,0); 

    AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE); 
    alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 1000 * 60 * 60 * 24,pendingIntent); 
} 
public void cancelDailyNotification(){ 
    AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE); 
    Intent myIntent = new Intent(getApplicationContext(), 
      notificationReceiver.class); 
    PendingIntent pendingIntent = PendingIntent.getBroadcast(
      getApplicationContext(), 0, myIntent, PendingIntent.FLAG_UPDATE_CURRENT); 

    alarmManager.cancel(pendingIntent); 

    SharedPreferences.Editor mEditor = mPrefs.edit(); 
    mEditor.putBoolean(tag, false).commit(); 
} 

@Override 
public boolean onKeyDown(int keyCode, @NonNull KeyEvent event){ 
    String webUrl = mWebView.getUrl(); 

    if(event.getAction() == KeyEvent.ACTION_DOWN){ 
     switch(keyCode){ 
      case KeyEvent.KEYCODE_BACK: 
       if(mWebView.canGoBack()){ 
        if((webUrl.contains("url"))){ 
         new AlertDialog.Builder(this).setTitle("title") 
           .setIcon(R.mipmap.ic_launcher) 
           .setMessage("Are you sure you want to exit the app?") 
           .setPositiveButton("yes", new DialogInterface.OnClickListener() { 
            @Override 
            public void onClick(DialogInterface dialog, int which) { 

             Intent intent = new Intent(Intent.ACTION_MAIN); 
             intent.addCategory(Intent.CATEGORY_HOME); 
             intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
             startActivity(intent); 
             finish(); 
            } 
           }).setNegativeButton("no", null).show(); 
        } 
        else 
        if((webUrl.contains("url"))){ 
         Toast.makeText(this, "Press the X button.", 
           Toast.LENGTH_SHORT).show(); 
        } 
        else 
        if((webUrl.contains("url")||(webUrl.contains("file:///android_asset/error_page.html")||webUrl.contains("url")))) { 
         new AlertDialog.Builder(this).setTitle("title") 
           .setIcon(R.mipmap.ic_launcher) 
           .setMessage("Are you sure you want to exit the app?") 
           .setPositiveButton("yes", new DialogInterface.OnClickListener() { 
            @Override 
            public void onClick(DialogInterface dialog, int which) { 

             Intent intent = new Intent(Intent.ACTION_MAIN); 
             intent.addCategory(Intent.CATEGORY_HOME); 
             intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
             startActivity(intent); 
             finish(); 
            } 
           }).setNegativeButton("no", null).show(); 
        }else { 
         mWebView.goBack(); 
        } 
       }else { 
        new AlertDialog.Builder(this).setTitle("title") 
          .setIcon(R.mipmap.ic_launcher) 
          .setMessage("Are you sure you want to exit the app?") 
          .setPositiveButton("yes", new DialogInterface.OnClickListener() { 
           @Override 
           public void onClick(DialogInterface dialog, int which) { 

            Intent intent = new Intent(Intent.ACTION_MAIN); 
            intent.addCategory(Intent.CATEGORY_HOME); 
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
            startActivity(intent); 
            finish(); 
           } 
          }).setNegativeButton("no", null).show(); 
       } 
       return true; 
     } 
    } 
    return super.onKeyDown(keyCode, event); 
} 

}

答えて

0

OnActivityResultでこのコードを試してください:

if (intent.getDataString() != null) { 
    results = new Uri[] { 
     Uri.parse(intent.getDataString()) 
    }; 
} else { 
    if (Build.VERSION.SDK_INT >= 16) { 
     if (intent.getClipData() != null) { 
      final int numSelectedFiles = intent.getClipData().getItemCount(); 
      results = new Uri[numSelectedFiles]; 
      for (int i = 0; i < numSelectedFiles; i++) { 
       results[i] = intent.getClipData().getItemAt(i).getUri(); 
      } 
     } 
    } 
} 
関連する問題