尝试在我的PC和手机之间进行简单的通信测试(目前正在使用模拟器进行测试) 我创建了一个运行正常的c#Rest服务
网址:http://192.168.1.100:8000/REST/client 结果:
TEST STRING!
我的Android应用程序中有一个Call函数,如下所示:
public void call()
{
String URL = "http://192.168.1.100:8000/REST/client";
EditText txt = (EditText) findViewById(R.id.Textbox);
String Result = "";
Toast.makeText(Helloworld.this, "STARTING", Toast.LENGTH_SHORT);
HttpClient hc = new DefaultHttpClient();
HttpGet request = new HttpGet(URL);
ResponseHandler<String> handler = new BasicResponseHandler();
try{
Result = hc.execute(request,handler);
}
catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
txt.setText(Result);
Toast.makeText(Helloworld.this, Result, Toast.LENGTH_SHORT);
hc.getConnectionManager().shutdown();
}
我通过一个按钮来调用它,
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
EditText txt = (EditText) findViewById(R.id.Textbox);
txt.setText("calling!", TextView.BufferType.EDITABLE );
call();
}
});
几个问题,这个代码就是这样,如果我运行它我没有看到任何Toast msgs并且文本框没有更新。但是如果我从onclick中删除了call(),则会更新文本框。好像电话挂了,但即使是这样,我也不会看到文本更新了吗?
答案 0 :(得分:1)
假设它可以到达您的服务等,您应该使用AsyncTasks并调用invalidate以确保更新显示在屏幕上。此外,您必须在.show()
上致电makeText()
。我没有测试过这个,但它应该是正确的想法。
public void doBeginCall()
{
Toast.makeText(this, "Call started", Toast.LENGTH_SHORT).show();
new CallTask().execute(null);
}
public void onCallComplete(String result)
{
Toast.makeText(this, "Call complete", Toast.LENGTH_SHORT).show();
((EditText)findViewById(R.id.Textbox)).setText(result);
invalidate();
}
class CallTask extends AsyncTask<String, String, String>
{
protected void onPostExecute(String result)
{
onCallComplete(result);
}
@Override
protected TaskResult doInBackground(String... params)
{
return call();
}
}
public String call()
{
String URL = "http://192.168.1.100:8000/REST/client";
String Result = "";
HttpClient hc = new DefaultHttpClient();
HttpGet request = new HttpGet(URL);
HttpResponse hr = null;
BasicResponseHandler handler = new BasicResponseHandler();
try
{
hr = hc.execute(request);
}
catch (ClientProtocolException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
hc.getConnectionManager().shutdown();
return handler.handleResponse(hr);
}
此外,您需要为您的应用设置适当的权限。在清单xml中包含以下行:
<uses-permission android:name="android.permission.INTERNET"/>