Sample Code Analysis

Start Gallery on Peer

The Start gallery on peer consists of the following files:

 

Table 1. Start Gallery on Peer Files

Files

Description

src/com/example/MainActivity.java

Main activity file

res/layout/sample_main.xml

Layout for the main activity

In this section, In this section, only java source files are explained. A detailed description of the layout files can be found on the Android Developer site.

 

Getting Ready

Importing the QPair SDK package

All classes using LG QPair APIs must import the LG QPair package as follows:

 

import com.lge.qpair.api.r1.*;

 

Creating the main activity

The main activity of the sample application is created.

 

public class MainActivity extends Activity {

}

 

Getting a button

In the main activity, a button is retrieved. This button will be used to send a command to the peer device.

 

protected void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   setContentView(R.layout.sample_main);

   // get the button for sending a message to the peer.
   Button button = (Button)findViewById(R.id.openggall);
}

 

Binding the QPair Service

The sample application implements an clickListener for the button. In the code below, bindService binds the main activity to the QPair service when button is clicked.

 

 
private OnClickListener clickListener = new OnClickListener() {

   public void onClick(View v) {

      final Intent intent = new Intent(QPairConstants.ACTION_SERVICE);

      // Bind to the QPair service
      boolean bindResult = 
          bindService(intent.setPackage(QPairConstants.PACKAGE_NAME), new MyServiceConnection(), 0);

      if (!bindResult) {
         Toast.makeText(MainActivity.this, "Binding to QPair service have failed.", Toast.LENGTH_SHORT).show();
      }
   }
};

 

Implementing Service Connection for Sending a Peer Intent

The sample application has a MyServiceConnection for receive information as the QPair service is connected or disconnected. The MyServiceConnection sends a peer intent to invoke a gallery application on the peer device. The sample application specifies the application by action and the data type.

 

 
public class MyServiceConnection implements ServiceConnection {
    
public void onServiceConnected(ComponentName name, IBinder service) {
        IPeerContext peerContext = IPeerContext.Stub.asInterface(service); ①

        try { 
                IPeerIntent peerIntent = peerContext.newPeerIntent();           ②
                peerIntent.setType("image/*");                ③
                peerIntent.setAction(Intent.ACTION_VIEW);   ④

                // call startActivityOnPeer() with an IPeerIntent using IPeerContext  
                peerContext.startActivityOnPeer(peerIntent, null, null); ⑤

        } catch (RemoteException e) {
                e.printStackTrace();
        }

        unbindService(this); ⑥
    }
}

 

① Gets an IPeerContext when the QPair service is connected.

② Creates a peer intent to send.

③ Sets the MIME type of data that the peer intent targets on the peer device.

④ Sets the action to open the gallery when the peer device receives the peer intent.

⑤ Sends the peer intent to start the gallery on the peer device.

⑥ Disconnects the activity from the QPair service.

Start Custom Activity on Peer

The Start custom activity on peer consists of the following files:

 

Table 2. Start Custom Activity on Peer Files

Files

Description

src/com/example/CustomActivity.java

Main activity class

res/layout/sample_main.xml

Layout for the main activity

 

In this section,the explanation of codes that have already explained in eariler sections is skipped.

Sending a peer intent to start an activity on peer

The MyServiceConnection sends a peer intent to peer to start an activity on the peer device. Unlike Start Gallery on Peer application, the sample application specifies the application on the peer device by a class name.

 

public class MyServiceConnection implements ServiceConnection {

    public void onServiceConnected(ComponentName name, IBinder service) {
        IPeerContext peerContext = IPeerContext.Stub.asInterface(service); 

        try {
            IPeerIntent peerIntent = IPeerContext.newPeerIntent();
            peerIntent.setClassName("com.example.customactivity",
                        "com.example.customactivity.CustomActivity"); ①

            // create an IPeerIntent for the callback. 
            IPeerIntent success_callback = peerContext.newPeerIntent();
            // set the action for the callback. 
            success_callback.setAction(ACTION_CALLBACK_SUCCESS);    ②
                
            // create an IPeerIntent for the callback. 
            IPeerIntent failure_callback = peerContext.newPeerIntent();
            // set the action for the callback. 
            failure_callback.setAction(ACTION_CALLBACK_FAILURE);    ③

            iPeerContext.startActivityOnPeer(peerIntent, 
                                   success_callback, failure_callback);  ④

        } catch (RemoteException e) {
                e.printStackTrace();
        }

        unbindService(this); 
    }
}

 

① Sets the name of the package and activity on the peer device to handle the peer intent. The Start Custom Activity on Peer application will be invoked on the peer device.

② Creates a success callback intent and sets the action name.

③ Creates a failure callback intent and sets the action name.

④ Sends the peer intent to start the custom activity on peer with callbacks.

 

QPair API Demo

QPair API Demo sample consists of the following files:

 

Table 3. QPair API Demo

Files

Description

src/com/example/qpairapidemo/SenderActivity.java

Main activity class file

src/com/example/qpairapidemo/ReceiverActivity.java

Activity class file for the peer device

src/com/example/qpairapidemo/ReceiverBroadcastReceiver.java

Broadcast receiver for the peer device

src/com/example/qpairapidemo/ReceiverService.java

Service class for the peer device

res/layout/sample_main.xml

Layout for the main activity

In this section,the explanation of codes that have already explained in eariler sections is skipped. The explanation of this sample application mainly focuses on configuring a peer intent with user inputs.

 

Sending an Intent to Peer

Codes here are implemented in the SenderActivity class.

Configuring a Peer Intent with User Inputs

The sample application provides options for a peer intent. The QPair APIs provide setters. The peer intent can be configured with setters for the specific actions you want.

private class MyServiceConnection implements ServiceConnection {
...
    public void onServiceConnected(ComponentName name, IBinder service) {
    ...
        else {
            if (has(R.id.sample_action)) {
                  i.setAction(str(R.id.sample_action));     ①
            }                                                           
            if (!"".equals(((Spinner)findViewById(R.id.sample_category)).getSelectedItem().toString())) {    
                  i.addCategory(((Spinner)findViewById(R.id.sample_category)).getSelectedItem().toString());   ②
            }
            if (has(R.id.sample_data) && has(R.id.sample_type)) {
                  i.setDataAndType(str(R.id.sample_data), str(R.id.sample_type));③
            } else if (has(R.id.sample_data)) {
                  i.setData(str(R.id.sample_data));
            } else if (has(R.id.sample_type)) {
                  i.setType(str(R.id.sample_type));
            }
            if (!"".equals(((Spinner)findViewById(R.id.sample_component)).getSelectedItem().toString())) {
                  i.setComponent(((Spinner)findViewById(R.id.sample_component))
                              .getSelectedItem().toString()); ④
            }
            if (has(R.id.sample_packageName)) {
                  i.setPackage(str(R.id.sample_packageName)); ⑤
            }
            ...
      }
...
}

① Loads a string from the text view and sets it as an action name. The default string is android.intent.action.MAIN”.

② Loads the selected category from the spinner and adds it as a category.

③ Sets the data with the MIME data type entered in the text view.

④ Specifies the component for handling the peer intent on the peer device.

⑤ Specifies the package for handling the peer intent on the peer device.

Attaching Extra Data

The sample application can add data to the peer intent. The attached data can be a specific type including char, boolean, float and etc, and also support array types are supported as well.

private class MyServiceConnection implements ServiceConnection {
    ...
    public void onServiceConnected(ComponentName name, IBinder service) {
        ...
        else {
           if (has(R.id.sample_boolean_array_extra)) {
               i.putBooleanArrayExtra("booleanArray",
                        Boolean_arrayOf(R.id.sample_boolean_array_extra));  ①
           }
           ...
           if (has(R.id.sample_byte_array_extra)) {
                i.putByteArrayExtra("byteArray",
                        Byte_arrayOf(R.id.sample_byte_array_extra));      ②
            }
            if (has(R.id.sample_byte_extra)) {
                i.putByteExtra("byte",
                        Byte.valueOf(str(R.id.sample_byte_extra)));
            }
            if (has(R.id.sample_char_array_extra)) {
               i.putCharArrayExtra("charArray",
                        Char_arrayOf(R.id.sample_char_array_extra));       ③
            }
            ...
        }
...
}

① Adds an array of Boolean type data to the peer intent.

② Adds an array of byte type data to the peer intent.

③ Adds an array of char type data to the peer intent.

Sending a Command to Peer

The sample application can send a broadcast intent to the peer device and also can start a service on the peer device.

private class MyServiceConnection implements ServiceConnection {
    ...
    public void onServiceConnected(ComponentName name, IBinder service) {
    ...
        else {
            else if (R.id.sample_send_broadcast == componentTypeId) {
                peerContext.sendBroadcastOnPeer(i, null, callback); ①
            }
            else if (R.id.sample_start_service == componentTypeId) {
                Log.i(T, "start_service: " + i.toString());
                peerContext.startServiceOnPeer(i, null, callback); ②
            }
        } 
        ...
    }
    ...
}

① Sends a broadcast intent to the peer device.

② Starts a service on the peer device.

Retrieving Information from peer intent

Codes here are implemented in ReceiverActivity class.

The sample application uses getters to retrieve information from a received peer intent.

private CharSequence stringFromIntent(Intent intent) {
    StringBuilder sb = new StringBuilder();
    sb.append("action    = ").append(intent.getAction()).append("\n");  ①
    sb.append("component = ").append(intent.getComponent()).append("\n");  ②
    ...

    return sb.toString();
}

① Gets the action of the received peer intent.

② Retrieves the component of the received peer intent.

Using Properties API

Codes here are implemented in SenderActivity class.

Getting local properties

The sample application sets properties that are automatically visible on both peer devices. The sample application registers a contentObserver to observe properties and gets a local property.

public void onCreate(Bundle savedInstanceState) {
     contentObserver = new MyContentObserver(new Handler());
     getContentResolver().registerContentObserver(
             Uri.parse(QPairConstants.PROPERTY_SCHEME_AUTHORITY + lastRequestUriPath),false, contentObserver);  ①
     ((TextView)findViewById(R.id.propertyValue)).setText(getQPairProperty(QPairConstants.PROPERTY_SCHEME_AUTHORITY + "/local/qpair/device_name")); ②
}

private CharSequence getQPairProperty(String uriString) {
        Uri uri = Uri.parse(uriString);
        Cursor cursor = getContentResolver().query(uri, null, null, null, null); ③
        if (cursor != null) {
            try {
                if (cursor.moveToFirst()) {
                    return cursor.getString(0);      ④
                }
            }finally {
                cursor.close();
            }
        }
        return "";
    }

① Registers a content observer to observe QPair properties.

② Gets local device name property.

③ Gets a content resolver of the sample application.

④ Parses a property from the content resolver.

Managing properties

The sample application can also update or delete properties.

private int updateQPairProperty(String uriString, String value) {
        Uri uri = Uri.parse(uriString);
        ContentValues cv = new ContentValues();
        cv.put("", value);
        return getContentResolver().update(uri, cv, null, null); ①
}

private int deleteQPairProperty(String uriString) {
        Uri uri = Uri.parse(uriString);
        return getContentResolver().delete(uri, null, null); ②
}

① Updates rows in a content URI.

② Deletes row in a content URI.

 

Navigation