Writing custom Android ViewAction to take screenshot - java

I'm trying to take a screenshot before I perform an action in Android using espresso.
protected T performAction(ViewAction viewAction) {
ViewAction screenShotAction = new ScreenShotAction();
viewInteraction.perform(screenShotAction);
viewInteraction.perform(viewAction);
return returnGeneric();
}
For example if in my test I perform a click() then I would take a screenshot of the device before I performed the click().
This is the code for taking the screenshot in the ScreenShotAction class
#Override
public void perform(UiController uiController, View view) {
View rootView = view.getRootView();
String state = Environment.getExternalStorageState();
if(Environment.MEDIA_MOUNTED.equals(state)) {
File picDir = new File(Environment.getExternalStorageDirectory() + "app_" + "test");
if (!picDir.exists()) {
picDir.mkdir();
}
rootView.setDrawingCacheEnabled(true);
rootView.buildDrawingCache(true);
Bitmap bitmap = rootView.getDrawingCache();
String fileName = "test.jpg";
File picFile = new File(picDir + "/" + fileName);
try {
picFile.createNewFile();
FileOutputStream picOut = new FileOutputStream(picFile);
bitmap = Bitmap.createBitmap(rootView.getWidth(), rootView.getHeight(), Bitmap.Config.ARGB_8888);
boolean saved = bitmap.compress(Bitmap.CompressFormat.JPEG, 100, picOut);
if (saved) {
// good
} else {
// error
throw new Exception("Image not saved");
}
picOut.flush();
picOut.close();
} catch (Exception e) {
e.printStackTrace();
}
rootView.destroyDrawingCache();
}
}
I do not see any image files in the phone's Pictures directory or any other directory. I believe the screenshot method is solid but am unsure if I am calling the method correctly.
Is viewInteraction.perform(screenShotAction) the corret way to call my custom view action?
Please help and thank you in advance.

You can do the following:
public class CaptureImage {
#SuppressWarnings("unused")
private static final String TAG = CaptureImage.class.getSimpleName();
private static final String NAME_SEPARATOR = "_";
private static final String EXTENSION = ".png";
private static final Object LOCK = new Object();
private static boolean outputNeedsClear = true;
private static final Pattern NAME_VALIDATION = Pattern.compile("[a-zA-Z0-9_-]+");
public static void takeScreenshot(View currentView, String className,
String methodName, #Nullable String prefix) {
methodName = methodName.replaceAll("[\\[\\](){}]", "");
if (!NAME_VALIDATION.matcher(methodName).matches()) {
throw new IllegalArgumentException(
"Name must match " + NAME_VALIDATION.pattern() +
" and " + methodName + " was received.");
}
Context context = InstrumentationRegistry.getTargetContext();
MyRunnable myRunnable = new MyRunnable(context, currentView, className, methodName, prefix);
Activity activity =
((Application)context.getApplicationContext()).getCurrentActivity();
activity.runOnUiThread(myRunnable);
}
private static class MyRunnable implements Runnable {
private View mView;
private Context mContext;
private String mClassName;
private String mMethodName;
private String mPrefix;
MyRunnable(Context context, View view, String className, String methodName, String prefix) {
mContext = context;
mView = view;
mClassName = className;
mMethodName = methodName;
mPrefix = prefix;
}
#TargetApi(VERSION_CODES.JELLY_BEAN_MR2)
public void run() {
UiAutomation uiAutomation = InstrumentationRegistry.getInstrumentation().getUiAutomation();
if (uiAutomation == null) {
return;
}
OutputStream out = null;
Bitmap bitmap = null;
try {
String timestamp = new SimpleDateFormat("MM_dd_HH_mm_ss", Locale.ENGLISH)
.format(new Date());
File screenshotDirectory = getScreenshotFolder();
int statusBarHeight = getStatusBarHeightOnDevice();
bitmap = uiAutomation.takeScreenshot();
Bitmap screenshot = Bitmap.createBitmap(bitmap, 0, statusBarHeight,
mView.getWidth(), mView.getHeight() - statusBarHeight);
String screenshotName = mMethodName + NAME_SEPARATOR +
(mPrefix != null ? (mPrefix + NAME_SEPARATOR) : "") +
timestamp + EXTENSION;
Log.d("YOUR_TAG", "Screenshot name: " + screenshotName);
File imageFile = new File(screenshotDirectory, screenshotName);
out = new FileOutputStream(imageFile);
screenshot.compress(Bitmap.CompressFormat.PNG, 90, out);
out.flush();
} catch (Throwable t) {
Log.e("YOUR_LOG", "Unable to capture screenshot.", t);
} finally {
try {
if (out != null) {
out.close();
}
} catch (Exception ignored) {
}
if (bitmap != null) {
bitmap.recycle();
}
}
}
private int getStatusBarHeightOnDevice() {
int _StatusBarHeight = 0;
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
mView.setDrawingCacheEnabled(true);
Bitmap screenShot = Bitmap.createBitmap(mView.getDrawingCache());
mView.setDrawingCacheEnabled(false);
if (screenShot != null) {
int StatusColor = screenShot.getPixel(0, 0);
for (int y = 1; y < (screenShot.getHeight() / 4); y++) {
if (screenShot.getPixel(0, y) != StatusColor) {
_StatusBarHeight = y - 1;
break;
}
}
}
if (_StatusBarHeight == 0) {
_StatusBarHeight = 50; // Set a default in case we don't find a difference
}
Log.d("YOUR_TAG", "Status Bar was measure at "
+ _StatusBarHeight + " pixels");
return _StatusBarHeight;
}
private File getScreenshotFolder() throws IllegalAccessException {
File screenshotsDir;
if (Build.VERSION.SDK_INT >= 21) {
// Use external storage.
screenshotsDir = new File(getExternalStorageDirectory(),
"screenshots");
} else {
// Use internal storage.
screenshotsDir = new File(mContext.getApplicationContext().getFilesDir(),
"screenshots");
}
synchronized (LOCK) {
if (outputNeedsClear) {
deletePath(screenshotsDir);
outputNeedsClear = false;
}
}
File dirClass = new File(screenshotsDir, mClassName);
File dirMethod = new File(dirClass, mMethodName);
createDir(dirMethod);
return dirMethod;
}
private void createDir(File dir) throws IllegalAccessException {
File parent = dir.getParentFile();
if (!parent.exists()) {
createDir(parent);
}
if (!dir.exists() && !dir.mkdirs()) {
throw new IllegalAccessException(
"Unable to create output dir: " + dir.getAbsolutePath());
}
}
private void deletePath(File path) {
if (path.isDirectory() && path.exists()) {
File[] children = path.listFiles();
if (children != null) {
for (File child : children) {
Log.d("YOUR_TAG", "Deleting " + child.getPath());
deletePath(child);
}
}
}
if (!path.delete()) {
// log message here
}
}
}
Then you can call it from a ViewAction or from the test case class directly:
View Action Class:
class ScreenshotViewAction implements ViewAction {
private final String mClassName;
private final String mMethodName;
private final int mViewId;
private final String mPrefix;
protected ScreenshotViewAction(final int viewId, final String className,
final String methodName, #Nullable final String prefix) {
mViewId = viewId;
mClassName = className;
mMethodName = methodName;
mPrefix = prefix;
}
#Override
public Matcher<View> getConstraints() {
return ViewMatchers.isDisplayed();
}
#Override
public String getDescription() {
return "Taking a screenshot.";
}
#Override
public void perform(final UiController aUiController, final View aView) {
aUiController.loopMainThreadUntilIdle();
final long startTime = System.currentTimeMillis();
final long endTime = startTime + 2000;
final Matcher<View> viewMatcher = ViewMatchers.withId(mViewId);
do {
for (View child : TreeIterables.breadthFirstViewTraversal(aView)) {
// found view with required ID
if (viewMatcher.matches(child)) {
CaptureImage.takeScreenshot(aView.getRootView(), mClassName,
mMethodName, mPrefix);
return;
}
}
aUiController.loopMainThreadForAtLeast(50);
}
while (System.currentTimeMillis() < endTime);
}
}
Now from your test case class, create the following static methods:
public static void takeScreenshot(int prefix) {
View currentView = ((ViewGroup)mActivity
.getWindow().getDecorView().findViewById(android.R.id.content)).getChildAt(0);
String fullClassName = Thread.currentThread().getStackTrace()[3].getClassName();
String testClassName = fullClassName.substring(fullClassName.lastIndexOf(".") + 1);
String testMethodName = Thread.currentThread().getStackTrace()[3].getMethodName();
CaptureImage.takeScreenshot(currentView, testClassName, testMethodName,
String.valueOf(prefix));
}
public static ViewAction takeScreenshot(#Nullable String prefix) {
String fullClassName = Thread.currentThread().getStackTrace()[3].getClassName();
String className = fullClassName.substring(fullClassName.lastIndexOf(".") + 1);
String methodName = Thread.currentThread().getStackTrace()[3].getMethodName();
return new ScreenshotViewAction(getDecorView().getId(), className, methodName, prefix);
}
Or you can invoke it from the perform view action:
takeScreenshot(0);
onView(withContentDescription(sContext
.getString(R.string.abc_action_bar_up_description)))
.perform(
ScreenshotViewAction.takeScreenshot(String.valueOf(1)),
click()
);

Related

I want to create generic AsyncTask, Which can be used for all activities to save Image

I have created a ImageLoading class which downloads and saves data to local storage. I am also calling it from multiple activities. After saving I need to update collection of class from which the instance of asyncTask is created. I don't want to use if statements in task to handle this and I don't want to inherit this task to other activities. Please Suggest me how to do this. I am sharing my code here.
public class LoadImageTask extends AsyncTask<Void, Void, Bitmap> {
private String url;
private ImageView imageView;
private long ID;
private Context context;
private SQLiteHandler sqLiteHandler;
private String imageType;
private int position;
public LoadImageTask(String url, ImageView imageView, long ID, Context context, String imageType, int position) {
this.url = url;
this.imageView = imageView;
this.ID = ID;
this.context = context;
this.imageType = imageType;
this.position = position;
sqLiteHandler = new SQLiteHandler(context);
}
String getRandomString(int length)
{
String data = "";
Random rand = new Random();
for (int i = 1 ; i <= length ; i++) {
int n = rand.nextInt(26) + 97;
data += String.valueOf((char)n);
}
return data;
}
private File getOutputMediaFile(){
File mediaStorageDir = new File(Environment.getExternalStorageDirectory()
+ "/Android/data/"
+ context.getPackageName()
+ "/Files");
if (! mediaStorageDir.exists()){
if (! mediaStorageDir.mkdirs()){
return null;
}
}
String timeStamp = new SimpleDateFormat("ddMMyyyy_HHmmssSSS").format(new Date());
timeStamp = String.format("%s_%s", timeStamp, getRandomString(10));
File mediaFile;
String mImageName="Image_"+ timeStamp +".jpg";
mediaFile = new File(mediaStorageDir.getPath() + File.separator + mImageName);
return mediaFile;
}
private void storeImage(Bitmap image) {
File pictureFile = getOutputMediaFile();
if (pictureFile == null) {
Log.d("Error:","Error creating media file, check storage permissions: ");
return;
}
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
image.compress(Bitmap.CompressFormat.PNG, 90, fos);
fos.close();
ImageDownload imageDownload = new ImageDownload(ID,pictureFile.getAbsolutePath());
if(imageType.equals(Constants.ImageType.PROFILE)) {
sqLiteHandler.UpdateUserImagePath(imageDownload,Constants.ImageType.PROFILE);
}
else if(imageType.equals(Constants.ImageType.BANNER)) {
sqLiteHandler.UpdateUserImagePath(imageDownload,Constants.ImageType.BANNER);
}
else if(imageType.equals(Constants.ImageType.SUBJECT)) {
if(sqLiteHandler.UpdateUserImagePath(imageDownload,Constants.ImageType.SUBJECT)){
((MainActivity) context).subjectsItems.get(position).Image = imageDownload.ImagePath;
//((MainActivity) context).subjectsItems.get(position).Image = imageDownload.ImagePath;
//((MessageList) context).messageDataItems.get(position).SubjectImage = imageDownload.ImagePath;
}
}
} catch (FileNotFoundException e) {
Log.d("Error:", "File not found: " + e.getMessage());
} catch (IOException e) {
Log.d("Error:", "Error accessing file: " + e.getMessage());
}
}
#Override
protected Bitmap doInBackground(Void... params) {
try {
URL urlConnection = new URL(url);
HttpURLConnection connection = (HttpURLConnection) urlConnection
.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
return myBitmap;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Bitmap result) {
Drawable d = new BitmapDrawable(imageView.getResources(), result);
imageView.setBackground(d);
storeImage(result);
//imageView.setImageBitmap(result);
}
}
Simply just do it like this :
((AppCompatActivity) context).subjectsItems.get(position).Image = imageDownload.ImagePath;

unable to decode stream java.io.FileNotFoundException /storage/emulated/0

hello i'm trying to save pictures taken from url on my application, but when i try to access the memory to place the data, an error comes out
unable to decode stream java.io.FileNotFoundException /storage/emulated/0 open failed:ENOENT(No such file or directory)
this is my DownloadManager Class
public static ArrayList<String> urls = new ArrayList<String>();
public static OnDownloadCompleteListener downloadCompleteListener;
public static void copyFile(String sourceFile, String destinationFile) {
FileInputStream inputStream = null;
FileOutputStream outputStream = null;
try {
inputStream = new FileInputStream(sourceFile);
outputStream = new FileOutputStream(destinationFile);
byte[] buffer = new byte[G.DOWNLOAD_BUFFER_SIZE];
int len;
while ((len = inputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, len);
}
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
} finally {
if (inputStream != null) {
try {
inputStream.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
if (outputStream != null) {
try {
outputStream.flush();
outputStream.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
}
public static void initialize() {
downloadCompleteListener = new OnDownloadCompleteListener() {
#Override
public void onDownloadComplete(String url, String localPath) {
Log.i("LOG", "Image Download Complete, Original URL: " + url + ", Save Path: " + localPath);
String newPath = localPath.replace("/temp/", "/final/");
copyFile(localPath, newPath);
String filename = HelperString.getFileName(localPath);
new File(localPath).delete();
Set<ImageView> imageViews = AdapterSerials.imageMap.keySet();
for (ImageView imageView: imageViews) {
if (AdapterSerials.imageMap.get(imageView).equals(filename)) {
if (imageView != null) {
BitmapFactory.Options options = new BitmapFactory.Options();
//options.inSampleSize = 8;
Bitmap bitmap = BitmapFactory.decodeFile(newPath, options);
imageView.setImageBitmap(bitmap);
}
}
}
}
};
}
public static void addToDownloadList(String url, ImageView imgLogo) {
String filename = HelperString.getFileName(url);
AdapterSerials.imageMap.put(imgLogo, filename);
if (urls.contains(url)) {
return;
}
if (new File(G.DIR_FINAL + "/" + filename).exists()) {
return;
}
urls.add(url);
DownloadRequest downloadRequest = new DownloadRequest()
.downloadPath("http://87.236.215.180/mazi/" + url)
.filepath(G.DIR_TEMP + "/" + filename)
.listener(downloadCompleteListener)
.download();
}
this is my DownloadRequest Class :
public class DownloadRequest {
private int downloadedSize;
private int totalSize;
private int percent;
public int getDownloadedSize() {
return downloadedSize;
}
public int getTotalSize() {
return totalSize;
}
public int getPercent() {
return percent;
}
public DownloadRequest download() {
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
try {
URL url = new URL(downloadPath);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setDoOutput(true);
connection.connect();
totalSize = connection.getContentLength();
File file = new File(filepath);
if (file.exists()) {
file.delete();
}
FileOutputStream outputStream = new FileOutputStream(filepath);
InputStream inputStream = connection.getInputStream();
byte[] buffer = new byte[G.DOWNLOAD_BUFFER_SIZE];
int len = 0;
while ((len = inputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, len);
downloadedSize += len;
percent = (int) (100.0f * (float) downloadedSize / totalSize);
if (percent == 100 && listener != null) {
G.HANDLER.post(new Runnable() {
#Override
public void run() {
listener.onDownloadComplete(downloadPath, filepath);
}
});
}
if (simulate) {
try {
Thread.sleep(100);
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
}
outputStream.close();
}
catch (MalformedURLException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
}
});
thread.start();
return this;
}
private String downloadPath;
private String filepath;
private OnDownloadCompleteListener listener;
private boolean simulate;
public DownloadRequest downloadPath(String value) {
downloadPath = value;
return this;
}
public DownloadRequest filepath(String value) {
filepath = value;
return this;
}
public DownloadRequest listener(OnDownloadCompleteListener value) {
listener = value;
return this;
}
public DownloadRequest simulate(boolean value) {
simulate = value;
return this;
}
And this is my G class :
public class G extends Application {
public static Context context;
public static final String SDCARD = Environment.getExternalStorageDirectory().getAbsolutePath();
public static final String DIR_APP = SDCARD + "/serial";
public static final String DIR_CACHE = DIR_APP + "/cache";
public static LayoutInflater inflater;
public static final Handler HANDLER = new Handler();
public static Activity currentActivity;
public static StructSerials selectedSerials;
public static StructFavSerials selectedFavSerials;
public static ArrayList<StructComment> rates = new ArrayList<StructComment>();
public static final int DOWNLOAD_BUFFER_SIZE = 8 * 1024;
public static final String DIR_FINAL = DIR_APP + "/final";
public static final String DIR_TEMP = DIR_APP + "/temp";
public static String android_id;
public static SharedPreferences preferences;
#Override
public void onCreate() {
super.onCreate();
context = getApplicationContext();
preferences = PreferenceManager.getDefaultSharedPreferences(context);
initImageLoader(getApplicationContext());
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
android_id = Secure.getString(context.getContentResolver(),
Secure.ANDROID_ID);
new File(DIR_APP).mkdirs();
new File(DIR_CACHE).mkdirs();
new File(DIR_TEMP).mkdirs();
new File(DIR_FINAL).mkdirs();
DownloadManager.initialize();
}
remember add this permission into your AndroidManifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

Looper in AsyncTask

I'm learning about HTML and parsing data with XML DOM. For this, I've created an App that reads the Wheater from Yahoo's wheater API.
When executing the app, shows an error in the logcat that says: java.lang.RuntimeException: Can't create handler inside thread that has not caller Looper.prepare().
I don't know what this means, or if the code is right.
This is the link to the XML file of Yahoo's wheater API:
http://weather.yahooapis.com/forecastrss?w=766273&u=c
And this is my code:
public class WeatherActivity extends Activity {
private static final String WEATHER_URL = "http://weather.yahooapis.com/forecastjson?w=";
private static final String MADRID_CODE = "766273";
private static final String LOCATION_NAME = "location";
private static final String CITY_NAME = "city";
private static final String CONDITION_NAME = "condition";
private static final String TEMPERATURE_NAME = "temperature";
private static final String FORECAST_NAME = "forecast";
private static final String DAY_NAME = "day";
private static final String HIGH_TEMPERATURE_NAME = "high_temperature";
private static final String LOW_TEMPERATURE_NAME = "low_temperature";
private static final String TODAY = "Today";
private static final String TOMORROW = "Tomorrow";
private Button mButton;
private TextView mCity;
private TextView mToday;
private TextView mTomorrow;
private class WeatherInfo {
String city;
int temperatureNow;
int lowTemperature;
int highTemperature;
int lowTemperatureTomorrow;
int highTemperatureTomorrow;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mCity = (TextView) findViewById(R.id.city);
mToday = (TextView) findViewById(R.id.today);
mTomorrow = (TextView) findViewById(R.id.tomorrow);
mButton = (Button) findViewById(R.id.button);
mButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
launch();
}
});
}
private void launch(){
try {
new WeatherAsyncTask().execute(MADRID_CODE);
} catch (IllegalArgumentException e) {
e.printStackTrace();
Toast.makeText(WeatherActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
private class WeatherAsyncTask extends AsyncTask<String, Void, WeatherInfo>{
#Override
protected WeatherInfo doInBackground(String... params) {
String code = params[0];
if (TextUtils.isEmpty(code))
throw new IllegalArgumentException("Code cannot be empty");
URL url = null;
HttpURLConnection connection = null;
try {
url = new URL(WEATHER_URL + code);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
InputStream is = connection.getInputStream();
WeatherInfo info = readWeatherInfo(is);
return info;
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(WeatherActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
} finally {
if (connection != null)
connection.disconnect();
}
return null;
}
#Override
protected void onPostExecute(WeatherInfo result) {
super.onPostExecute(result);
showResult(result);
}
private WeatherInfo readWeatherInfo(InputStream is){
if (is == null)
return null;
WeatherInfo info = new WeatherInfo();
try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document dom = builder.parse(is);
Element root = dom.getDocumentElement();
NodeList items = root.getElementsByTagName("item");
for (int i=0; i<items.getLength(); i++) {
Node item = items.item(i);
NodeList datos = item.getChildNodes();
for (int j=0; j<datos.getLength(); j++) {
Node dato = datos.item(j);
String etiqueta = dato.getNodeName();
if (etiqueta.equals(LOCATION_NAME)) {
String texto = obtenerTexto(dato);
if (texto.equals(TEMPERATURE_NAME)) {
info.city = texto;
}
}
else if (etiqueta.equals(CONDITION_NAME)) {
String texto = obtenerTexto(dato);
if (texto.equals(CITY_NAME)) {
info.temperatureNow = Integer.parseInt(texto);
}
}
else if (etiqueta.equals(FORECAST_NAME)) {
String texto = obtenerTexto(dato);
String day = null;
int high = -111;
int low = -111;
if (texto.equals(DAY_NAME)){
day = texto;
} else if (texto.equals(HIGH_TEMPERATURE_NAME)){
high = Integer.parseInt(texto);
} else if (texto.equals(LOW_TEMPERATURE_NAME)){
low = Integer.parseInt(texto);
}
if (day.equals(TODAY)){
info.highTemperature = high;
info.lowTemperature = low;
} else if (day.equals(TOMORROW)){
info.highTemperatureTomorrow = high;
info.lowTemperatureTomorrow = low;
}
}
}
}
}
catch (Exception ex)
{
throw new RuntimeException(ex);
}
return info;
}
private String obtenerTexto(Node dato) {
StringBuilder texto = new StringBuilder();
NodeList fragmentos = dato.getChildNodes();
for (int k=0;k<fragmentos.getLength();k++) {
texto.append(fragmentos.item(k).getNodeValue());
}
return texto.toString();
}
}
private void showResult(WeatherInfo info){
mCity.setText("Temperature in " + info.city);
mToday.setText("Today: " + info.temperatureNow + " F (min: " + info.lowTemperature + " F / max: " + info.highTemperature + " F).");
mTomorrow.setText("Tomorrow: min: " + info.lowTemperatureTomorrow + " F / max: " + info.highTemperatureTomorrow + " F.");
}
}
You cannot show a Toast in the doInBackground of an ASyncTask
Try wrapping it in a runOnUIThread() like:
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(WeatherActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
You can use preimplemented method onProgressUpdate() of AsyncTask which allows you to post Toasts. To do this, you have to change your AsyncTask declaration into
private class WeatherAsyncTask extends AsyncTask<String, String, WeatherInfo>
and add method
#Override
protected void onProgressUpdate(String... values)
{
super.onProgressUpdate(values);
Toast.makeText(WeatherActivity.this, values[0], Toast.LENGTH_SHORT).show();
}
and inside your AsyncTask you can catch your exception and do this
catch (IOException e)
{
e.printStackTrace();
publishProgress(e.getMessage());
}
All this is available by default in AsyncTask without the need of creating new runnables.

How to create and show Qr Code in Android App [duplicate]

This question already has answers here:
How to generate a QR Code for an Android application? [closed]
(6 answers)
Closed 9 years ago.
can you help me please. I want to write small app for Android that has one button. When you push it it must show you qr code. Qr code must be generated form some string.
Tryed so far:
public void onClick(View v){
QRCodeEncoder qrCodeEncoder = new QRCodeEncoder("Hello",
null,
Contents.Type.TEXT,
BarcodeFormat.QR_CODE.toString(),
smallerDimension);
Bitmap bitmap = qrCodeEncoder.encodeAsBitmap();
}
first you will need to add zing2.1.jar file in your project then do the below code
QRCodeEncoder.java
public final class QRCodeEncoder {
private static final int WHITE = 0xFFFFFFFF;
private static final int BLACK = 0xFF000000;
private int dimension = Integer.MIN_VALUE;
private String contents = null;
private String displayContents = null;
private String title = null;
private BarcodeFormat format = null;
private boolean encoded = false;
public QRCodeEncoder(String data, Bundle bundle, String type, String format, int dimension) {
this.dimension = dimension;
encoded = encodeContents(data, bundle, type, format);
}
public String getContents() {
return contents;
}
public String getDisplayContents() {
return displayContents;
}
public String getTitle() {
return title;
}
private boolean encodeContents(String data, Bundle bundle, String type, String formatString) {
// Default to QR_CODE if no format given.
format = null;
if (formatString != null) {
try {
format = BarcodeFormat.valueOf(formatString);
} catch (IllegalArgumentException iae) {
// Ignore it then
}
}
if (format == null || format == BarcodeFormat.QR_CODE) {
this.format = BarcodeFormat.QR_CODE;
encodeQRCodeContents(data, bundle, type);
} else if (data != null && data.length() > 0) {
contents = data;
displayContents = data;
title = "Text";
}
return contents != null && contents.length() > 0;
}
private void encodeQRCodeContents(String data, Bundle bundle, String type) {
if (type.equals(Contents.Type.TEXT)) {
if (data != null && data.length() > 0) {
contents = data;
displayContents = data;
title = "Text";
}
} else if (type.equals(Contents.Type.EMAIL)) {
data = trim(data);
if (data != null) {
contents = "mailto:" + data;
displayContents = data;
title = "E-Mail";
}
} else if (type.equals(Contents.Type.PHONE)) {
data = trim(data);
if (data != null) {
contents = "tel:" + data;
displayContents = PhoneNumberUtils.formatNumber(data);
title = "Phone";
}
} else if (type.equals(Contents.Type.SMS)) {
data = trim(data);
if (data != null) {
contents = "sms:" + data;
displayContents = PhoneNumberUtils.formatNumber(data);
title = "SMS";
}
} else if (type.equals(Contents.Type.CONTACT)) {
if (bundle != null) {
StringBuilder newContents = new StringBuilder(100);
StringBuilder newDisplayContents = new StringBuilder(100);
newContents.append("MECARD:");
String name = trim(bundle.getString(ContactsContract.Intents.Insert.NAME));
if (name != null) {
newContents.append("N:").append(escapeMECARD(name)).append(';');
newDisplayContents.append(name);
}
String address = trim(bundle.getString(ContactsContract.Intents.Insert.POSTAL));
if (address != null) {
newContents.append("ADR:").append(escapeMECARD(address)).append(';');
newDisplayContents.append('\n').append(address);
}
Collection<String> uniquePhones = new HashSet<String>(Contents.PHONE_KEYS.length);
for (int x = 0; x < Contents.PHONE_KEYS.length; x++) {
String phone = trim(bundle.getString(Contents.PHONE_KEYS[x]));
if (phone != null) {
uniquePhones.add(phone);
}
}
for (String phone : uniquePhones) {
newContents.append("TEL:").append(escapeMECARD(phone)).append(';');
newDisplayContents.append('\n').append(PhoneNumberUtils.formatNumber(phone));
}
Collection<String> uniqueEmails = new HashSet<String>(Contents.EMAIL_KEYS.length);
for (int x = 0; x < Contents.EMAIL_KEYS.length; x++) {
String email = trim(bundle.getString(Contents.EMAIL_KEYS[x]));
if (email != null) {
uniqueEmails.add(email);
}
}
for (String email : uniqueEmails) {
newContents.append("EMAIL:").append(escapeMECARD(email)).append(';');
newDisplayContents.append('\n').append(email);
}
String url = trim(bundle.getString(Contents.URL_KEY));
if (url != null) {
// escapeMECARD(url) -> wrong escape e.g. http\://zxing.google.com
newContents.append("URL:").append(url).append(';');
newDisplayContents.append('\n').append(url);
}
String note = trim(bundle.getString(Contents.NOTE_KEY));
if (note != null) {
newContents.append("NOTE:").append(escapeMECARD(note)).append(';');
newDisplayContents.append('\n').append(note);
}
// Make sure we've encoded at least one field.
if (newDisplayContents.length() > 0) {
newContents.append(';');
contents = newContents.toString();
displayContents = newDisplayContents.toString();
title = "Contact";
} else {
contents = null;
displayContents = null;
}
}
} else if (type.equals(Contents.Type.LOCATION)) {
if (bundle != null) {
// These must use Bundle.getFloat(), not getDouble(), it's part of the API.
float latitude = bundle.getFloat("LAT", Float.MAX_VALUE);
float longitude = bundle.getFloat("LONG", Float.MAX_VALUE);
if (latitude != Float.MAX_VALUE && longitude != Float.MAX_VALUE) {
contents = "geo:" + latitude + ',' + longitude;
displayContents = latitude + "," + longitude;
title = "Location";
}
}
}
}
public Bitmap encodeAsBitmap() throws WriterException {
if (!encoded) return null;
Map<EncodeHintType, Object> hints = null;
String encoding = guessAppropriateEncoding(contents);
if (encoding != null) {
hints = new EnumMap<EncodeHintType, Object>(EncodeHintType.class);
hints.put(EncodeHintType.CHARACTER_SET, encoding);
}
MultiFormatWriter writer = new MultiFormatWriter();
BitMatrix result = writer.encode(contents, format, dimension, dimension, hints);
int width = result.getWidth();
int height = result.getHeight();
int[] pixels = new int[width * height];
// All are 0, or black, by default
for (int y = 0; y < height; y++) {
int offset = y * width;
for (int x = 0; x < width; x++) {
pixels[offset + x] = result.get(x, y) ? BLACK : WHITE;
}
}
Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
return bitmap;
}
private static String guessAppropriateEncoding(CharSequence contents) {
// Very crude at the moment
for (int i = 0; i < contents.length(); i++) {
if (contents.charAt(i) > 0xFF) { return "UTF-8"; }
}
return null;
}
private static String trim(String s) {
if (s == null) { return null; }
String result = s.trim();
return result.length() == 0 ? null : result;
}
private static String escapeMECARD(String input) {
if (input == null || (input.indexOf(':') < 0 && input.indexOf(';') < 0)) { return input; }
int length = input.length();
StringBuilder result = new StringBuilder(length);
for (int i = 0; i < length; i++) {
char c = input.charAt(i);
if (c == ':' || c == ';') {
result.append('\\');
}
result.append(c);
}
return result.toString();
}
}
Contents.java
import android.provider.ContactsContract;
public final class Contents {
private Contents() {
}
public static final class Type {
// Plain text. Use Intent.putExtra(DATA, string). This can be used for URLs too, but string
// must include "http://" or "https://".
public static final String TEXT = "TEXT_TYPE";
// An email type. Use Intent.putExtra(DATA, string) where string is the email address.
public static final String EMAIL = "EMAIL_TYPE";
// Use Intent.putExtra(DATA, string) where string is the phone number to call.
public static final String PHONE = "PHONE_TYPE";
// An SMS type. Use Intent.putExtra(DATA, string) where string is the number to SMS.
public static final String SMS = "SMS_TYPE";
// A contact. Send a request to encode it as follows:
// <p/>
// import android.provider.Contacts;
// <p/>
// Intent intent = new Intent(Intents.Encode.ACTION); intent.putExtra(Intents.Encode.TYPE,
// CONTACT); Bundle bundle = new Bundle(); bundle.putString(Contacts.Intents.Insert.NAME,
// "Jenny"); bundle.putString(Contacts.Intents.Insert.PHONE, "8675309");
// bundle.putString(Contacts.Intents.Insert.EMAIL, "jenny#the80s.com");
// bundle.putString(Contacts.Intents.Insert.POSTAL, "123 Fake St. San Francisco, CA 94102");
// intent.putExtra(Intents.Encode.DATA, bundle);
public static final String CONTACT = "CONTACT_TYPE";
// A geographic location. Use as follows:
// Bundle bundle = new Bundle();
// bundle.putFloat("LAT", latitude);
// bundle.putFloat("LONG", longitude);
// intent.putExtra(Intents.Encode.DATA, bundle);
public static final String LOCATION = "LOCATION_TYPE";
private Type() {
}
}
public static final String URL_KEY = "URL_KEY";
public static final String NOTE_KEY = "NOTE_KEY";
// When using Type.CONTACT, these arrays provide the keys for adding or retrieving multiple
// phone numbers and addresses.
public static final String[] PHONE_KEYS = {
ContactsContract.Intents.Insert.PHONE, ContactsContract.Intents.Insert.SECONDARY_PHONE,
ContactsContract.Intents.Insert.TERTIARY_PHONE
};
public static final String[] PHONE_TYPE_KEYS = {
ContactsContract.Intents.Insert.PHONE_TYPE,
ContactsContract.Intents.Insert.SECONDARY_PHONE_TYPE,
ContactsContract.Intents.Insert.TERTIARY_PHONE_TYPE
};
public static final String[] EMAIL_KEYS = {
ContactsContract.Intents.Insert.EMAIL, ContactsContract.Intents.Insert.SECONDARY_EMAIL,
ContactsContract.Intents.Insert.TERTIARY_EMAIL
};
public static final String[] EMAIL_TYPE_KEYS = {
ContactsContract.Intents.Insert.EMAIL_TYPE,
ContactsContract.Intents.Insert.SECONDARY_EMAIL_TYPE,
ContactsContract.Intents.Insert.TERTIARY_EMAIL_TYPE
};
}
Do the below code to add string and set it to ImageView
String qrData = "Name : "+name+"\n Company : "+comp;
int qrCodeDimention = 500;
QRCodeEncoder qrCodeEncoder = new QRCodeEncoder(qrData, null,
Contents.Type.TEXT, BarcodeFormat.QR_CODE.toString(), qrCodeDimention);
try {
Bitmap bitmap = qrCodeEncoder.encodeAsBitmap();
imageView.setImageBitmap(bitmap);
} catch (WriterException e) {
e.printStackTrace();
}
I dont know which library are you using.
I am calling my zxing library QRReaderActivity in my app like this.
startActivity(QRReaderActivity.class);
the method is
private void startActivity(Class<?> className) {
Intent intent = new Intent(this, className);
startActivityForResult(intent, 0);
}

Using Android USB Host API to read my USB game controller/Or other USB device data

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).

Categories