Android Wear控制PPT播放软件的开发

成型软件:http://dev.360.cn/mod/mobileapp/?qid=157816976&appid=202350521

这次开发是以http://www.oschina.net/news/53042的代码为蓝本进行开发的,特此感谢,。

主要内容为对手机端进行改造,加入手表端。电脑上的服务端不需修改,可以直接使用。

手机端由一个Activity和一个Service组成

手机端的一个Activity,目的是设置服务端IP地址和端口号。在设置完成后会ping一次电脑,结果会在LOG中显示,大家可以根据自己的需要进行改造。两个EditText为ip地址跟端口,按钮是确认和ping。

public class MobileActivity extends ActionBarActivity {

    public static String ipnum;
    public static int scoketnum;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_mobile);
        final EditText ip = (EditText) findViewById(R.id.ip);
        final EditText num = (EditText) findViewById(R.id.num);
        final Button OK = (Button) findViewById(R.id.OK);
        OK.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ipnum = ip.getText().toString();
                scoketnum = Integer.parseInt(num.getText().toString());
                try {
                    System.out.println(ping(ipnum));
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    public String ping(String m_strForNetAddress) throws IOException, InterruptedException {//ping测试
        Process p = Runtime.getRuntime().exec("ping -c 1 " + m_strForNetAddress);//m_strForNetAddress是输入的网址或者Ip地址
        int status = p.waitFor(); //status 只能获取是否成功,无法获取更多的信息
        if (status == 0) {
            return "success";
        } else {
            return "failed";
        }
    }

}

手机端的服务代码,作用仅仅是将手表的信息转发到电脑的服务端:

public class DataLayerListenerService extends WearableListenerService {

    private static final String TAG = "DataLayerSample";
    private static final String DATA_ITEM_RECEIVED_PATH = "/data-item-received";
    private DatagramSocket socket;
    GoogleApiClient mGoogleApiClient;

    @Override
    public void onDataChanged(DataEventBuffer dataEvents) {
        Log.d(TAG, "onDataChanged!!! ");
        try {
            socket = new DatagramSocket();
        } catch (SocketException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(new GoogleApiClient.ConnectionCallbacks() {
                    @Override
                    public void onConnected(Bundle connectionHint) {
                        Log.d(TAG, "onConnected: " + connectionHint);
                        // Now you can use the Data Layer API
                    }

                    @Override
                    public void onConnectionSuspended(int cause) {
                        Log.d(TAG, "onConnectionSuspended: " + cause);
                    }
                })
                .addOnConnectionFailedListener(new GoogleApiClient.OnConnectionFailedListener() {
                    @Override
                    public void onConnectionFailed(ConnectionResult result) {
                        Log.d(TAG, "onConnectionFailed: " + result);
                    }
                })
                        // Request access only to the Wearable API
                .addApi(Wearable.API)
                .build();
        GoogleApiClient googleApiClient = new GoogleApiClient.Builder(this)
                .addApi(Wearable.API)
                .build();

        ConnectionResult connectionResult =
                googleApiClient.blockingConnect(30, TimeUnit.SECONDS);

        if (!connectionResult.isSuccess()) {
            Log.e(TAG, "Failed to connect to GoogleApiClient.");
            return;
        }

        // Loop through the events and send a message
        // to the node that created the data item.
        for (DataEvent event : dataEvents) {
            Uri uri = event.getDataItem().getUri();
            if (event.getType() == DataEvent.TYPE_CHANGED) {
                DataMap dataMap = DataMapItem.fromDataItem(event.getDataItem()).getDataMap();
                if (event.getDataItem().getUri().getPath().equals("/ijz-con")) {
                    String content = dataMap.get("content");
                    if (!content.equals("")) {
                        sendMessage(content);
                        Log.d("TAG", content);
                    }
                }
                // Get the node id from the host value of the URI
                String nodeId = uri.getHost();
                // Set the data of the message to be the bytes of the URI
                byte[] payload = uri.toString().getBytes();

                // Send the RPC
                Wearable.MessageApi.sendMessage(googleApiClient, nodeId,
                        DATA_ITEM_RECEIVED_PATH, payload);
            }
        }
        if (!mGoogleApiClient.isConnected())
            mGoogleApiClient.connect();
    }

    private void sendMessage(String str) {
        try {
            // 首先创建一个DatagramSocket对象

            // 创建一个InetAddree
            InetAddress serverAddress = InetAddress.getByName(MobileActivity.ipnum);
            byte data[] = str.getBytes();
            // 创建一个DatagramPacket对象,并指定要讲这个数据包发送到网络当中的哪个地址,以及端口号
            DatagramPacket packet = new DatagramPacket(data, data.length,
                    serverAddress, MobileActivity.scoketnum);
            // 调用socket对象的send方法,发送数据
            socket.send(packet);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}
在手机的Manifest文件中,注册一个service:

 
            
                
            
        

手表端只有一个Activity,两个按钮,分别是上和下,对应的是电脑的向上键和向下键

public class WearActivity extends Activity implements DataApi.DataListener, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
    GoogleApiClient mGoogleAppiClient;
    private TextView mTextView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mGoogleAppiClient = new GoogleApiClient.Builder(this)
                .addApi(Wearable.API)
                .build();
        setContentView(R.layout.activity_wear);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);//屏幕常亮
        final WatchViewStub stub = (WatchViewStub) findViewById(R.id.watch_view_stub);
        stub.setOnLayoutInflatedListener(new WatchViewStub.OnLayoutInflatedListener() {
            @Override
            public void onLayoutInflated(WatchViewStub stub) {
                mTextView = (TextView) stub.findViewById(R.id.text);
                Button up = (Button) findViewById(R.id.up);
                Button down = (Button) findViewById(R.id.down);
                up.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        sendTextToPhone("keyboard:key,Up,click");//发送点击上键
                        sendTextToPhone("");
                    }
                });
                down.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        sendTextToPhone("keyboard:key,Down,click");//发送点击下键
                        sendTextToPhone("");
                    }
                });
            }
        });
        Wearable.DataApi.addListener(mGoogleAppiClient, this);
    }

    private void sendTextToPhone(String content) {
        PutDataMapRequest dataMap = PutDataMapRequest.create("/ijz-con");
        dataMap.getDataMap().putString("content", content);
        PutDataRequest request = dataMap.asPutDataRequest();
        PendingResult pendingResult = Wearable.DataApi
                .putDataItem(mGoogleAppiClient, request);
        pendingResult.setResultCallback(new ResultCallback() {

            @Override
            public void onResult(DataApi.DataItemResult result) {
                if (result.getStatus().isSuccess())
                    Log.e("tag", "success");

            }
        });
    }

    @Override
    protected void onStart() {
        Log.d("TAG", "开始");
        mGoogleAppiClient.connect();
        super.onStart();
    }

    @Override
    protected void onStop() {
        Log.d("TAG", "stop");
        if (null != mGoogleAppiClient && mGoogleAppiClient.isConnected()) {
            Wearable.DataApi.removeListener(mGoogleAppiClient, this);
            mGoogleAppiClient.disconnect();
        }
        super.onStop();
    }

    @Override
    public void onConnected(Bundle arg0) {
        Log.d("TAG", "connected");
    }

    @Override
    public void onConnectionSuspended(int arg0) {
        // TODO Auto-generated method stub
        Log.d("TAG", "ConnectionSuspended");

    }

    @Override
    public void onConnectionFailed(ConnectionResult arg0) {
        // TODO Auto-generated method stub
        Log.d("TAG", "ConnectionFailed");

    }

    @Override
    public void onDataChanged(DataEventBuffer dataEvents) {

    }
}

需要在手机端声明联网权限

    


两端都不要忘记在Manifest中注册gms,因为手表和手机的通信需要谷歌框架!

        



你可能感兴趣的:(Android Wear控制PPT播放软件的开发)