2

I want to connect to a URL and disconnect after that. But after my Update on Android 4.1 (worked before on 2.3.7) it doesn't work anymore! :/

Why? I have no Idea:

public void insert_into_Mysql() {
    URL url = new URL("http://***/insertOrder.php?product="+product+"&owner="+owner);
    HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
    try {
        openActivityOverview(product);  
    } finally {
        urlConnection.disconnect();
    }

Noting is inserted in the MySql-Table...

Thanks for Help! :)

4

3 回答 3

2

您需要使用AsyncTask 来打开 url 连接。

例如,请参阅以下链接:

http://www.vogella.com/articles/AndroidPerformance/article.html

http://androidresearch.wordpress.com/2012/03/17/understanding-asynctask-once-and-forever/

于 2012-11-01T13:09:23.057 回答
2

在线程中写入 url 连接。

从 Android API v15 开始,它不需要在主线程上工作的繁重进程。所以你应该将你的逻辑移动到另一个线程,比如下面的源代码:

new Thread(new Runnable() {
   public void run() {
        // your logic
   }                        
}).start();

更多信息请参考http://developer.android.com/guide/practices/responsiveness.html

于 2012-11-01T13:05:32.980 回答
1

您可以使用 AsyncTask 执行后台操作,例如联网。

private class ATask extends AsyncTask
{

    public ATask()
    {
    }

    @Override
    protected Object doInBackground(Object... params) 
    {
        // Background logic here.
        return null;
    }   

    @Override
    protected void onPostExecute(Object result) 
    {
        // Foreground logic here.
    }
}

或者,您可以禁用主线程上的无网络限制,但这通常被认为是一个坏主意,并且可能不应该在玩耍之外使用。

StrictMode.ThreadPolicy 策略 = new StrictMode.ThreadPolicy.Builder().permitAll().build(); StrictMode.setThreadPolicy(policy);

于 2012-11-01T13:28:31.987 回答