【问题标题】:Android Service :upload image to a http serverAndroid服务:上传图片到http服务器
【发布时间】:2014-06-05 08:31:53
【问题描述】:

我正在尝试将图像从我的 android 手机上传到服务中的 http 服务器。 好吧,我在活动中有一个 brodcastreceiver,每次有数据时,它都会将其发送到服务进行上传。但是,我的代码只上传一次(我在服务器中检查它)然后崩溃(没有任何错误消息)。

希望有人能告诉我崩溃的原因,提前谢谢。

PS:我的疑惑在于 Looper.prepare();和 Looper.loop();我对他们不是很熟悉,即使在阅读了他们之后。

这是我的服务的 onStartCommand :

     public int onStartCommand(Intent intent, int flags, int startId) {
        Toast.makeText(getBaseContext(), "Service started 2", Toast.LENGTH_LONG).show();
        int rssi1 = intent.getIntExtra("key1", 0);
        int rssi2 = intent.getIntExtra("key2", 0);
        int rssi3 = intent.getIntExtra("key3", 0);
        Toast.makeText(getBaseContext(), "Service started 2" + rssi1 +" "+ rssi2 + " " + rssi3, Toast.LENGTH_LONG).show();

         Toast.makeText(getBaseContext(), "Service Appel 2", Toast.LENGTH_LONG).show();
            upLoadServerUri = "http://192.168.1.150:8080/UploadToServer.php";
            mContext = getApplicationContext();
          folder = new File("/storage/sdcard");
          new Thread(new Runnable()
            {
                @Override
                public void run() 
                {   Looper.prepare();
                    imagepath = Environment.getExternalStorageDirectory().toString() + "/downloadedfile1.jpg";
                    uploadFile(imagepath);

                }
            }).start();
          Looper.loop();
        return START_STICKY;
    }

【问题讨论】:

  • 你最后做了什么?

标签: android service upload broadcastreceiver httpserver


【解决方案1】:

您无需致电Looper.prepare();Looper.loop();。您可以使用AsyncTask 在工作线程中执行上传任务。像这样:

class UploadTask extends AsyncTask<String, Object, Object> {

    @Override
    protected Object doInBackground(String... content) {
        uploadFile(content[0]);
        return null;
    }
}

在服务中:

public int onStartCommand(Intent intent, int flags, int startId) {
    imagepath = Environment.getExternalStorageDirectory().toString() + "/downloadedfile1.jpg";
    new UploadTask().execute(imagepath, null, null);
}

PS:你可以参考this熟悉Looper和Handler的东西。

【讨论】:

    【解决方案2】:

    那么我相信你的问题不是上传,因为上传了一张图片......

    因为您尝试上传,而不是 UI 任务,您可以做的是删除服务并在 BroadCastReceiver(BCR) 本身中执行...每当在 BCR 中调用接收时,您可以尝试上传...

    希望对你有帮助

    【讨论】:

    • 谢谢@user1915922 ,有趣的旗帜提示,我会试试的。
    猜你喜欢
    • 2015-10-20
    • 1970-01-01
    • 1970-01-01
    • 2014-10-13
    • 2014-07-18
    • 1970-01-01
    • 1970-01-01
    • 2017-05-04
    • 2011-06-01
    相关资源
    最近更新 更多