简体   繁体   English

为什么在触摸Android屏幕时却什么也没做?

[英]Why, when touching the Android screen it does nothing?

This is the MainActivity.java 这是MainActivity.java

package com.test.webservertest;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.support.v7.app.ActionBarActivity;
import android.util.AndroidRuntimeException;
import android.util.Xml;
import android.view.Menu;
import android.view.MenuItem;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.content.Context;
import android.view.View.OnClickListener;

import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.util.EncodingUtils;
import org.json.JSONObject;
import org.json.JSONTokener;

import java.io.DataOutputStream;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.Socket;
import java.net.URL;
import java.net.UnknownHostException;
import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.Locale;
import java.net.URLConnection;

import java.net.HttpURLConnection;
import java.io.*;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.logging.Logger;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends ActionBarActivity
{
    private static final int MY_DATA_CHECK_CODE = 0;
    public static MainActivity currentActivity;
    TextToSpeech mTts;
    private String targetURL;
    private String urlParameters;
    private Button btnClick;
    private String clicking = "clicked";
    private final String[] ipaddresses = new String[2];
    private final Integer[] ipports = new Integer[2];
    private TextView text;
    private Socket socket;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //setContentView(new SingleTouchEventView(this, null));

        /*ipaddresses[0] = "10.0.0.3";
        ipaddresses[1] = "10.0.0.2";
        ipports[0] = 8098;
        ipports[1] = 8088;*/

        //addListenerOnButton();
        currentActivity = this;
        initTTS();
    }

    public void addListenerOnButton() {

        /*btnClick = (Button) findViewById(R.id.checkipbutton);

        btnClick.setOnClickListener(new OnClickListener()
        {
            @Override
            public void onClick(View arg0)
            {
                text = (TextView) findViewById(R.id.textView2);
                try
                {

                } catch (Exception e)
                {
                    text.setText("Connection Failed");
                }
            }
        });*/
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu)
    {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item)
    {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings)
        {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    /**
     * Dispatch onStart() to all fragments.  Ensure any created loaders are
     * now started.
     */   

    @Override
    protected void onStart()
    {
        super.onStart();
        TextToSpeechServer.main(null);
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    public void initTTS() {
        Intent checkIntent = new Intent();
        checkIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
        startActivityForResult(checkIntent, MY_DATA_CHECK_CODE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(requestCode == MY_DATA_CHECK_CODE) {
            if(resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS) {
                mTts = new TextToSpeech(getApplicationContext(), new OnInitListener() {
                    @Override
                    public void onInit(int i) {

                        if(i == TextToSpeech.SUCCESS) {
                            int result = mTts.setLanguage(Locale.US);
                            if(result == TextToSpeech.LANG_AVAILABLE
                                    || result == TextToSpeech.LANG_COUNTRY_AVAILABLE) {
                                mTts.setPitch(1);
                                mTts.speak(textforthespeacch, TextToSpeech.QUEUE_FLUSH, null);
                            }
                        }
                    }
                });
            } else {
                Intent installIntent = new Intent();
                installIntent.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
                startActivity(installIntent);
            }
        }
    }

    public static String textforthespeacch = "";
    public static void TextToSpeak(String text) {
        textforthespeacch = text;
    }

    private boolean is_start = true;
    public class SingleTouchEventView extends View {
        private Paint paint = new Paint();
        private Path path = new Path();
        private Path circlePath = new Path();

        public SingleTouchEventView(Context context, AttributeSet attrs) {
            super(context, attrs);

            paint.setAntiAlias(true);
            paint.setStrokeWidth(6f);
            paint.setColor(Color.BLACK);
            paint.setStyle(Paint.Style.STROKE);
            paint.setStrokeJoin(Paint.Join.ROUND);
        }

        @Override
        protected void onDraw(Canvas canvas) {
            canvas.drawPath(path, paint);
            canvas.drawPath(circlePath, paint);
        }

        @Override
        public boolean onTouchEvent(MotionEvent event)
        {
            float eventX = event.getX();
            float eventY = event.getY();

            float lastdownx = 0;
            float lastdowny = 0;

            switch (event.getAction())
            {
                case MotionEvent.ACTION_DOWN:
                    path.moveTo(eventX, eventY);
                    circlePath.addCircle(eventX, eventY, 50, Path.Direction.CW);
                    lastdownx = eventX;
                    lastdowny = eventY;

                    Thread t = new Thread(new Runnable()
                    {
                        @Override
                        public void run()
                        {
                            byte[] response = null;
                            if (is_start == true)
                            {
                                response = Get("http://10.0.0.2:8098/?cmd=start");
                                is_start = false;
                            }
                            else
                            {
                               response = Get("http://10.0.0.2:8098/?cmd=stop");
                                is_start = true;
                            }

                            if (response!=null)
                            {
                                String a = null;
                                try
                                {
                                    a = new String(response,"UTF-8");
                                    textforthespeacch = a;
                                    MainActivity.currentActivity.initTTS();
                                } catch (UnsupportedEncodingException e)
                                {
                                    e.printStackTrace();
                                }
                                Logger.getLogger("MainActivity(inside thread)").info(a);
                            }
                        }
                    });
                    t.start();
                    return true;
                case MotionEvent.ACTION_MOVE:
                    path.lineTo(eventX, eventY);
                    break;
                case MotionEvent.ACTION_UP:
                    // nothing to do
                    circlePath.reset();   
                    break;
                default:
                    return false;
            }    
            // Schedules a repaint.
            invalidate();
            return true;
        }
    }

    private byte[] Get(String urlIn)
    {
        URL url = null;

        String urlStr = urlIn;

        if (urlIn!=null)
            urlStr=urlIn;

        try
        {
            url = new URL(urlStr);
        } catch (MalformedURLException e)
        {
            e.printStackTrace();
            return null;
        }
        HttpURLConnection urlConnection = null;
        try
        {

            urlConnection = (HttpURLConnection) url.openConnection();
            InputStream in = new BufferedInputStream(urlConnection.getInputStream());

            byte[] buf=new byte[10*1024];
            int szRead = in.read(buf);

            byte[] bufOut;   
            if (szRead==10*1024)
            {
                throw new AndroidRuntimeException("the returned data is bigger than 10*1024.. we don't handle it..");
            }
            else
            {
                bufOut = Arrays.copyOf(buf, szRead);
            }
            return bufOut;
        }
        catch (IOException e)
        {
            e.printStackTrace();
            return null;
        }
        finally
        {
            if (urlConnection!=null)
                urlConnection.disconnect();
        }
    }
}

It was working fine. 工作正常。 Maybe I need to enable something on my Android device? 也许我需要在Android设备上启用某些功能?

My Android device is connected now to the PC via USB and working fine. 我的Android设备现在已通过USB连接到PC,并且工作正常。

When I'm running my program in debug mode and touch the screen it never stop on: 当我在调试模式下运行程序并触摸屏幕时,它永远不会停止运行:

@Override
        public boolean onTouchEvent(MotionEvent event)
        {
            float eventX = event.getX();

I added a break point on the line: float eventX = event.getX(); 我在行上添加了一个断点: float eventX = event.getX(); But touching the screen does nothing. 但是触摸屏幕无济于事。

You are not at all registering the OnTouchListener. 您根本没有注册OnTouchListener。 First register OnTouchListener using anonymousclass or just implements it in your class 首先使用匿名类注册OnTouchListener或仅在您的类中实现它

From your code you need the listener for this SingleTouchEventView view. 从您的代码中,您需要此SingleTouchEventView视图的侦听器。 Just add " implements View.OnTouchListenter " for the class. 只需为该类添加“ implements View.OnTouchListenter ”。 Because you have already overridden onTouch method in your code. 因为您已经在代码中覆盖了onTouch方法。

You have to change your style.xml when you remove "Extends ActionbarActivity"! 删除“扩展ActionbarActivity”时,必须更改style.xml! Check this change appTheme 检查此更改应用

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM