为什么,在触摸Android屏幕时它什么都不做?

时间:2015-08-01 07:25:30

标签: java android android-studio

这是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();
        }
    }
}

工作正常。也许我需要在Android设备上启用某些功能?

我的Android设备现在通过USB连接到PC并正常工作。

当我在调试模式下运行我的程序并触摸屏幕时,它永远不会停止:

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

我在行上添加了一个断点:float eventX = event.getX(); 但触摸屏幕什么也没做。

2 个答案:

答案 0 :(得分:0)

您根本没有注册OnTouchListener。首先使用anonymousclass注册OnTouchListener,或者只在类中实现它

从您的代码中,您需要此SingleTouchEventView视图的侦听器。只需添加" {{1}}"为了上课。因为您已经在代码中重写了onTouch方法。

答案 1 :(得分:0)

删除"扩展ActionbarActivity"时,您必须更改style.xml! 请检查此change appTheme