我做了一个类,它发出一个简单的 GET 请求并显示带有响应的 toast messege ...
如果我从底部事件单击调用该函数,它会显示带有返回数据的消息,就可以了。
但是如果我从广播接收器类中调用相同的函数,它只会显示带有数据''(null)的masege
我相信它会在我获取数据之前显示按摩,并使用按钮等待数据..
我怎样才能让它从广播接收器工作?
班上:
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());
}});
来自不同班级的广播接收者女巫,它不会返回数据,但会显示吐司..
public class CustomBroadcastReceiver extends BroadcastReceiver {
private static final String TAG = "CustomBroadcastReceiver";
@Override
public void onReceive(Context context, Intent intent) {
myclass.doHttpRequest("blabla", context);
break;
} }
}
请帮助.... :) 谢谢