any example of IMAP and if possible source code of IMAP and Android.
http://code.google.com/hosting/search?q=label%3AAndroid+IMAP&projectsearch=Search+projects
protected InputStream getContentStream() throws MessagingException {
InputStream is = null;
boolean pk = message.getPeek(); // acquire outisde of message cache lock
// Acquire MessageCacheLock, to freeze seqnum.
synchronized(message.getMessageCacheLock()) {
try {
IMAPProtocol p = message.getProtocol();
// Check whether this message is expunged
message.checkExpunged();
if (p.isREV1() && (message.getFetchBlockSize() != -1))
return new IMAPInputStream(message, sectionId, bs.size, pk);
// Else, vanila IMAP4, no partial fetch
int seqnum = message.getSequenceNumber();
BODY b;
if (pk)
b = p.peekBody(seqnum, sectionId);
else
b = p.fetchBody(seqnum, sectionId);
if (b != null)
is = b.getByteArrayInputStream();
} catch (ConnectionException cex) {
throw new FolderClosedException(
message.getFolder(), cex.getMessage());
} catch (ProtocolException pex) {
throw new MessagingException(pex.getMessage(), pex);
}
refer this
Related
Some background: I have been trying to refactor this Android app's Usb system. Initially, in order to transfer data between endpoints, they used the UsbDeviceConnection.bulkTransfer() method. I refactored it to use the UsbRequest.initialize(), UsbRequest.queue(), and then UsbDeviceConnection.requestWait() methods. When the Android program is booted on the tablet, my new methods work fine (perhaps even better), but when there is a USB disruption/disconnection from the external device, once reconnected, it won't pick up where it left off. However, their old method, UsbDeviceConnection.bulkTransfer() DOES pick up communication upon reconnect.
Here is the code I refactored, along with the original method:
Original Method [bulkTransfer()] -
byte[] response = new byte[64];
int result = 0;
int tries = 0;
while (result < 1){
if (tries > 5) {
Log.d("PayloadTask", "PayloadTask Timed Out.");
return null;
} else if (isCancelled()) {
Log.w("PayloadTask", "PayloadTask Cancelled!");
return null;
}
/*synchronized (usbConnection)*/
result = usbConnection.bulkTransfer(usbFromAggBoard, response, response.length, 25);
tries += 1;
}
Log.i("PayloadTask", new Integer(response.length).toString() + " bytes received: ");
Log.d("PayloadTask", "doInBackground returning some payload from the aggboard.");
return Payload.CreatePayload(response);
Refactored Code [UsbRequest/requestWait()] -
byte[] response = new byte[64];
int result = 0;
int tries = 0;
while (result < 1){
if (tries > 5) {
Log.d("PayloadTask", "PayloadTask Timed Out.");
return null;
} else if (isCancelled()) {
Log.w("PayloadTask", "PayloadTask Cancelled!");
return null;
}
/*synchronized (usbConnection)*/
if (usbConnection != null) {
UsbRequest request = new UsbRequest();
ByteBuffer byteBuffer = ByteBuffer.wrap(response);
byteBuffer.rewind();
try {
request.initialize(usbConnection, usbFromAggBoard);
if (!request.queue(byteBuffer, response.length)) {
throw new IOException("Error queueing USB request.");
}
usbConnection.requestWait();
} catch (IOException e) {
e.printStackTrace();
} finally {
if(usbConnection != null) {
result = request.hashCode();
request.close();
}
else{
Log.d("PayloadTask", "Request not received by usbConnection");
}
}
}
tries += 1;
}
Log.i("PayloadTask", new Integer(response.length).toString() + " bytes received: ");
Log.d("PayloadTask", "doInBackground returning some payload from the aggboard.");
return Payload.CreatePayload(response);
I'm trying to implement a way to listen to a client's connection event on the smartphone hotspot. I see that android.net.wifi.WIFI_HOTSPOT_CLIENTS_CHANGED is no longer avaible. How can i do this? I think that this is possible because the smartphone notify me when i client make a connection to the smartphone hotspot.
You can't use the Intent Action...You have to use a custom method, i'l suggest you create a background thread that checks/reads the I.P table (/proc/net/arp) constantly and update you...here's a snippet I've used.
Read i.p list table
public ArrayList<String> getConnectedDevices() {
ArrayList<String> arrayList = new ArrayList();
try {
BufferedReader bufferedReader = new BufferedReader(new FileReader("/proc/net/arp"));
while (true) {
String readLine = bufferedReader.readLine();
if (readLine == null) {
break;
}
String[] split = readLine.split(" +");
if (split != null && split.length >= 4) {
arrayList.add(split[0]);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return arrayList;
}
Create runnable to check
class CheckHotSpotConnection implements Runnable {
private CheckHotSpotConnection() {
}
public void run() {
int i = 0;
while (discoverClient()) {
i = getConnectedDevices().size();
if (i > 1) {
//client discovered
//disable client discovery to end thread
} else {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
Start Thread
new Thread(new CheckHotSpotConnection()).start();
I am using CSipSimple for adding a new feature which is transfer call . For this feature I need the callID of call .
I am seeing that when I call ,the following function is called .
public void placeCallWithOption(Bundle b) {
if (service == null) {
return;
}
String toCall = "";
Long accountToUse = SipProfile.INVALID_ID;
// Find account to use
SipProfile acc = accountChooserButton.getSelectedAccount();
if(acc == null) {
return;
}
accountToUse = acc.id;
// Find number to dial
toCall = digits.getText().toString();
if(isDigit) {
toCall = PhoneNumberUtils.stripSeparators(toCall);
}
if(accountChooserFilterItem != null && accountChooserFilterItem.isChecked()) {
toCall = rewriteNumber(toCall);
}
if (TextUtils.isEmpty(toCall)) {
return;
}
// Well we have now the fields, clear theses fields
digits.getText().clear();
// -- MAKE THE CALL --//
if (accountToUse >= 0) {
// It is a SIP account, try to call service for that
try {
service.makeCallWithOptions(toCall, accountToUse.intValue(), b);
// service.xfer(callId,"01628105601");
} catch (RemoteException e) {
Log.e(THIS_FILE, "Service can't be called to make the call");
}
} else if (accountToUse != SipProfile.INVALID_ID) {
// It's an external account, find correct external account
CallHandlerPlugin ch = new CallHandlerPlugin(getActivity());
ch.loadFrom(accountToUse, toCall, new OnLoadListener() {
#Override
public void onLoad(CallHandlerPlugin ch) {
placePluginCall(ch);
}
});
}
}
But from this , I can't get callId of the call. How can I get callId of each call ? Any advice is of great help .
Using SipCallSession to fetch a call id
SipCallSession callInfo = new SipCallSession();
callinfo.getCallid();
Edit:- i'm able to start the internet using vpn.The other issues is that now i'm receiving packets in my service in this piece of code of my VpnService.But i can't think of a proper way to block particular website.I've tried using name resolution using InnetAddress but that's not giving the expected result :
**#Override
public void run()
{
Log.i(TAG, "Started");
FileChannel vpnInput = new FileInputStream(vpnFileDescriptor).getChannel();
FileChannel vpnOutput = new FileOutputStream(vpnFileDescriptor).getChannel();
try
{
ByteBuffer bufferToNetwork = null;
boolean dataSent = true;
boolean dataReceived;
while (!Thread.interrupted())
{
if (dataSent)
bufferToNetwork = ByteBufferPool.acquire();
int readBytes = vpnInput.read(bufferToNetwork);
if (readBytes > 0)
{
dataSent = true;
bufferToNetwork.flip();
Packet packet = new Packet(bufferToNetwork);
Log.e("loggg packet",packet.toString());
if (packet.isUDP())
{
deviceToNetworkUDPQueue.offer(packet);
}
else if (packet.isTCP())
{
deviceToNetworkTCPQueue.offer(packet);
}
else
{
Log.w(TAG, "Unknown packet type");
dataSent = false;
}
}
else
{
dataSent = false;
}
ByteBuffer bufferFromNetwork = networkToDeviceQueue.poll();
if (bufferFromNetwork != null)
{
bufferFromNetwork.flip();
vpnOutput.write(bufferFromNetwork);
dataReceived = true;
ByteBufferPool.release(bufferFromNetwork);
}
else
{
dataReceived = false;
}
if (!dataSent && !dataReceived)
Thread.sleep(10);
}
}
catch (InterruptedException e)
{
Log.i(TAG, "Stopping");
}
catch (IOException e)
{
Log.w(TAG, e.toString(), e);
}
finally
{
closeResources(vpnInput, vpnOutput);
}
}**
I'm receiving a packet in this format:
Packet{ip4Header=IP4Header{version=4, totalLength=40, protocol=TCP, headerChecksum=14192, sourceAddress=10.0.8.1, destinationAddress=216.58.196.100}, tcpHeader=TCPHeader{sourcePort=39217, destinationPort=443, sequenceNumber=800911985, acknowledgementNumber=823271551, headerLength=20, window=29596, checksum=32492, flags= ACK}, payloadSize=0}
I'm using THIS CODE for starter and unable to block packets.
Apps like greyshirts no root firewall and mobiwool no root firewall works perfectly and they are also vpn based.Any suggestion is most welcomed.
I want to send multiple images those are present in my internal storage and when i selects that folder i want upload that folder into google drive. i have tried this google drive api for android https://developers.google.com/drive/android/create-file
and i have used the below code but it shows some error in getGoogleApiClient
the code is
ResultCallback<DriveContentsResult> contentsCallback = new
ResultCallback<DriveContentsResult>() {
#Override
public void onResult(DriveContentsResult result) {
if (!result.getStatus().isSuccess()) {
// Handle error
return;
}
MetadataChangeSet metadataChangeSet = new MetadataChangeSet.Builder()
.setMimeType("text/html").build();
IntentSender intentSender = Drive.DriveApi
.newCreateFileActivityBuilder()
.setInitialMetadata(metadataChangeSet)
.setInitialDriveContents(result.getDriveContents())
.build(getGoogleApiClient());
try {
startIntentSenderForResult(intentSender, 1, null, 0, 0, 0);
} catch (SendIntentException e) {
// Handle the exception
}
}
}
is there any approach to send images to drive or gmail?
I can't give you the exact code that does what you need, but you may try to modify the code I use for testing Google Drive Android API (GDAA). It creates folders and uploads files to Google Drive. It is up to you if you choose the REST or GDAA flavor, each has it's specific advantages.
This covers only a half of your question, though. Selecting and enumerating files on your Android device should be covered elsewhere.
UPDATE: (per Frank's comment below)
The example I mentioned above would give you a full solution from scratch, but let's address the points of your question I could decipher:
The hurdle 'some error' is a method that returns GoogleApiClient object initialized prior to your code sequence. Would look something like:
GoogleApiClient mGAC = new GoogleApiClient.Builder(appContext)
.addApi(Drive.API).addScope(Drive.SCOPE_FILE)
.addConnectionCallbacks(callerContext)
.addOnConnectionFailedListener(callerContext)
.build();
If you have this cleared out, let's assume your folder is represented by a java.io.File object. Here is the code that:
1/ enumerates the files in you local folder
2/ sets the name, content and MIME type of each file (using jpeg for simplicity here).
3/ uploads each file to the root folder of Google drive
(the create() method must run off-UI thread)
// enumerating files in a folder, uploading to Google Drive
java.io.File folder = ...;
for (java.io.File file : folder.listFiles()) {
create("root", file.getName(), "image/jpeg", file2Bytes(file))
}
/******************************************************
* create file/folder in GOODrive
* #param prnId parent's ID, (null or "root") for root
* #param titl file name
* #param mime file mime type
* #param buf file contents (optional, if null, create folder)
* #return file id / null on fail
*/
static String create(String prnId, String titl, String mime, byte[] buf) {
DriveId dId = null;
if (mGAC != null && mGAC.isConnected() && titl != null) try {
DriveFolder pFldr = (prnId == null || prnId.equalsIgnoreCase("root")) ?
Drive.DriveApi.getRootFolder(mGAC):
Drive.DriveApi.getFolder(mGAC, DriveId.decodeFromString(prnId));
if (pFldr == null) return null; //----------------->>>
MetadataChangeSet meta;
if (buf != null) { // create file
DriveContentsResult r1 = Drive.DriveApi.newDriveContents(mGAC).await();
if (r1 == null || !r1.getStatus().isSuccess()) return null; //-------->>>
meta = new MetadataChangeSet.Builder().setTitle(titl).setMimeType(mime).build();
DriveFileResult r2 = pFldr.createFile(mGAC, meta, r1.getDriveContents()).await();
DriveFile dFil = r2 != null && r2.getStatus().isSuccess() ? r2.getDriveFile() : null;
if (dFil == null) return null; //---------->>>
r1 = dFil.open(mGAC, DriveFile.MODE_WRITE_ONLY, null).await();
if ((r1 != null) && (r1.getStatus().isSuccess())) try {
Status stts = bytes2Cont(r1.getDriveContents(), buf).commit(mGAC, meta).await();
if ((stts != null) && stts.isSuccess()) {
MetadataResult r3 = dFil.getMetadata(mGAC).await();
if (r3 != null && r3.getStatus().isSuccess()) {
dId = r3.getMetadata().getDriveId();
}
}
} catch (Exception e) { /* error handling*/ }
} else {
meta = new MetadataChangeSet.Builder().setTitle(titl).setMimeType("application/vnd.google-apps.folder").build();
DriveFolderResult r1 = pFldr.createFolder(mGAC, meta).await();
DriveFolder dFld = (r1 != null) && r1.getStatus().isSuccess() ? r1.getDriveFolder() : null;
if (dFld != null) {
MetadataResult r2 = dFld.getMetadata(mGAC).await();
if ((r2 != null) && r2.getStatus().isSuccess()) {
dId = r2.getMetadata().getDriveId();
}
}
}
} catch (Exception e) { /* error handling*/ }
return dId == null ? null : dId.encodeToString();
}
//-----------------------------
static byte[] file2Bytes(File file) {
if (file != null) try {
return is2Bytes(new FileInputStream(file));
} catch (Exception e) {}
return null;
}
//----------------------------
static byte[] is2Bytes(InputStream is) {
byte[] buf = null;
BufferedInputStream bufIS = null;
if (is != null) try {
ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();
bufIS = new BufferedInputStream(is);
buf = new byte[2048];
int cnt;
while ((cnt = bufIS.read(buf)) >= 0) {
byteBuffer.write(buf, 0, cnt);
}
buf = byteBuffer.size() > 0 ? byteBuffer.toByteArray() : null;
} catch (Exception e) {}
finally {
try {
if (bufIS != null) bufIS.close();
} catch (Exception e) {}
}
return buf;
}
//--------------------------
private static DriveContents bytes2Cont(DriveContents driveContents, byte[] buf) {
OutputStream os = driveContents.getOutputStream();
try { os.write(buf);
} catch (IOException e) {/*error handling*/}
finally {
try { os.close();
} catch (Exception e) {/*error handling*/}
}
return driveContents;
}
Needles to say the code here is taken directly from the GDAA wrapper here (mentioned at the beginning), so if you need to resolve any references you have to look up the code there.
Good Luck