就是采用socket与serversocket直接的通信
机顶盒端代码:
package cn.tvsr.remotedemo; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.ServerSocket; import java.net.Socket; import android.app.Activity; import android.os.Bundle; import android.view.KeyEvent; import android.widget.Toast; public class RemoteDemoActivity extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); new Thread(new Runnable() { @Override public void run() { ServerSocket server; try { server = new ServerSocket(6868); System.out.println("Tvsr:Server Started!"); while(true){ System.out.println("Tvsr:Server Runing!"); Socket client = server.accept(); InputStream ins = client.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(ins)); final String tmp = br.readLine(); final int keyCode = Integer.parseInt(tmp); runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(getApplicationContext(), "Tvsr:Message received!-->keyCode:"+tmp, Toast.LENGTH_LONG).show(); System.out.println("Tvsr:Message received!-->keyCode:"+tmp); RemoteDemoActivity.this.onKeyDown(keyCode, new KeyEvent(KeyEvent.ACTION_DOWN, keyCode)); } }); } } catch (IOException e) { e.printStackTrace(); } } }).start(); } }
手机端代码:
package cn.tvsr.controldemo; import java.io.IOException; import java.io.OutputStream; import java.io.PrintStream; import java.net.Socket; import java.net.UnknownHostException; import android.app.Activity; import android.os.Bundle; import android.view.KeyEvent; import android.widget.Toast; public class ControlDemoActivity extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { Toast.makeText(getApplicationContext(), "keyCode:"+keyCode, Toast.LENGTH_LONG).show(); try { Socket socket = new Socket("192.168.5.101", 6868); OutputStream os = socket.getOutputStream(); PrintStream ps = new PrintStream(os); ps.println(keyCode); ps.flush(); ps.close(); os.close(); socket.close(); } catch (UnknownHostException e) { System.out.println("Tvsr:Server err!"); e.printStackTrace(); } catch (IOException e) { System.out.println("Tvsr:Server err!"); e.printStackTrace(); } return super.onKeyDown(keyCode, event); } }