【问题标题】:Retrofit for uploading video-networkonmainthreadexception用于上传视频的改造-networkonmainthreadexception
【发布时间】:2016-02-14 02:00:51
【问题描述】:

我想将视频(从图库中选择)上传到服务器(localhost-Wampserver 在我的计算机上运行 Apache 2.4.4)。从异常和搜索中,我发现网络操作不应该发生在运行 UI 的线程中。但我该怎么做呢?我的代码如下:

PostFile

public final class PostFile 
{
  public static final MediaType MEDIA_TYPE_MARKDOWN
      = MediaType.parse("vide/mp4");

  private final OkHttpClient client = new OkHttpClient();

  public void run(String path) throws Exception 
  {
    File file = new File(path);

    Request request = new Request.Builder()
        .url("http://192.168.1.7")
        .post(RequestBody.create(MEDIA_TYPE_MARKDOWN, file))
        .build();

    Response response = client.newCall(request).execute();
    if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);

        System.out.println(response.body().string());
  }

}

MainActivity.java

public class MainActivity extends Activity 
{
    private static int RESULT_LOAD_IMG = 1;
    String decodableString;

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

    public void loadImagefromGallery(View view) 
    {
        // Create intent to Open Image applications like Gallery, Google Photos
        Intent galleryIntent = new Intent(Intent.ACTION_PICK,
                android.provider.MediaStore.Video.Media.EXTERNAL_CONTENT_URI);
        // Start the Intent
        startActivityForResult(galleryIntent, RESULT_LOAD_IMG);
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) 
    {
        super.onActivityResult(requestCode, resultCode, data);
        try {
            // When a video is picked
            if (requestCode == RESULT_LOAD_IMG && resultCode == RESULT_OK
                    && null != data) 
            {
                // Get the video from data
                Uri selectedVideo = data.getData();
                String[] filePathColumn = { MediaStore.Video.Media.DATA };
                Cursor cursor = getContentResolver().query(selectedVideo,
                        filePathColumn, null, null, null);
                cursor.moveToFirst();
                int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                decodableString = cursor.getString(columnIndex);
                Log.i("mok",decodableString);
                cursor.close();
                new PostFile().run(decodableString);
                Log.i("mok","done");
            } else 
            {
                Toast.makeText(this, "You haven't picked any video",
                        Toast.LENGTH_LONG).show();
            }
        } catch (Exception e) 
        {
            e.printStackTrace();
            Toast.makeText(this, "Something went wrong", Toast.LENGTH_LONG)
                        .show();
            }
        }
}

堆栈跟踪:

【问题讨论】:

  • 下次不要截图错误。只需复制它并像代码一样粘贴。它更容易阅读。
  • @DamianKozlak 我不知道如何在 logcat 中(一次全部)复制它们
  • 用鼠标选择它... :)
  • @DamianKozlak 相信我这是不可能的。是一行一行的。我有这么多使用鼠标的专业知识;)

标签: java android multithreading exception retrofit


【解决方案1】:

AsyncTask 提供doInBackground 方法。

http://developer.android.com/reference/android/os/AsyncTask.html

【讨论】:

    【解决方案2】:

    您需要做的就是了解如何使用 Retrofit。 这里解释了文件上传如何与 Retrofit 一起工作以及如何做到这一点。

    https://futurestud.io/blog/retrofit-how-to-upload-files/

    在后台执行查询应该使用回调机制。查询进入后台,回调在主线程上执行。

    How to implement an async Callback using Square's Retrofit networking library

    使用-squares-retrofit-networking-library 在这里您可以找到使用回调定义改造休息方法的好例子。

    这是你需要的一切。甚至不要尝试更改线程策略,强烈建议不要这样做。

    【讨论】:

    • 赞成。我忘记了@mok 正在使用 Retrofit,所以使用 Retrofit 的方法而不是 AsyncTask 是更好的解决方案。
    • @DamianKozlak 完全正确。我真的很困惑,因为我认为使用 Retrofit 我不需要使用 AsyncTask。
    • 感谢您的参考,尤其是最后一段。但是,他们两个似乎都太先进了。我的意思是我没有使用这些 API 的先验知识。请您举一个可行的例子(不管它多么简单,只要它有效,然后我会理解其他的事情)。
    • stackoverflow.com/questions/26500036/using-retrofit-in-android 在这里你可以找到一个很好的适配器、接口和使用它们的例子。投票最多的答案
    【解决方案3】:

    您需要使用AsyncTask 执行它

    【讨论】:

      猜你喜欢
      • 2014-06-23
      • 2023-03-13
      • 2017-10-15
      • 1970-01-01
      • 2017-05-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-08
      相关资源
      最近更新 更多