I'm developing an application in JavaFX who "scan" Mp3 files to get ID3tag.
Actually my program works, but the application is slow when there is a lot of songs (mp3).
I use a thread who scan every files from an list of mp3files (path).
I'm wondering if it's possible to use more threads to scan every files 4 by 4 rather than 1 by 1 ?
I'm low with multi-threading from java so I ask for your help. Any advice would be great.
Here is my function :
private ArrayList checkMp3files(String sDir)
{
this.currentData = 0;
this.filesCorrupted.clear();
ArrayList<DataSong> newLs = new ArrayList<>(); // ArrayList with Data from all Songs scanned
Task taskScan = new Task<ArrayList<DataSong>>() {
#Override
protected ArrayList<DataSong> call() throws InterruptedException, IOException, UnsupportedTagException
{
String absoluteLoc;
String location;
for(String mp3file : Mp3FileData)
{
DataSong ds = new DataSong();
updateMessage("Scanning " + ++currentData + " of " + nbrOfFiles + " Mp3files");
updateProgress(currentData, nbrOfFiles);
try {
mp3 = new Mp3File(mp3file);
} catch (InvalidDataException ex) {
filesCorrupted.add(mp3file);
}
long durationLong = mp3.getLengthInSeconds();
int durationInt = (int) durationLong;
ds.setLenghtOfMp3inSec(durationInt);
ds.setBitRateOfMp3(mp3.getBitrate());
ds.setSampleRate(mp3.getSampleRate());
ds.setVbrOrCbr(mp3.isVbr());
if(mp3 != null){
ds.setAbsoluteLocation(mp3.getFilename());
ds.setLocation(removeSDir(mp3.getFilename(), sDir));
if(mp3.hasId3v2Tag())
{
String artist = "";
String album = "";
String title = "";
String track = "";
String year = "";
String genDesc = "";
String composer = "";
String publisher = "";
String originalArtist = "";
String albumArtist = "";
String copyright = "";
String url = "";
ID3v2 id3v2Tag = mp3.getId3v2Tag();
try{
artist = id3v2Tag.getArtist();
album = id3v2Tag.getAlbum();
title = id3v2Tag.getTitle();
track = id3v2Tag.getTrack();
year = id3v2Tag.getYear();
genDesc = id3v2Tag.getGenreDescription();
composer = id3v2Tag.getComposer();
publisher = id3v2Tag.getPublisher();
originalArtist = id3v2Tag.getOriginalArtist();
albumArtist = id3v2Tag.getAlbumArtist();
copyright = id3v2Tag.getCopyright();
url = id3v2Tag.getUrl();
}
catch(Exception ex){
System.out.println(mp3file);
filesCorrupted.add(mp3file);
}
if(!(artist == null) && !(artist.isEmpty()))
{
ds.setArtist(artist);
}
if(!(album == null) && !(album.isEmpty()))
{
ds.setAlbum(album);
}
if(!(title == null) && !(title.isEmpty()))
{
ds.setTitle(title);
}
if(!(track == null) && !(track.isEmpty()))
{
ds.setTrackOnAlbum(track);
}
if(!(year == null) && !(year.isEmpty()))
{
ds.setYearReleased(year);
}
if(!(genDesc == null) && !(genDesc.isEmpty()))
{
ds.setGenre(genDesc);
}
if(!( composer == null) && !(composer.isEmpty()))
{
ds.setComposer(id3v2Tag.getComposer());
}
if(!(publisher == null) && !(publisher.isEmpty()))
{
ds.setPublisher(publisher);
}
if(!(originalArtist == null) && !(originalArtist.isEmpty()))
{
ds.setOriginArtist(originalArtist);
}
if(!(albumArtist == null) && !(albumArtist.isEmpty()))
{
ds.setAlbumArtString(albumArtist);
}
if(!(copyright == null) && !(copyright.isEmpty()))
{
ds.setCopyright(copyright);
}
if(!(url == null)&& !(url.isEmpty()))
{
ds.setUrl(url);
}
}
}
newLs.add(ds);
}
}
return newLs;
}
};
btnScan.disableProperty().bind(taskScan.runningProperty());
listAdvance.textProperty().bind(taskScan.messageProperty());
pi.progressProperty().bind(taskScan.progressProperty());
taskScan.stateProperty().addListener(new ChangeListener<Worker.State>(){
#Override
public void changed(ObservableValue<? extends Worker.State> observable, Worker.State oldValue, Worker.State newValue)
{
if(newValue == Worker.State.SUCCEEDED)
{
System.out.println("Error : " + taskScan.getException());
listAdvance.textProperty().unbind();
btnScan.disableProperty().unbind();
}
if(newValue == Worker.State.FAILED)
{
listAdvance.textProperty().unbind();
btnScan.disableProperty().unbind();
System.out.println("Error : " + taskScan.getException());
}
}
});
Thread toScanFiles = new Thread(taskScan);
toScanFiles.start();
return newLs;
}
I already thank you for your answers.
Related
i need to debug the below code to trace some unexpected results from the begining of the while loop. i put break point in the line of while loop but the debugger does not reach to it i want the debugger to run all code before that line then stop at the line to be debugged step by step how can i do that
public class MainActivity extends AppCompatActivity {
Button readExcelButton;
static String TAG = "ExelLog";
ArrayList<PhoneData> phoneData = new ArrayList<PhoneData>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void readFile(View view) {
if (!isExternalStorageAvailable() || isExternalStorageReadOnly()) {
Log.e(TAG, "Storage not available or read only");
return;
}
try {
// Creating Input Stream
File file = new File(this.getExternalFilesDir(null), "3.xls");
// FileInputStream myInput = new FileInputStream(file);
InputStream inStream;
Workbook wb = null;
inStream = new FileInputStream(file);
// Create a workbook using the File System
wb = new HSSFWorkbook(inStream);
// Get the first sheet from workbook
Sheet sheet1 = wb.getSheetAt(0);
int totalNumberOfRows = sheet1.getLastRowNum();
Log.d(TAG, "RowsNo: " + totalNumberOfRows);
int i = 6;
while (i <= totalNumberOfRows) {
if (sheet1.getRow(i).getCell(16).getCellTypeEnum() == CellType.NUMERIC) {
double duration = sheet1.getRow(i).getCell(16).getNumericCellValue();
if (duration > .91 && duration < 1) {
//sheet1.getRow(i).getCell(8).setCellType(CellType.NUMERIC);
double status = sheet1.getRow(i).getCell(8).getNumericCellValue();
if (status == 60 || status == 72 || status == 73 || status == 101) {
System.out.println("if succeed");
Double telephone = sheet1.getRow(i).getCell(2).getNumericCellValue();
int tel = telephone.intValue();
System.out.println("telephone is" + tel);
}
//Toast.makeText(this, "Telephone Number: " + Double.toString(telephone), Toast.LENGTH_SHORT).show();
// String exchange = sheet1.getRow(i).getCell(1).getStringCellValue();
// String complainTime =sheet1.getRow(i).getCell(5).getStringCellValue();
// phoneData.add(new PhoneData(Double.toString(telephone), exchange,Double.toString(status),complainTime));
// System.out.println("exchange is"+exchange + duration+status+complainTime );
}
System.out.println("Test Data From Excel" + duration);
System.out.println("Row Number" + i);
} else {
System.out.println("Not Numeric");
}
i++;
}
} catch (Exception e) {
e.printStackTrace();
}
return;
}
private static boolean isExternalStorageReadOnly() {
String extStorageState = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(extStorageState)) {
return true;
}
return false;
}
private static boolean isExternalStorageAvailable() {
String extStorageState = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(extStorageState)) {
return true;
}
return false;
}
}
I have below code and in this code i am using from HttpClient for connect to webservice .Net but when i using this, i get Error 500 from here Log.i("OK", Integer.toString(code)); but i need that when i get 200 i login to webSite and etc..
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
HttpClient client = new DefaultHttpClient();
HttpPost methodPost = new HttpPost("http://online.test.com/MobileWebService/Related.asmx/Login");
try {
HttpResponse response = client.execute(methodPost);
int code = response.getStatusLine().getStatusCode();
Log.i("OK", Integer.toString(code));
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
thread.start();
}
}
Notice 1 : ..../Login is a method in webService for login. It get 4 parameters .
Notice 2 : As the first step i should be sure that it is connected successfully (I mean I should get the "200") and then Login to webSite.
I don't like use KSOAP .
And below is my webService .Net:
[WebMethod(EnableSession = true)]
public int Login(string username, string pass, string device, int? security)
{
var ret = -3;
try
{
var bs = new BaseMaster();
if (!bs.securityRequest(10))
{
return -10;
}
bs.setLogMobileVisit();
if (string.IsNullOrEmpty(pass) || security == null || string.IsNullOrEmpty(username))
{
ret = -2;
}
else if (security != 128110)
{
ret = -1;
}
else
{
var user = GetUserByName(username);
var p = Hash.MD5(pass);
if (user != null && user.Hidden == false && user.Password == Hash.MD5(pass))
{
if (user.Firstname != device)
{
return -4;
}
var u = new UserDB();
u.LastLogDate = DateTime.Now;
u.UpdateDate = DateTime.Now;
u.UserID = user.UserID;
Makarem_Facade.MakaremFL.UpdateMobileUserDB(u);
ret = (int)user.UserID;
var pl = new PermissionDBList();
Security.Login(user,false,pl);
StartSession(user);
}
else if (user.Hidden == true)
{
ret = 0;
}
else if (user == null)
{
ret = -3;
}
else
{
ret = -5;
}
}
}
catch
{
ret = -6;
}
return ret;
}
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);
}
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).
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
i am developing an android application that will receive MMS from specific number and show it in my application, I found this code but when i run it, Nothing Happened
public class MMSActivity extends Activity {
ImageView imageView1;
TextView t;
MMSMonitor myMonitor = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
t= (TextView) findViewById(R.id.t);
imageView1= (ImageView) findViewById(R.id.imageView1);
startMMSMonitor();
}
#Override
public void onDestroy()
{
super.onDestroy();
if(myMonitor != null)
myMonitor.stopMMSMonitoring();
}
protected void startMMSMonitor()
{
Context ctx = this;
ContentResolver cr = this.getContentResolver();
myMonitor = new MMSMonitor(cr, ctx);
myMonitor.startMMSMonitoring();
}
public void setMMSText(String text)
{
//Do whatever you want
}
public void setMMSImageData(byte[] data, String fileType)
{
//Do whatever you want
}
public class MMSMonitor {
private ContentResolver contentResolver = null;
private Handler mmshandler = null;
private ContentObserver mmsObserver = null;
public String mmsNumber = "";
public boolean monitorStatus = false;
public String activationCode;
int mmsCount = 0;
String lastMMSTxId = null;
String code;
public MMSMonitor(final ContentResolver contentResolver, final Context mainContext) {
this.contentResolver = contentResolver;
mmshandler = new MMSHandler();
mmsObserver = new MMSObserver(mmshandler);
System.out.println( "MMSMonitor :: ***** Start MMS Monitor *****");
}
public void startMMSMonitoring() {
try {
monitorStatus = false;
if (!monitorStatus) {//do not get it
//it is observe anychange like delete or incoming MMS etc...
//ContentObserver is used to get notified if the data residing in the data set has changed.
//So it is used to observe the data source for changes.
//Content providers manage access to a structured set of data
//Content providers are the standard interface that connects data
//in one process with code running in another process.
//When you want to access data in a content provider, you use the ContentResolver object
contentResolver.registerContentObserver(Uri.parse("content://mms-sms"), true, mmsObserver);
Uri uriMMSURI = Uri.parse("content://mms");
Cursor mmsCur = contentResolver.query(uriMMSURI, null, "msg_box = 4", null, "_id");
if (mmsCur != null && mmsCur.getCount() > 0) {
//Number of MMS
mmsCount = mmsCur.getCount();
System.out.println( "MMSMonitor :: Init MMSCount ==" + mmsCount);
}
}
} catch (Exception e) {
System.out.println( "MMSMonitor :: startMMSMonitoring Exception== "+ e.getMessage());
}
}
public void stopMMSMonitoring() {
try {
monitorStatus = false;
if (!monitorStatus){
contentResolver.unregisterContentObserver(mmsObserver);
}
} catch (Exception e) {
System.out.println( "MMSMonitor :: stopMMSMonitoring Exception == "+ e.getMessage());
}
}
//A Handler allows you to send and process Message and Runnable objects associated with a thread's MessageQueue.
class MMSHandler extends Handler {
public void handleMessage(final Message msg) {
//Log("MMS", "MMSMonitor :: Handler");
}
}
class MMSObserver extends ContentObserver {
private Handler mms_handle = null;
public MMSObserver(final Handler mmshandle) {
super(mmshandle);
mms_handle = mmshandle;
}
public void onChange(final boolean bSelfChange) {
super.onChange(bSelfChange);
//Log("MMS", "MMSMonitor :: Onchange");
Thread thread = new Thread() {
public void run() {
try {
monitorStatus = true;
// Send message to Activity
Message msg = new Message();
mms_handle.sendMessage(msg);
// Getting the mms count
Uri uriMMSURI = Uri.parse("content://mms/");
Cursor mmsCur = contentResolver.query(uriMMSURI, null, "msg_box = 4 or msg_box = 1", null,"_id");
int currMMSCount = 0;
if (mmsCur != null && mmsCur.getCount() > 0) {
currMMSCount = mmsCur.getCount();
}
if (currMMSCount > mmsCount) {
mmsCount = currMMSCount;
mmsCur.moveToLast();
// get id , subject
//String subject = mmsCur.getString(6);
//int id = Integer.parseInt(mmsCur.getString(0));
String subject = mmsCur.getString(mmsCur.getColumnIndex("sub"));
int id = Integer.parseInt(mmsCur.getString(mmsCur.getColumnIndex("_id")));
System.out.println( "MMSMonitor :: _id == " + id);
System.out.println( "MMSMonitor :: Subject == " + subject);
byte[] imgData = null;
String message = "";
String address = "";
String fileName = "";
String fileType = "";
String direction = "";
// GET DIRECTION
boolean isIncoming = false;
//int type = Integer.parseInt(mmsCur.getString(12));
int type = Integer.parseInt(mmsCur.getString(mmsCur.getColumnIndex("m_type")));
if (type == 128) {
direction = "0";
System.out.println( "MMSMonitor :: Type == Outgoing MMS");
} else {
isIncoming = true;
direction = "1";
System.out.println( "MMSMonitor :: Type == Incoming MMS");
}
// Get Parts
Uri uriMMSPart = Uri.parse("content://mms/part");
Cursor curPart = contentResolver
.query(uriMMSPart, null, "mid = " + id, null, "_id");
System.out.println( "MMSMonitor :: parts records length == "+ curPart.getCount());
curPart.moveToLast();
do {
//String contentType = curPart.getString(3);
//String partId = curPart.getString(0);
String contentType = curPart.getString(curPart.getColumnIndex("ct"));
String partId = curPart.getString(curPart.getColumnIndex("_id"));
System.out.println( "MMSMonitor :: partId == " + partId);
System.out.println( "MMSMonitor :: part mime type == "+ contentType);
// Get the message
if (contentType.equalsIgnoreCase("text/plain"))
{
System.out.println("MMSMonitor :: ==== Get the message start ====");
byte[] messageData = readMMSPart(partId);
if (messageData != null && messageData.length > 0)
message = new String(messageData);
if(message == ""){
Cursor curPart1 = contentResolver
.query(uriMMSPart, null, "mid = " + id +
" and _id =" + partId,null, "_id");
for (int i = 0; i < curPart1.getColumnCount(); i++)
{
System.out.println("MMSMonitor :: Column Name : " +
curPart1.getColumnName(i));
}
curPart1.moveToLast();
message = curPart1.getString(13);
}
System.out.println("MMSMonitor :: Txt Message == " + message);
//SEND DATA TO ACTIVITY
setMMSText(message);
}
// Get Image
else if (isImageType(contentType) == true) {
System.out.println("MMSMonitor :: ==== Get the Image start ====");
fileName = "mms_" + partId;
fileType = contentType;
imgData = readMMSPart(partId);
System.out.println( "MMSMonitor :: Iimage data length == "+ imgData.length);
//SEND DATA TO ACTIVITY
setMMSImageData(imgData, fileType);
}
} while (curPart.moveToPrevious());
}
} catch (Exception e) {
System.out.println( "MMSMonitor Exception:: "+ e.getMessage());
}
}
};
thread.start();
}
}
private byte[] readMMSPart(String partId) {
byte[] partData = null;
Uri partURI = Uri.parse("content://mms/part/" + partId);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
InputStream is = null;
try {
System.out.println("MMSMonitor :: Entered into readMMSPart try..");
ContentResolver mContentResolver = contentResolver;
is = mContentResolver.openInputStream(partURI);
byte[] buffer = new byte[256];
int len = is.read(buffer);
while (len >= 0) {
baos.write(buffer, 0, len);
len = is.read(buffer);
}
partData = baos.toByteArray();
//Log.i("", "Text Msg :: " + new String(partData));
} catch (IOException e) {
System.out.println( "MMSMonitor :: Exception == Failed to load part data");
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
System.out.println("Exception :: Failed to close stream");
}
}
}
return partData;
}
private boolean isImageType(String mime) {
boolean result = false;
if (mime.equalsIgnoreCase("image/jpg")
|| mime.equalsIgnoreCase("image/jpeg")
|| mime.equalsIgnoreCase("image/png")
|| mime.equalsIgnoreCase("image/gif")
|| mime.equalsIgnoreCase("image/bmp")) {
result = true;
}
return result;
}
}
}
//=====================
}
any answer i will appreciate it,
also
what this statement suppose be to do ?
Cursor mmsCur = contentResolver.query(uriMMSURI, null, "msg_box = 4 or msg_box = 1", null,"_id");
I think your approach isn't even the right one.
Afaik you have to register a broadcastreceiver and handle/implement this in your app in order to achieve what you want.
See
Android MMS Broadcast receiver
Detecting new MMS (Android 2.1)
Detecting MMS messages on Android
There are all infos u need ;)