I'm trying to create a very simple Service to feed an Activity and provide it with a set of frames.
I followed the Bound Service methodology and created a callback interface to feed the Activity.
Client side (Activity):
public class MainActivity extends AppCompatActivity implements FrameReadyCallBack {
private Intent videoServiceIntent;
private VideoService videoService;
private boolean bound = false;
private ImageView surfaceView_video = null;
private String videoPort = "5002";
private String videoServerAddr = "192.168.10.107";
private ServiceConnection serviceConnection = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
surfaceView_video = findViewById(R.id.surfaceView_video);
serviceConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName className, IBinder service) {
VideoService.ImagesCollectorBinder binder = (VideoService.ImagesCollectorBinder) service;
videoService = binder.getService();
bound = true;
videoService.registerCallBack(MainActivity.this); // register
}
#Override
public void onServiceDisconnected(ComponentName arg0) {
bound = false;
}
};
startVideoService();
}
#Override
public void frameReady(byte[] image_data) {
//TODO: create image and update surfaceView_video
}
public void startVideoService()
{
videoServiceIntent = new Intent(this, VideoService.class);
videoServiceIntent.putExtra(VideoService.LOCAL_PORT_KEY, videoPort);
videoServiceIntent.putExtra(VideoService.LOCAL_VIDEOSERVER_ADDR_KEY, videoServerAddr);
startService(videoServiceIntent);
}
#Override
protected void onStart() {
super.onStart();
bindService();
}
#Override
protected void onStop() {
super.onStop();
unbindService();
}
private void bindService() {
bindService(videoServiceIntent, serviceConnection, Context.BIND_AUTO_CREATE);
}
private void unbindService(){
if (bound) {
videoService.registerCallBack(null); // unregister
unbindService(serviceConnection);
bound = false;
}
}
}
Service side:
public class VideoService extends Service {
public static final String LOCAL_PORT_KEY = "video_port";
public static final String LOCAL_VIDEOSERVER_ADDR_KEY = "video_server_addr";
private static final int DEFAULT_VIDEO_PORT = 5002;
private static final int VIDEO_SERVER_RESPAWN = 2000;
private FrameReadyCallBack frameReadyCallBack = null;
private VideoReceiver videoReceiver = null;
private IBinder videoServiceBinder = new VideoServiceBinder();
#Nullable
#Override
public IBinder onBind(Intent intent) {
return videoServiceBinder ;
}
#Override
public boolean onUnbind(Intent intent) {
videoReceiver.kill();
return super.onUnbind(intent);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
final int localVideoPort = intent.getIntExtra(LOCAL_PORT_KEY, DEFAULT_VIDEO_PORT);
final String videoServerAddr = intent.getStringExtra(LOCAL_VIDEOSERVER_ADDR_KEY);
videoReceiver = new VideoReceiver(videoServerAddr, localVideoPort);
videoReceiver.start();
return Service.START_NOT_STICKY;
}
public void registerCallBack(FrameReadyCallBack frameReadyCallBack) {
this.frameReadyCallBack = frameReadyCallBack;
}
public class VideoServiceBinder extends Binder {
public VideoService getService() {
return VideoService.this;
}
}
private class VideoReceiver extends Thread {
private boolean keepRunning = true;
private int VIDEO_SERVER_PORT;
private String VIDEO_SERVER_ADDR;
private int bad_frames;
private int frames;
private int link_respawn;
private FrameDecodingStatus status;
public VideoReceiver(String addr, int listen_port) {
VIDEO_SERVER_PORT = listen_port;
VIDEO_SERVER_ADDR = addr;
}
public void run() {
InetAddress serverAddr;
link_respawn = 0;
try {
serverAddr = InetAddress.getByName(VIDEO_SERVER_ADDR);
} catch (UnknownHostException e) {
Log.e(getClass().getName(), e.getMessage());
e.printStackTrace();
return;
}
Socket socket = null;
DataInputStream stream;
do {
bad_frames = 0;
frames = 0;
status = FrameDecodingStatus.Idle;
try {
socket = new Socket(serverAddr, VIDEO_SERVER_PORT);
stream = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
final byte[] _data = new byte[PACKET_SIZE];
final byte[] _image_data = new byte[IMAGE_SIZE];
int _data_index = 0;
while (keepRunning) {
if (stream.read(_data, 0, _data.length) == 0)
continue;
for (byte _byte : _data) {
if (status == FrameDecodingStatus.Idle) {
//Wait SoM
} else if (status == FrameDecodingStatus.Data) {
//Collect data
} else {
frameReadyCallBack.frameReady(_image_data);
status = FrameDecodingStatus.Idle;
}
}
}
}
link_respawn++;
Thread.sleep(VIDEO_SERVER_RESPAWN);
Log.d(getClass().getName(), "Link respawn: " + link_respawn);
} catch (Throwable e) {
Log.e(getClass().getName(), e.getMessage());
e.printStackTrace();
}
} while (keepRunning);
if (socket != null) {
try {
socket.close();
} catch (Throwable e) {
Log.e(getClass().getName(), e.getMessage());
e.printStackTrace();
}
}
}
public void kill() {
keepRunning = false;
}
}
}
Callback interface:
public interface FrameReadyCallBack {
void frameReady(byte[] image_data);
}
As far as I can see frameReady() callback is never called and the whole mechanism fails.
Where is the error?
When the new message is received, message should be passed to the internet for my further business logic.
To receive the new messages I used onReceive of broadcastreceiver and to process the internet business logics in background I used AsyncTask.
I am getting the null pointer exception in onPostExecute method of AyncTask, I read many stackoverflow and other website solutions and created the interface and initialized it in the AsyncTask extended class constructor. But getting only nullpointer.
My Full code:
MainActivity:
public class SmsActivity extends Activity implements ParseURL.OnAsyncRequestComplete {
private static SmsActivity inst;
public static final String SMS_BUNDLE = "pdus";
public static SmsActivity instance() {
return inst;
}
#Override
public void onStart() {
super.onStart();
inst = this;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sms);
}
#Override
public void processResp(String output){
String outpu1 = output+" in main";
}
}
BroadCastReceiver:
public class SmsBroadcastReceiver extends BroadcastReceiver{
public static final String SMS_BUNDLE = "pdus";
public void onReceive(Context context, Intent intent) {
Bundle intentExtras = intent.getExtras();
if (intentExtras != null) {
Object[] sms = (Object[]) intentExtras.get(SMS_BUNDLE);
String smsMessageStr = "";
boolean rechargeResult = false;
for (int i = 0; i < sms.length; ++i) {
SmsMessage smsMessage = SmsMessage.createFromPdu((byte[]) sms[i]);
String smsBody = smsMessage.getMessageBody().toString();
String address = smsMessage.getOriginatingAddress();
smsMessageStr += "SMS From: " + address + "\n";
if (smsBody != null) {
String[] splitValues = smsBody.split(" ");
if (splitValues != null && splitValues.length > 0) {
String siteURL = "SITE_URL";
try {
ParseURL.OnAsyncRequestComplete procesInterf = null;
ParseURL urlParse = new ParseURL(procesInterf);
Toast.makeText(context, siteURL, Toast.LENGTH_LONG).show();
new ParseURL(procesInterf).execute(new String[]{siteURL});
} catch (Exception e) {
Toast.makeText(context, "123 "+e.getMessage(), Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(context, "split values is null", Toast.LENGTH_LONG).show();
}
else {
Toast.makeText(context, "smsbody is null", Toast.LENGTH_LONG).show();
}
}
}
}
}
}
ParseURL:
public class ParseURL extends AsyncTask<String, Void, String> {
ProgressDialog progressDialog;
OnAsyncRequestComplete caller;
//Context context;
public ParseURL(OnAsyncRequestComplete a) {
caller = a;
// context = a;
}
public interface OnAsyncRequestComplete {
public void processResp(String response);
}
#Override
protected void onPreExecute()
{
progressDialog.setMessage("WAIT...");
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.setCancelable(false);
progressDialog.show();
}
#Override
protected String doInBackground(String... strings) {
String responseStatus = "";
try {
if(strings!=null) {
if (null != strings[0]) {
Document doc = Jsoup.connect(strings[0]).timeout(0).get();
if (doc != null) {
String result = doc.select("body").text();
if (null != result) {
if (result.toLowerCase().contains("FAILED".toLowerCase())) {
responseStatus = result;
} else if (result.toLowerCase().contains("SUCCESS".toLowerCase())) {
responseStatus = "SUCCESS";
} else {
responseStatus = "FAILED";
}
} else {
responseStatus = "google";
}
} else {
responseStatus = "facebook";
}
} else {
responseStatus = "youtube";
}
}else{
responseStatus = "ebay";
}
} catch (Throwable t) {
t.printStackTrace();
}
return responseStatus;
}
#Override
protected void onPostExecute(String s) {
caller.processResp(s);
}
}
I tried many solutions which is shared in the stackoverflow and other sites. But I could not solve it. Please do not mark this as duplicate.
Thanks in advance.
Ohh maaan...
ParseURL.OnAsyncRequestComplete procesInterf = null;
ParseURL urlParse = new ParseURL(procesInterf);
public ParseURL(OnAsyncRequestComplete a) {
caller = a;
}
#Override
protected void onPostExecute(String s) {
caller.processResp(s);
}
Are You see mistake?
You pass null to the ParseUrl constructor, so on PosteExecute() tries to call a method of a null callback.
I suspect that you would like to do that
ParseURL.OnAsyncRequestComplete procesInterf = SmsActivity.this;
But it will work, if your SmsBroadcastReceiver class is a inner class of SmsActivity.
You never initialize caller. Basically you set it to null, then you pass it to your AsyncTask, then you try to use it.
You already use the singleton pattern in your Activity, so you were probably after
ParseURL.OnAsyncRequestComplete procesInterf = SmsActivity.instance();
I'm trying to call 4 methods to use as arguments in another. I'm getting a "Cannot make a static reference to a non-static method" error. My problem is that I understand why my methods aren't already static.
Origin class:
public class IotdHandler extends DefaultHandler {
private String url = "http://www.nasa.gov/rss/image_of_the_day.rss";
private boolean inUrl = false;
private boolean inTitle = false;
private boolean inDescription = false;
private boolean inItem = false;
private boolean inDate = false;
private Bitmap image = null;
private String title = null;
private StringBuffer description = new StringBuffer();
private String date = null;
public void processFeed() {
try {
SAXParserFactory factory =
SAXParserFactory.newInstance();
SAXParser parser = factory.newSAXParser();
XMLReader reader = parser.getXMLReader();
reader.setContentHandler(this);
InputStream inputStream = new URL(url).openStream();
reader.parse(new InputSource(inputStream));
} catch (Exception e)
{ }
}
private Bitmap getBitmap(String url) {
try {
HttpURLConnection connection =
(HttpURLConnection)new URL(url).openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap bitmap = BitmapFactory.decodeStream(input);
input.close();
return bitmap;
} catch (IOException ioe) { return null; }
}
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
if (localName.equals("url")) { inUrl = true; }
else { inUrl = false; }
if (localName.startsWith("item")) { inItem = true; }
else if (inItem) {
if (localName.equals("title")) { inTitle = true; }
else { inTitle = false; }
if (localName.equals("description")) { inDescription = true; }
else { inDescription = false; }
if (localName.equals("pubDate")) { inDate = true; }
else { inDate = false; }
}
}
public void characters(char ch[], int start, int length) {
String chars = new String(ch).substring(start, start + length);
if (inUrl && url == null) { image = getBitmap(chars); }
if (inTitle && title == null) { title = chars; }
if (inDescription) { description.append(chars); }
if (inDate && date == null) { date = chars; }
}
public Bitmap getImage() { return image; }
public String getTitle() { return title; }
public StringBuffer getDescription() { return description; }
public String getDate() { return date; }
}
calling method:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_daily_image);
IotdHandler handler = new IotdHandler();
handler.processFeed();
resetDisplay(IotdHandler.getTitle(), IotdHandler.getDate(),
IotdHandler.getImage(), IotdHandler.getDescription());
}
Use handler instead of IotdHandler for accessing non-static methods from IotdHandler class same as you are accessing processFeed() method from IotdHandler.:
resetDisplay(handler.getTitle(), handler.getDate(),
handler.getImage(), handler.getDescription());
You have to call.
resetDisplay(handler.getTitle(), handler.getDate(),
handler.getImage(), handler.getDescription());
I have a home class when i open task manager at home class it shows 15 MB of ram.
then on opening BooksDetails class it increases to 29 MB.
on Clicking back memory does not return 15MB
Here is a sample
public class BooksDetails extends Activity
{
private Button btnBack;
private TextView tvBookTitle, tvBookSentences, tvBookInSummary, tvSpecialSentences;
private JustifiedTextView tvBookTxt;
private Button btnFavorite, btnShare, btnRelated;
public book mBook;
private Share ds;
private Button btnShareFacebook, btnShareTwitter, btnShareGooglePlus,btnCancelShare;// bookShare
private int idCount;
private IDGENERATOR idGen;
private String uniqueTag;
// private ProgressBar mProgress;
private ProgressWheel mProgress;
// getBookText getBookTextTask;
public int homeBookId;
private static int count = 0;
public static int ifDidntFindAnId = -1;
public static boolean shouldTerminate = false;
public static int terminateCount = 0;
private int currentTerminateCount = 0;
private boolean isAppRunning = true;
private UiLifecycleHelper uiHelper;
private PendingAction pendingAction = PendingAction.NONE;
private enum PendingAction
{
NONE, POST_PHOTO, POST_STATUS_UPDATE
}
private Session.StatusCallback callback = new Session.StatusCallback()
{
#Override
public void call(Session session, SessionState state,
Exception exception)
{
onSessionStateChange(session, state, exception);
}
};
private String user_id = null;
private int isFavourite = -1;
BooksDetailsHelp booksDetailsHelp;
private FontMan fMan;
public FontMan getFontMan()
{
if (fMan == null)
{
fMan = FontMan.getInstance(this);
}
return fMan;
}
#Override
protected void onCreate(Bundle savedInstanceState)
{
// processing
}
And
#Override
public void onDestroy()
{
super.onDestroy();
if (uiHelper != null)
uiHelper.onDestroy();
destroy();
}
private void destroy()
{
try
{
tvBookTxt.destroy();
Globals.destroy(findViewById(R.id.rootView));
}
catch (Exception e)
{
}
btnBack = null;
tvBookTitle = tvBookSentences = tvBookInSummary = tvSpecialSentences = null;
tvBookTxt = null;
btnFavorite.setOnClickListener(null);
btnShare.setOnClickListener(null);
btnRelated.setOnClickListener(null);
btnFavorite = btnShare = btnRelated = null;
mBook = null;
ds = null;
btnShareFacebook.setOnClickListener(null);
btnShareTwitter.setOnClickListener(null);
btnShareGooglePlus.setOnClickListener(null);
btnCancelShare.setOnClickListener(null);
btnShareFacebook = btnShareTwitter = btnShareGooglePlus = btnCancelShare = null;
idGen = null;
uniqueTag = null;
mProgress = null;
uiHelper = null;
pendingAction = null;
callback = null;
user_id = null;
booksDetailsHelp.destroy();
booksDetailsHelp = null;
fMan = null;
if (getUserSocialIdsTask != null)
{
getUserSocialIdsTask.cancel(true);
}
getUserSocialIdsTask = null;
finish();
System.gc();
}
public synchronized static void destroy(View homeView)
{
try
{
disableListeners(homeView);
}
catch (Exception e)
{
// TODO: handle exception
}
try
{
unbindDrawables(homeView);
}
catch (Exception e)
{
}
}
private static void disableListeners(View view)
{
try
{
view.setOnClickListener(null);
}
catch (Exception e)
{
// TODO: handle exception
}
if (view instanceof ViewGroup)
{
for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++)
{
disableListeners(((ViewGroup) view).getChildAt(i));
}
}
}
private static void unbindDrawables(View view)
{
if (view.getBackground() != null)
{
view.getBackground().setCallback(null);
}
if (view instanceof ViewGroup)
{
for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++)
{
unbindDrawables(((ViewGroup) view).getChildAt(i));
}
((ViewGroup) view).removeAllViews();
}
}
here is an image after clicking the back button
I am trying to use Android USB Host API to read my USB game controller data, once I get this to work, I will connect other device to test.
My game controller is connected to my Android phone using OTG cable. I am now able to get device, endpoints information, but I don't know how to read the raw data and display it.
Can someone please help me? Some example codes will be appreciated.
TextView countDisplay;
ArrayList<String> listItems = new ArrayList<String>();
ArrayAdapter<String> adapter;
String values = "";
UsbManager mManager;
UsbDevice device = null;
private byte[] bytes;
private static int TIMEOUT = 0;
private boolean forceClaim = true;
static PendingIntent mPermissionIntent;
UsbDeviceConnection connection = null;
UsbEndpoint InputEndpoint = null;
UsbEndpoint OutputEndpoint = null;
private Handler mHandler = new Handler();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mManager = (UsbManager) getSystemService(Context.USB_SERVICE);
mPermissionIntent = PendingIntent.getBroadcast(this, 0, new Intent(
"com.android.example.USB_PERMISSION"), 0);
IntentFilter filter = new IntentFilter();
filter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);
filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
registerReceiver(mUsbReceiver, filter);
HashMap<String, UsbDevice> deviceList = mManager.getDeviceList();
values = values + "deviceListSize:" + deviceList.size() + ",tostring:"
+ deviceList.toString();
Iterator<UsbDevice> deviceIterator = deviceList.values().iterator();
while (deviceIterator.hasNext()) {
device = deviceIterator.next();
values = values + ",device id:" + device.getDeviceId()
+ ",device name:" + device.getDeviceName();
values = values + ",Protocol:" + device.getDeviceProtocol()
+ ",ProductId:" + device.getProductId();
values = values + ",DeviceClass:" + device.getDeviceClass()
+ ",VendorId:" + device.getVendorId();
}
if (device != null) {
values = values + ",getInterfaceCount:"
+ device.getInterfaceCount();
UsbInterface intf = device.getInterface(0);
values = values + ",intf.getEndpointCount():"
+ intf.getEndpointCount();
UsbEndpoint endpoint1 = intf.getEndpoint(0);
UsbEndpoint endpoint2 = intf.getEndpoint(1);
mManager.requestPermission(device, mPermissionIntent);
if (mManager.hasPermission(device)) {
values = values + ",has permission over device!";
connection = mManager.openDevice(device);
if (connection == null) {
values = values + ",connection null";
} else {
values = values + ",getFileDescriptor:"
+ connection.getFileDescriptor();
if (endpoint1.getDirection() == UsbConstants.USB_DIR_IN) {
InputEndpoint = endpoint1;
} else {
OutputEndpoint = endpoint1;
}
if (endpoint2.getDirection() == UsbConstants.USB_DIR_IN) {
InputEndpoint = endpoint2;
} else {
OutputEndpoint = endpoint2;
}
}
if (InputEndpoint == null) {
countDisplay.setText(values + ",InputEndpoint is null");
}
if (OutputEndpoint == null) {
countDisplay.setText(values + ",OutputEndPoint is null");
}
connection.claimInterface(intf, forceClaim);
mHandler.postDelayed(runnable, 1);
} else {
values = values + ",Do not have permission over device!";
}
}
setContentView(R.layout.activity_main);
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = inflater.inflate(R.layout.activity_main, null);
LinearLayout ll = new LinearLayout(this);
ll.setOrientation(LinearLayout.VERTICAL);
int counter = 1;
countDisplay = new TextView(this);
ll.addView(countDisplay);
countDisplay.setText(values + ",counter here");
final Button button = new Button(this);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (device != null && mManager.hasPermission(device)) {
values = values + ",device id:" + device.getDeviceId()
+ ",device name:" + device.getDeviceName();
values = values + ",Protocol:" + device.getDeviceProtocol()
+ ",ProductId:" + device.getProductId();
values = values + ",DeviceClass:" + device.getDeviceClass()
+ ",VendorId:" + device.getVendorId();
countDisplay.setText(values + ",okok");
} else {
if (device != null)
mManager.requestPermission(device, mPermissionIntent);
}
}
});
ll.addView(button);
setContentView(ll);
}
And Runnable:
private Runnable runnable = new Runnable() {
public void run() {
if (connection != null) {
int count = connection.bulkTransfer(InputEndpoint, bytes,
bytes.length, TIMEOUT);
countDisplay.setText(values + ",bultTransferNo:" + count);
countDisplay.setText(values + "bulkValue:" + bytes);
} else {
countDisplay.setText(values + ",connection is null");
}
}
};
This program serves as an example of the following USB host features:
Matching devices based on interface class, subclass and protocol (see device_filter.xml)
Asynchronous IO on bulk endpoints
All code Copyright:
/*
* Copyright (C) 2011 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
AdbDevice
package com.android.adb;
import android.hardware.usb.UsbConstants;
import android.hardware.usb.UsbDeviceConnection;
import android.hardware.usb.UsbEndpoint;
import android.hardware.usb.UsbInterface;
import android.hardware.usb.UsbRequest;
import android.util.SparseArray;
import java.util.LinkedList;
/* This class represents a USB device that supports the adb protocol. */
public class AdbDevice {
private final AdbTestActivity mActivity;
private final UsbDeviceConnection mDeviceConnection;
private final UsbEndpoint mEndpointOut;
private final UsbEndpoint mEndpointIn;
private String mSerial;
// pool of requests for the OUT endpoint
private final LinkedList<UsbRequest> mOutRequestPool = new LinkedList<UsbRequest>();
// pool of requests for the IN endpoint
private final LinkedList<UsbRequest> mInRequestPool = new LinkedList<UsbRequest>();
// list of currently opened sockets
private final SparseArray<AdbSocket> mSockets = new SparseArray<AdbSocket>();
private int mNextSocketId = 1;
private final WaiterThread mWaiterThread = new WaiterThread();
public AdbDevice(AdbTestActivity activity, UsbDeviceConnection connection,
UsbInterface intf) {
mActivity = activity;
mDeviceConnection = connection;
mSerial = connection.getSerial();
UsbEndpoint epOut = null;
UsbEndpoint epIn = null;
// look for our bulk endpoints
for (int i = 0; i < intf.getEndpointCount(); i++) {
UsbEndpoint ep = intf.getEndpoint(i);
if (ep.getType() == UsbConstants.USB_ENDPOINT_XFER_BULK) {
if (ep.getDirection() == UsbConstants.USB_DIR_OUT) {
epOut = ep;
} else {
epIn = ep;
}
}
}
if (epOut == null || epIn == null) {
throw new IllegalArgumentException("not all endpoints found");
}
mEndpointOut = epOut;
mEndpointIn = epIn;
}
// return device serial number
public String getSerial() {
return mSerial;
}
// get an OUT request from our pool
public UsbRequest getOutRequest() {
synchronized(mOutRequestPool) {
if (mOutRequestPool.isEmpty()) {
UsbRequest request = new UsbRequest();
request.initialize(mDeviceConnection, mEndpointOut);
return request;
} else {
return mOutRequestPool.removeFirst();
}
}
}
// return an OUT request to the pool
public void releaseOutRequest(UsbRequest request) {
synchronized (mOutRequestPool) {
mOutRequestPool.add(request);
}
}
// get an IN request from the pool
public UsbRequest getInRequest() {
synchronized(mInRequestPool) {
if (mInRequestPool.isEmpty()) {
UsbRequest request = new UsbRequest();
request.initialize(mDeviceConnection, mEndpointIn);
return request;
} else {
return mInRequestPool.removeFirst();
}
}
}
public void start() {
mWaiterThread.start();
connect();
}
public AdbSocket openSocket(String destination) {
AdbSocket socket;
synchronized (mSockets) {
int id = mNextSocketId++;
socket = new AdbSocket(this, id);
mSockets.put(id, socket);
}
if (socket.open(destination)) {
return socket;
} else {
return null;
}
}
private AdbSocket getSocket(int id) {
synchronized (mSockets) {
return mSockets.get(id);
}
}
public void socketClosed(AdbSocket socket) {
synchronized (mSockets) {
mSockets.remove(socket.getId());
}
}
// send a connect command
private void connect() {
AdbMessage message = new AdbMessage();
message.set(AdbMessage.A_CNXN, AdbMessage.A_VERSION, AdbMessage.MAX_PAYLOAD, "host::\0");
message.write(this);
}
// handle connect response
private void handleConnect(AdbMessage message) {
if (message.getDataString().startsWith("device:")) {
log("connected");
mActivity.deviceOnline(this);
}
}
public void stop() {
synchronized (mWaiterThread) {
mWaiterThread.mStop = true;
}
}
// dispatch a message from the device
void dispatchMessage(AdbMessage message) {
int command = message.getCommand();
switch (command) {
case AdbMessage.A_SYNC:
log("got A_SYNC");
break;
case AdbMessage.A_CNXN:
handleConnect(message);
break;
case AdbMessage.A_OPEN:
case AdbMessage.A_OKAY:
case AdbMessage.A_CLSE:
case AdbMessage.A_WRTE:
AdbSocket socket = getSocket(message.getArg1());
if (socket == null) {
log("ERROR socket not found");
} else {
socket.handleMessage(message);
}
break;
}
}
void log(String s) {
mActivity.log(s);
}
private class WaiterThread extends Thread {
public boolean mStop;
public void run() {
// start out with a command read
AdbMessage currentCommand = new AdbMessage();
AdbMessage currentData = null;
// FIXME error checking
currentCommand.readCommand(getInRequest());
while (true) {
synchronized (this) {
if (mStop) {
return;
}
}
UsbRequest request = mDeviceConnection.requestWait();
if (request == null) {
break;
}
AdbMessage message = (AdbMessage)request.getClientData();
request.setClientData(null);
AdbMessage messageToDispatch = null;
if (message == currentCommand) {
int dataLength = message.getDataLength();
// read data if length > 0
if (dataLength > 0) {
message.readData(getInRequest(), dataLength);
currentData = message;
} else {
messageToDispatch = message;
}
currentCommand = null;
} else if (message == currentData) {
messageToDispatch = message;
currentData = null;
}
if (messageToDispatch != null) {
// queue another read first
currentCommand = new AdbMessage();
currentCommand.readCommand(getInRequest());
// then dispatch the current message
dispatchMessage(messageToDispatch);
}
// put request back into the appropriate pool
if (request.getEndpoint() == mEndpointOut) {
releaseOutRequest(request);
} else {
synchronized (mInRequestPool) {
mInRequestPool.add(request);
}
}
}
}
}
}
AdbMessage
package com.android.adb;
import android.hardware.usb.UsbRequest;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
/* This class encapsulates and adb command packet */
public class AdbMessage {
// command names
public static final int A_SYNC = 0x434e5953;
public static final int A_CNXN = 0x4e584e43;
public static final int A_OPEN = 0x4e45504f;
public static final int A_OKAY = 0x59414b4f;
public static final int A_CLSE = 0x45534c43;
public static final int A_WRTE = 0x45545257;
// ADB protocol version
public static final int A_VERSION = 0x01000000;
public static final int MAX_PAYLOAD = 4096;
private final ByteBuffer mMessageBuffer;
private final ByteBuffer mDataBuffer;
public AdbMessage() {
mMessageBuffer = ByteBuffer.allocate(24);
mDataBuffer = ByteBuffer.allocate(MAX_PAYLOAD);
mMessageBuffer.order(ByteOrder.LITTLE_ENDIAN);
mDataBuffer.order(ByteOrder.LITTLE_ENDIAN);
}
// sets the fields in the command header
public void set(int command, int arg0, int arg1, byte[] data) {
mMessageBuffer.putInt(0, command);
mMessageBuffer.putInt(4, arg0);
mMessageBuffer.putInt(8, arg1);
mMessageBuffer.putInt(12, (data == null ? 0 : data.length));
mMessageBuffer.putInt(16, (data == null ? 0 : checksum(data)));
mMessageBuffer.putInt(20, command ^ 0xFFFFFFFF);
if (data != null) {
mDataBuffer.put(data, 0, data.length);
}
}
public void set(int command, int arg0, int arg1) {
set(command, arg0, arg1, (byte[])null);
}
public void set(int command, int arg0, int arg1, String data) {
// add trailing zero
data += "\0";
set(command, arg0, arg1, data.getBytes());
}
// returns the command's message ID
public int getCommand() {
return mMessageBuffer.getInt(0);
}
// returns command's first argument
public int getArg0() {
return mMessageBuffer.getInt(4);
}
// returns command's second argument
public int getArg1() {
return mMessageBuffer.getInt(8);
}
// returns command's data buffer
public ByteBuffer getData() {
return mDataBuffer;
}
// returns command's data length
public int getDataLength() {
return mMessageBuffer.getInt(12);
}
// returns command's data as a string
public String getDataString() {
int length = getDataLength();
if (length == 0) return null;
// trim trailing zero
return new String(mDataBuffer.array(), 0, length - 1);
}
public boolean write(AdbDevice device) {
synchronized (device) {
UsbRequest request = device.getOutRequest();
request.setClientData(this);
if (request.queue(mMessageBuffer, 24)) {
int length = getDataLength();
if (length > 0) {
request = device.getOutRequest();
request.setClientData(this);
if (request.queue(mDataBuffer, length)) {
return true;
} else {
device.releaseOutRequest(request);
return false;
}
}
return true;
} else {
device.releaseOutRequest(request);
return false;
}
}
}
public boolean readCommand(UsbRequest request) {
request.setClientData(this);
return request.queue(mMessageBuffer, 24);
}
public boolean readData(UsbRequest request, int length) {
request.setClientData(this);
return request.queue(mDataBuffer, length);
}
private static String extractString(ByteBuffer buffer, int offset, int length) {
byte[] bytes = new byte[length];
for (int i = 0; i < length; i++) {
bytes[i] = buffer.get(offset++);
}
return new String(bytes);
}
#Override
public String toString() {
String commandName = extractString(mMessageBuffer, 0, 4);
int dataLength = getDataLength();
String result = "Adb Message: " + commandName + " arg0: " + getArg0() +
" arg1: " + getArg1() + " dataLength: " + dataLength;
if (dataLength > 0) {
result += (" data: \"" + getDataString() + "\"");
}
return result;
}
private static int checksum(byte[] data) {
int result = 0;
for (int i = 0; i < data.length; i++) {
int x = data[i];
// dang, no unsigned ints in java
if (x < 0) x += 256;
result += x;
}
return result;
}
}
AdbSocket
package com.android.adb;
/* This class represents an adb socket. adb supports multiple independent
* socket connections to a single device. Typically a socket is created
* for each adb command that is executed.
*/
public class AdbSocket {
private final AdbDevice mDevice;
private final int mId;
private int mPeerId;
public AdbSocket(AdbDevice device, int id) {
mDevice = device;
mId = id;
}
public int getId() {
return mId;
}
public boolean open(String destination) {
AdbMessage message = new AdbMessage();
message.set(AdbMessage.A_OPEN, mId, 0, destination);
if (! message.write(mDevice)) {
return false;
}
synchronized (this) {
try {
wait();
} catch (InterruptedException e) {
return false;
}
}
return true;
}
public void handleMessage(AdbMessage message) {
switch (message.getCommand()) {
case AdbMessage.A_OKAY:
mPeerId = message.getArg0();
synchronized (this) {
notify();
}
break;
case AdbMessage.A_WRTE:
mDevice.log(message.getDataString());
sendReady();
break;
}
}
private void sendReady() {
AdbMessage message = new AdbMessage();
message.set(AdbMessage.A_OKAY, mId, mPeerId);
message.write(mDevice);
}
}
For additional information on usb and connecting you might find the following article helpfull.
http://android.serverbox.ch/?p=549
The last paragraph explains some of the issue you might face. The example they provide may also show you how to go about reading the data and how you will have to format the messages.
It looks like you face two issue. One setting up your code to read message, which Puspendu's answer aludes to, and the second issue which is "how" to communicate, what messages you will need to send to establish a connection, handshake, and determine the good stuff, i.e. the data you want.
Puspendu has shown one example of reading and writing to a device. However i would imagine that depending on the device you connect, the handshake and message structure will change, hence you'll have to look those parts up (afraid i dont know of any other examples).