我有一類我做,使簡單的GET請求,並顯示與響應敬酒messege http請求......從巴頓VS從
如果我叫從底事件的函數點擊顯示器返回數據的消息傳遞,就好了。
但如果我叫從brodcast reciver類相同的功能,它只是顯示我相信的,這顯示了massege我能得到的數據之前,並與數據「」(空)
的massege它等待數據的按鈕..
我該如何使它從brodcast reciver工作?
類:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import android.app.Activity;
import android.content.Context;
import android.widget.Toast;
public class myclass{
public static void doHttpRequest(String param1, Context context){
String ret="";
try {
URL url = new URL("http://website.com/page?param="+param1);
HttpURLConnection con = (HttpURLConnection) url
.openConnection();
ret=readStream(con.getInputStream());
} catch (Exception e) {
e.printStackTrace();
}
CharSequence text = "return data- "+ret;
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
private static String readStream(InputStream in) {
BufferedReader reader = null;
String line = "";
String alllines = "";
try {
reader = new BufferedReader(new InputStreamReader(in));
while ((line = reader.readLine()) != null) {
alllines=alllines+line;
}
return alllines;
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return alllines;
}
}
從按鈕正常工作:
final Button button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
myclass.doHttpRequest("blabla", getBaseContext());
}});
來自不同類的brodcast reciver巫婆它不會返回數據,表示的是烤麪包..
public class CustomBroadcastReceiver extends BroadcastReceiver {
private static final String TAG = "CustomBroadcastReceiver";
@Override
public void onReceive(Context context, Intent intent) {
myclass.doHttpRequest("blabla", context);
break;
} }
}
請幫助.... :)感謝
提示: '公共抽象無效的onReceive(上下文語境,意圖意圖)' 這個方法總是被調用它的進程的主線程中,除非你明確地要求它使用registerReceiver(不同的線程調度BroadcastReceiver,IntentFilter,String,android.os.Handler)。當它在主線程上運行時,不應該在其中執行長時間運行的操作。 來源:http://developer.android.com/reference/android/content/BroadcastReceiver.html –