【发布时间】:2017-03-14 16:33:16
【问题描述】:
我不确定我正在尝试做的事情是否有意义,但我会试一试: 我的手机充当客户端,我需要将有关运动事件的数据发送到服务器。 我正在处理与 AsyncTask 的通信,因此我想在 AsyncTask 类中实现 onTouch 方法。 我让我的 AsyncTask 实现了 View.OnTouchListener,但事件并没有真正到达我的 AsyncTask 中的 onTouch 方法。 我猜我错过了一些非常基本的东西..
这里是 AsyncTask 代码:
public class tpAsyncTask extends AsyncTask<String,String,String> implements View.OnTouchListener {
Context context;
boolean isCancelled = false;
float prevX;
float prevY;
Socket socket;
ObjectOutputStream oos;
private final static String TAG = "ME ASYNCTASK LOGGER: ";
public tpAsyncTask(Context context){
this.context = context;
}
@Override
protected String doInBackground(String... strings) {
String IP = strings[0];
String port = strings[1];
try {
InetAddress inetAddress = InetAddress.getByName(IP);
socket = new Socket(inetAddress,Integer.parseInt(port));
OutputStream os = socket.getOutputStream();
oos = new ObjectOutputStream(os);
while(!isCancelled()) {
Thread.sleep(1000);
}
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onCancelled() {
super.onCancelled();
try {
oos.flush();
oos.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
// PROBLEM IS THAT THE APP NEVER REACH HERE
if(!isCancelled()) {
switch(motionEvent.getAction()) {
case MotionEvent.ACTION_MOVE:
{
Log.d(TAG, "ACTION MOVE IS PREFORMED");
}
case MotionEvent.ACTION_DOWN:
{
Log.d(TAG, "ACTION DOWN IS PREFORMED");
}
}
}
return false;
}}
谢谢
编辑,已解决:
正如这里评论的许多家伙所说,我必须将我的 onTouch 实现附加到特定视图。
所以,因为我需要我的 onTouch 事件来包含所有屏幕的大小,所以我只是创建了一个相对布局的对象,并将它传递给我的 asyncTask(实现 OnTouchListener)的构造函数,并在构造函数上设置myRelativeLayout.setOnTouchListerner(this)。
这就是诀窍 - 现在只要我触摸屏幕,就会调用 asyncTask 中的 onTouch 方法。
非常感谢大家。
【问题讨论】:
-
在 PostExecute() 中设置 onTouchListener()
标签: android android-asynctask motionevent