智能小车移动端主要代码

之前做的一个智能小车手机端的逻辑代码

链接: https://pan.baidu.com/s/1UY_jDgqtWcg6gU9hdHnDZg 提取码: 69au

package com.example.xtyclient;
 
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.Socket;
import java.net.SocketException;
import java.util.Enumeration;
 
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.StrictMode;
import android.R.integer;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;
 
public class MainActivity extends Activity
{
    String urlnew="http://192.168.253.1";
    int url_flag=-1;
    //String urlnew_old="http://192.168.253.1";
    int reload_time=0;
    int connect_flag=-1;
    WebView webView=null;
    Button Button_Up;
    Button Button_Down;
    Button Button_Left;
    Button Button_Right;
    Button Button_Stop;
 
    Button ButtonConnectServer;
    Button ButtonClientSend;
    Button buttonChangeName;
 
    Button Button_Camera_Up1;
    Button Button_Camera_Down1;
 
    TextView TextViewClientInfo;
    EditText EditTextClientConnect;
    EditText EditTextClientSend;
    ScrollView mScrollView=null;
    static String StringEditTextClientInfo;
    static String StringTextViewClientInfo;
    static String stringclientname="";
    //    static String stringclientname="client";
    String stringhistory="";
 
    //    int Socket_ClientPort=65519;
    int Socket_ClientPort=9999;
    static String Socket_CLientIp;
    private Socket mSocketClient = null;
    static BufferedReader mBufferedReaderServer = null;
    static PrintWriter mPrintWriterServer = null;
    static BufferedReader mBufferedReaderClient = null;
    static PrintWriter mPrintWriterClient = null;
    Boolean flagClientConnectYes=false;
    Handler mHandler;
    private Thread mThreadClient = null;
 
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
 
        StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
                .detectDiskReads()
                .detectDiskWrites()
                .detectNetwork()   // or .detectAll() for all detectable problems
                .penaltyLog()
                .build());
        StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
                .detectLeakedSqlLiteObjects()
                .penaltyLog()
                .penaltyDeath()
                .build());
 
        mHandler=new Handler()
        {
            @Override
            public void handleMessage(Message msg)
            {
                super.handleMessage(msg);
                reload_time=(reload_time+1)%65536;
                if (url_flag==-1&&urlnew.contains("8090"))
                {
                    WebSettings settings = webView.getSettings();
                    settings.setJavaScriptEnabled(true);
                    webView.loadUrl(urlnew);
                    url_flag=1;
                }
                if (reload_time%10==0)
                {
                    webView.reload();
                    webView.loadUrl(urlnew);
                    EditTextClientSend.setText("time:"+reload_time);
                }
 
                switch (msg.what)
                {
                    case 0x111://TextViewServer 更改消息
//                  TextViewClientInfo.append(StringTextViewClientInfo);
                        stringhistory+=StringTextViewClientInfo;
                        TextViewClientInfo.setText(stringhistory);
                        mScrollView.scrollTo(0,TextViewClientInfo.getHeight());
                        break;
                    case 0x112://Edittext 更改消息
//                  TextViewClientInfo.append(StringTextViewClientInfo);
                        stringhistory+=StringTextViewClientInfo;
                        TextViewClientInfo.setText(stringhistory);
                        mScrollView.scrollTo(0,TextViewClientInfo.getHeight());
                        EditTextClientSend.setText("");
                        break;
                    case 0x113:
 
                        break;
                    default:
                        break;
                }
            }
        };
        //更改客户端名字
        buttonChangeName.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                dialoglogin d1=new dialoglogin(MainActivity.this);
                d1.show();
            }
        });
 
        //连接服务器
        ButtonConnectServer.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                //isConnecting = true;
                //ButtonConnectServer.setText("停止连接");
                //EditTextClientConnect.setEnabled(false);
                mThreadClient = new Thread(mRunnable);
                mThreadClient.start();
                System.out.println("Main Client连接成功!");
            }
        });
        //向服务器发送消息
        ButtonClientSend.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                // TODO Auto-generated method stub
                if(flagClientConnectYes==true)
                {
                    String msgText =EditTextClientSend.getText().toString();//取得编辑框中我们输入的内容
                    if(msgText.length()<=0)
                    {
                        Toast.makeText(getApplicationContext(), "发送内容不能为空!", Toast.LENGTH_SHORT).show();
                    }
                    else
                    {
                        if (ButtonConnectServer.VISIBLE==View.VISIBLE)
                        {
                            ButtonConnectServer.setVisibility(View.GONE);
                            EditTextClientConnect.setVisibility(View.GONE);
                        }
                        try
                        {
                            System.out.println("发送消息《");
                            mPrintWriterClient.print(stringclientname+" :"+msgText);//发送给服务器
                            System.out.println("发送消息||");
                            mPrintWriterClient.flush();
                            System.out.println("发送消息》");
                            StringTextViewClientInfo =stringclientname+" :"+ msgText + "\n";//消息换行
                            Message msg = new Message();
                            msg.what = 0x112;
                            mHandler.sendMessage(msg);
                        }
                        catch (Exception e)
                        {
                            // TODO: handle exception
                            Toast.makeText(getApplicationContext(), "发送异常:" + e.getMessage(), Toast.LENGTH_SHORT).show();
                        }
                    }
                }
                else
                {
                    Toast.makeText(getApplicationContext(), "没有连接", Toast.LENGTH_SHORT).show();
                }
 
            }
        });
 
        Button_Down.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                try
                {
                    mPrintWriterClient.print("5");//发送给服务器
                    mPrintWriterClient.flush();
                }
                catch (Exception e)
                {
                    // TODO: handle exception
                    Toast.makeText(getApplicationContext(), "发送异常:" + e.getMessage(), Toast.LENGTH_SHORT).show();
                }
            }
        });
 
        Button_Up.setOnClickListener(new View.OnClickListener()
        {
 
            @Override
            public void onClick(View v)
            {
                try
                {
                    mPrintWriterClient.print("2");//发送给服务器
                    mPrintWriterClient.flush();
                }
                catch (Exception e)
                {
                    // TODO: handle exception
                    Toast.makeText(getApplicationContext(), "发送异常:" + e.getMessage(), Toast.LENGTH_SHORT).show();
                }
            }
        });
 
        Button_Left.setOnClickListener(new View.OnClickListener()
        {
 
            @Override
            public void onClick(View v)
            {
                try
                {
                    mPrintWriterClient.print("4");//发送给服务器
                    mPrintWriterClient.flush();
                }
                catch (Exception e)
                {
                    // TODO: handle exception
                    Toast.makeText(getApplicationContext(), "发送异常:" + e.getMessage(), Toast.LENGTH_SHORT).show();
                }
            }
        });
 
        Button_Right.setOnClickListener(new View.OnClickListener()
        {
 
            @Override
            public void onClick(View v)
            {
                try
                {
                    mPrintWriterClient.print("6");//发送给服务器
                    mPrintWriterClient.flush();
                }
                catch (Exception e)
                {
                    // TODO: handle exception
                    Toast.makeText(getApplicationContext(), "发送异常:" + e.getMessage(), Toast.LENGTH_SHORT).show();
                }
            }
        });
 
        Button_Stop.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                try
                {
                    mPrintWriterClient.print("1");//发送给服务器
                    mPrintWriterClient.flush();
                }
                catch (Exception e)
                {
                    // TODO: handle exception
                    Toast.makeText(getApplicationContext(), "发送异常:" + e.getMessage(), Toast.LENGTH_SHORT).show();
                }
            }
        });
 
        //camera
        Button_Camera_Up1.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                try
                {
                    mPrintWriterClient.print("a");//发送给服务器
                    mPrintWriterClient.flush();
                }
                catch (Exception e)
                {
                    // TODO: handle exception
                    Toast.makeText(getApplicationContext(), "发送异常:" + e.getMessage(), Toast.LENGTH_SHORT).show();
                }
            }
        });
 
        Button_Camera_Down1.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                try
                {
                    mPrintWriterClient.print("c");//发送给服务器
                    mPrintWriterClient.flush();
                }
                catch (Exception e)
                {
                    // TODO: handle exception
                    Toast.makeText(getApplicationContext(), "发送异常:" + e.getMessage(), Toast.LENGTH_SHORT).show();
                }
            }
        });
 
    }
    public void initView()
    {
        //WebView webView=null;
        webView  = (WebView)  findViewById(R.id.webView1);
        // webView.setMotionEventSplittingEnabled(split)
        // webView.setMovementMethod(new ScrollingMovementMethod());
        webView.getSettings().setSupportZoom(true);
        webView.setWebViewClient(new WebViewClient(){
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return true;
            }
        });
 
        webView.loadUrl("www.baidu.com");
//        Button_Up=(Button)findView
        Button_Down=(Button)findViewById(R.id.button_down);
        Button_Up=(Button)findViewById(R.id.button_up);
        Button_Left=(Button)findViewById(R.id.button_left);
        Button_Right=(Button)findViewById(R.id.button_right);
        Button_Stop=(Button)findViewById(R.id.button_stop);
 
        Button_Camera_Up1=(Button)findViewById(R.id.button_camera_up1);
        Button_Camera_Down1=(Button)findViewById(R.id.button_camera_down1);
 
        ButtonConnectServer=(Button)findViewById(R.id.ButtonContentServe);
        ButtonClientSend=(Button)findViewById(R.id.buttonservesend);
        EditTextClientConnect=(EditText)findViewById(R.id.editTextClient);
        EditTextClientConnect.setText(Global.getHostIP()+":"+Socket_ClientPort);
        EditTextClientSend=(EditText)findViewById(R.id.editTextSend);
        TextViewClientInfo=(TextView)findViewById(R.id.textViewClientInfo);
//      TextViewClientInfo.setMovementMethod(new ScrollingMovementMethod());
        buttonChangeName=(Button)findViewById(R.id.buttonchangename);
//      TextViewClientInfo.setMovementMethod(ScrollingMovementMethod.getInstance());
        mScrollView =(ScrollView)findViewById(R.id.scrollView);
    }
 
    private Runnable    mRunnable   = new Runnable()
    {
        public void run()
        {
            String msgText =EditTextClientConnect.getText().toString();
            if(msgText.length()<=0)
            {
                //Toast.makeText(mContext, "IP不能为空!", Toast.LENGTH_SHORT).show();
                StringTextViewClientInfo = "IP地址不合法\n";//消息换行
                Message msg = new Message();
                msg.what = 0x111;
                mHandler.sendMessage(msg);
                return;
            }
            int start = msgText.indexOf(":");
            if( (start == -1) ||(start+1 >= msgText.length()) )
            {
                StringTextViewClientInfo = "IP地址不合法\n";//消息换行
                Message msg = new Message();
                msg.what = 0x111;
                mHandler.sendMessage(msg);
                return;
            }
            String sIP = msgText.substring(0, start);
            //@@@
            //urlnew=sIP+":8090/?action=stream";
            urlnew="http://"+sIP+":8090/javascript_simple.html";
            //webView.loadUrl(urlnew);
            String sPort = msgText.substring(start+1);
            int port = Integer.parseInt(sPort);
 
            Log.d("gjz", "IP:"+ sIP + ":" + port);
 
            try
            {
                //连接服务器
                mSocketClient = new Socket(sIP, port);  //portnum
                flagClientConnectYes=true;
                //取得输入、输出流
                mBufferedReaderClient = new BufferedReader(new InputStreamReader(mSocketClient.getInputStream()));
 
                mPrintWriterClient = new PrintWriter(mSocketClient.getOutputStream(), true);
 
                StringTextViewClientInfo = "\nClent: 已经连接server!\n";//消息换行
                Message msg = new Message();
                msg.what = 0x111;
                mHandler.sendMessage(msg);
                //break;
            }
            catch (Exception e)
            {
                StringTextViewClientInfo = "连接IP异常:" + e.toString() + e.getMessage() + "\n";//消息换行
                Message msg = new Message();
                msg.what = 0x111;
                mHandler.sendMessage(msg);
                return;
            }
//接受消息
            char[] buffer = new char[256];
            int count = 0;
            while (true)
            {
                try
                {
                    //if ( (recvMessageClient = mBufferedReaderClient.readLine()) != null )
                    if((count = mBufferedReaderClient.read(buffer))>0)
                    {
//                      StringTextViewClientInfo ="Server :"+ getInfoBuff(buffer, count) + "\n";//消息换行
                        StringTextViewClientInfo =getInfoBuff(buffer, count) + "\n";//消息换行
                        Message msg = new Message();
                        msg.what = 0x111;
                        mHandler.sendMessage(msg);
                    }
                }
                catch (Exception e)
                {
                    StringTextViewClientInfo = "Clent: 接收异常:" + e.getMessage() + "\n";//消息换行
                    Message msg = new Message();
                    msg.what = 0x111;
                    mHandler.sendMessage(msg);
                }
            }
        }
    };
 
 
    public static String getLocalIpAddress()
    {
        try
        {
            for (Enumeration<NetworkInterface> en = NetworkInterface
                    .getNetworkInterfaces(); en.hasMoreElements();)
            {
                NetworkInterface intf = en.nextElement();
                for (Enumeration<InetAddress> enumIpAddr = intf
                        .getInetAddresses(); enumIpAddr.hasMoreElements();)
                {
                    InetAddress inetAddress = enumIpAddr.nextElement();
                    if (!inetAddress.isLoopbackAddress())
                    {
                        //获取ip
                        //  Socket_ServeIp= inetAddress.getHostAddress().toString();
                        return inetAddress.getHostAddress().toString();
                    }
                }
            }
        } catch (SocketException ex)
        {
            Log.e("WifiPreference IpAddress", ex.toString());
        }
        return null;
    }
 
    private String getInfoBuff(char[] buff, int count)
    {
        char[] temp = new char[count];
        for(int i=0; i<count; i++)
        {
            temp[i] = buff[i];
        }
        return new String(temp);
    }
 
    public void onDestroy()
    {
        super.onDestroy();
        if (flagClientConnectYes)
        {
            flagClientConnectYes = false;
            try {
                if(mSocketClient!=null)
                {
                    mSocketClient.close();
                    mSocketClient = null;
 
                    mPrintWriterClient.close();
                    mPrintWriterClient = null;
                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            mThreadClient.interrupt();
        }
    }
}

留下评论