Android mobile phone remote control set-top box (TV)

Company requirements: Refer to the Wukong remote control to control the set-top box on the mobile phone. Refer to the remote control for the mobile phone apk interface. The set-top box apk adds a switch in the settings. When it is turned on, it runs a background server. Process related actions.

How to realize the demand? First of all, application communication is nothing more than Socket and Http. Socket can also use TCP and UDP. If HTTP is used, many methods are derived, basic HTTP GET and POST requests, and then SOAP of WebService.

Of these methods, Socket is of course the most basic. So start with Socket.
The first is the server side: open the server, wait for the client to connect and receive the message KeyCode, and respond to the corresponding event;
then the client: simulate the UI interface of the remote control, set up the interface, add a click event for each control and assign the corresponding KeyCode, Connect to the server and pass the KeyCode information to the server.
After completion, you need to add network permissions in the resource configuration file:

<uses-permission android:name="android.permission.INTERNET"/>

Once all is completed, the test found only within the current application response button when leaving this application interface, without permission will be reported abnormal, then you need to add in Manifest.xml the
highest authority:

android:sharedUserId="android.uid.system"

At this time, you need to compile with the mk file under the SDK:
Android.mk

ifneq ($(BOARD_USE_DEFAULT_APPINSTALL),false)
LOCAL_PATH:= $(call my-dir)
include $(CLEAR_VARS)

LOCAL_MODULE_TAGS := optional

LOCAL_SRC_FILES := $(call all-subdir-java-files)

LOCAL_PACKAGE_NAME := RemoteTV
LOCAL_CERTIFICATE := platform

include $(BUILD_PACKAGE)
endif

The whole idea is like this, the following code:

ClientActivity, StrictMode (strict mode) is used here. If you don’t understand, you can understand it on Baidu. Here I only simulated the number keys and the up, down, left, and right keys. You can add them if necessary:

public class ClientActivity extends Activity implements OnClickListener {
    
    
    private EditText mServerIp;
    private EditText mServerPort;
    private EventSender mEventSender;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
                .detectDiskReads()
                .detectDiskWrites()
                .detectNetwork() 
                .penaltyLog() 
                .build());
        StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
                .detectLeakedSqlLiteObjects() 
                .penaltyLog() 
                .penaltyDeath()
                .build());
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_client);
        mServerIp = (EditText) findViewById(R.id.cli_adr_edi);
        mServerPort = (EditText) findViewById(R.id.cli_port_edi);
        findViewById(R.id.cli_connect_btn).setOnClickListener(this);
findViewById(R.id.num_1).setOnClickListener(this);
findViewById(R.id.num_2).setOnClickListener(this);
findViewById(R.id.num_3).setOnClickListener(this);
findViewById(R.id.num_4).setOnClickListener(this);
findViewById(R.id.num_5).setOnClickListener(this);
findViewById(R.id.num_6).setOnClickListener(this);
findViewById(R.id.num_7).setOnClickListener(this);
findViewById(R.id.num_8).setOnClickListener(this);
findViewById(R.id.num_9).setOnClickListener(this);
findViewById(R.id.btn_up).setOnClickListener(this);
findViewById(R.id.btn_left).setOnClickListener(this);
findViewById(R.id.btn_right).setOnClickListener(this);
findViewById(R.id.btn_down).setOnClickListener(this);
}
    @Override
    public void onClick(View v) {
        int code = -1;
        switch (v.getId()) {
            case R.id.cli_connect_btn:
                if(mEventSender != null) mEventSender.close();
                mEventSender = new EventSender(mServerIp.getText().toString(), Integer.valueOf(mServerPort.getText().toString()));
                mEventSender.connect();
                return;
            case R.id.num_1:
             code = KeyEvent.KEYCODE_1;
                break;
            case R.id.num_2:
                code = KeyEvent.KEYCODE_2;
                break;
            case R.id.num_3:
                code = KeyEvent.KEYCODE_3;
                break;
            case R.id.num_4:
                code = KeyEvent.KEYCODE_4;
                break;
            case R.id.num_5:
                code = KeyEvent.KEYCODE_5;
                break;
            case R.id.num_6:
                 code = KeyEvent.KEYCODE_6;
                break;
            case R.id.num_7:
                code = KeyEvent.KEYCODE_7;
                break;
            case R.id.num_8:
                code = KeyEvent.KEYCODE_8;
                break;
            case R.id.num_9:
                code = KeyEvent.KEYCODE_9;
                break;
            case R.id.btn_up:
                code=KeyEvent.KEYCODE_DPAD_UP;
                break;
              case R.id.btn_left:
                code=KeyEvent.KEYCODE_DPAD_LEFT;
                break;
            case R.id.btn_down:
                code=KeyEvent.KEYCODE_DPAD_DOWN;
                break;
            case R.id.btn_right:
                code=KeyEvent.KEYCODE_DPAD_RIGHT;
                break;
        }  
         if(mEventSender == null) return;
        mEventSender.println(createKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, code)));
    }
    private String createKeyEvent(KeyEvent event) {
        JSONObject json = new JSONObject();
        try {
            json.put("Event", event.getKeyCode());
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return json.toString();
    }
    public class EventSender {
    
    
        private static final String TAG = "EventSender";
        private Socket mSocket;
        private String mDstAddress;
        private int mDstPort;
        private PrintWriter mPrintWriter;
        private EventSender(String dstAddress, int dstPort){
            Log.d(TAG, "EventSender");
            mDstAddress = dstAddress;
            mDstPort = dstPort;
            mSocket = new Socket();
        }
         public void println(String str){
            mPrintWriter.println(str);
        }
        public boolean close(){
            Log.d(TAG, "close()");
            if(mSocket != null){
                try {
                    mSocket.close();
                    mSocket = null;
                    return true;
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return false;
        }
        public boolean connect(){
            Log.d(TAG, "connect()");
            try {
                if (mSocket != null && !mSocket.isConnected()) {
                    Log.d(TAG, "new InetSocketAddress()");
                    mSocket.connect(new InetSocketAddress(mDstAddress, mDstPort));
                    mPrintWriter = new PrintWriter(mSocket.getOutputStream(), true);
                    mSocket.setKeepAlive(true);
                }
                return true;
                 }catch (IOException e) {
                e.printStackTrace();
            }
            return false;
        }
    }
}

Service-Terminal:

public class ServerActivity extends Activity implements OnClickListener{
    
    
    private static final String TAG = "ServerActivity";
    private RemoteServer mRemoteServer;
    private EditText mServerPort;
    private TextView mServerRecEvent;
    private int keycode;
    private Instrumentation instrumentation;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
                .detectDiskReads()
                .detectDiskWrites()
                .detectNetwork() 
                .penaltyLog() 
                .build());
        StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
                .detectLeakedSqlLiteObjects() 
                .penaltyLog() 
               .penaltyDeath()
                .build());
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_server);
        findViewById(R.id.ser_port_btn).setOnClickListener(this);
        mServerPort = (EditText) findViewById(R.id.ser_port_edi);
        mServerRecEvent = (TextView) findViewById(R.id.ser_recev_event);
    }
    @Override
    public void onClick(View v) {
        openServer(Integer.valueOf(mServerPort.getText().toString()));
    }
    public void openServer(int dstPort){
        Log.d(TAG, "openServer() - dstPort:" + dstPort);
        mServerRecEvent.setText("");
        if (mRemoteServer == null) {
            mRemoteServer = new RemoteServer(dstPort);
            if(mRemoteServer.openServer()) {
                mServerRecEvent.setText("服务启动成功!!!!/r/n");
            }
             Log.d(TAG, "openServer() - mRemoteServer:" + mRemoteServer);
        }
    }
    private void onEvent(String line) {
        Log.d(TAG, "line: " + line);

        try {
            JSONObject object=new JSONObject(line);
            keycode = (int) object.get("Event");
            Log.d(TAG, "keycode: " + keycode);
            if (instrumentation==null){
                instrumentation=new Instrumentation();
            }
            //通过KeyCode响应相应操作
            instrumentation.sendKeyDownUpSync(keycode);
            Log.d(TAG, "event key : " + keycode);
        } catch (JSONException e) {
   e.printStackTrace();
        }
        Message msg = Message.obtain();
        msg.what = 0;
        msg.obj = line;
        mHandler.sendMessage(msg);
   }
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            String text = mServerRecEvent.getText().toString();
            mServerRecEvent.setText(text + String.valueOf(msg.obj));
        }
    };


    class RemoteServer implements Runnable{
        private static final String TAG = "RemoteServer";
        private int mPort;
        private ServerSocket mServerSocket;
        private boolean mIsClose = false;
     public boolean isClose(){
            return mIsClose;
        }
        public boolean close(){
            try {
                mServerSocket.close();
                mServerSocket = null;
                mIsClose = true;
            } catch (IOException e) {
                e.printStackTrace();
            }
            return mIsClose;
        }
        public RemoteServer(int port){
            Log.d(TAG, "RemoteServer()");
            mPort = port;
        }
        public boolean openServer(){
            try {
                mServerSocket = new ServerSocket(mPort);
                new Thread(this).start();
                return true;
            } catch (IOException e) {
                e.printStackTrace();
            }
            return false;
        }
        public void run() {
            try {
                while (!mIsClose) {
                    Socket socket = mServerSocket.accept();
                    new ServerThread(socket);
                }
            } catch (IOException e) {
            }
        }
        private class ServerThread extends Thread {
    
    
            private Socket client;
            private BufferedReader in;
            public ServerThread(Socket s) throws IOException {
                client = s;
                in = new BufferedReader(new InputStreamReader(client.getInputStream()));
                start();
            }
            public void run() {
                android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_URGENT_DISPLAY);
                try {
                    String line = in.readLine();
                    while (!mIsClose) {
                        if(line != null){
                            onEvent(line);
                        }
                        line = in.readLine();
                    }
                    Log.d(TAG, "--- See you, bye! ---");
                 client.close();
                }
                catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

MainActivity

public class MainActivity extends Activity implements View.OnClickListener {
    
    

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        findViewById(R.id.btn_client).setOnClickListener(this);
        findViewById(R.id.btn_server).setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_client:
             startActivity(new Intent(this, ClientActivity.class));
                break;
            case R.id.btn_server:
                startActivity(new Intent(this, ServerActivity.class));
                break;
        }
    }
}

The layout will not be put, if you need it, you can look at the implementation process, mainly Socket communication, the upper interface below, the interface is the test interface, it is ugly, let's take a look:
first install the compiled APP on the client and the box, Enter the server side on the box side, enter the port number: img-w10
enter the client side on the mobile side, enter the IP address and port number of the server side:
img-w150
note here, there is no judgment when the connection is successful, after clicking the connection service, if there is no response, the connection is successful.
Also: the box and the mobile phone must be in the same LAN! ! ! The port number entered by the client and the port number entered by the server must be consistent.

Code download address: http://download.csdn.net/download/json_jerry/9955125 I
originally wanted to provide it with 0 points, but I don’t know why the minimum is 1 point.

Guess you like

Origin blog.csdn.net/Json_Jerry/article/details/77675990
Recommended