Search code examples
androidapportable

Can't open mail attachment on Android using Apportable


I've tried open mail attachment. Receive url in following method

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation

But can't get data from this url

NSData *data = [NSData dataWithContentsOfFile:[url path]]
// data is nil

Received url

content://gmail-ls/[email protected]/messages/1/attachments/0.0/BEST/false

Solution

  • I've used Android SDK to resolve this problem. You can look how use java with apportable here.

    This is my java code

    static private byte[] readBytes(InputStream inputStream) throws IOException {
        // this dynamically extends to take the bytes you read
        ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();
    
        // this is storage overwritten on each iteration with bytes
        int bufferSize = 1048576;
        byte[] buffer = new byte[bufferSize];
    
        // we need to know how may bytes were read to write them to the byteBuffer
        int len = 0;
        while ((len = inputStream.read(buffer)) != -1) {
            byteBuffer.write(buffer, 0, len);
        }
    
        // and then we can return your byte array.
        return byteBuffer.toByteArray();
    }
    
    public byte[] dataFromUrl(String path, Activity activity) {
        Uri uri = Uri.parse(path);
    
        InputStream is = null;
        byte[] data = null;
    
        try {
            is = activity.getContentResolver().openInputStream(uri);
            data = readBytes(is);
        } catch (Exception e) {
            e.printStackTrace();
        }
    
        return data;
    }
    

    And Objective-C part

    + (void)initializeJava
    {
        [super initializeJava]; 
    
        // here your initialize code
        ...
    
        [KeyboardBridge registerInstanceMethod:@"dataFromUrl"
                                      selector:@selector(dataFromUrl:forActivity:)
                                   returnValue:[NSData className]
                                     arguments:[NSString className], [AndroidActivity className], nil];
    
    }
    
    - (NSData *)dataFromUrl:(NSString *)path {
        return [self dataFromUrl:path forActivity:[AndroidActivity currentActivity]];
    }