Wednesday, September 3, 2014

Java - ByteBuffer



There are 2 states in a ByteBuffer object, read-mode and write-mode. There are 3 importantsvalues in a ByteBuffer:
position, limit and capacity.

Capacity: this gives us the maximum bytes a buffer can have, it's a buffer size.

Position: in write-mode it's the index of the next byte to write. If 4 bytes has been written into a ByteBuffer object, than the position is 4, which is the 5th element of a ByteBuffer's array. In read-mode it's the index of the next byte to read, the logic is the same as in write-mode.

Limit: is the space left to write or the amount of bytes yet to read, depending on the state.

Initial state of ByteBuffer is write-mode, why? Well, if you create a new buffer, the buffer is normally empty,
because you haven't filled it yet, so there's nothing to read also. So the first thing to do is to fill the buffer with data, that's why the first state of a ByteBuffer object is write-mode.

Write data to ByteBuffer:
byte[] data = new byte[48];
byteBuffer.put(data, 0, numBytes);

Remaining data means in this state (write-mode), how many bytes available in the buffer to write.
byteBuffer.remaining();

Switch from write-mode to read-mode
byteBuffer.flip();

Remaining data means in this state (=read-mode), how many bytes available left in the buffer to read.
byteBuffer.remaining();

Read data into the buffer:
byteBuffer.get(buffer);

This method means clear all the bytes, reset its states and switch to write-mode.
byteBuffer.clear();

This method means move the remaining bytes to the beginning of the buffer, update its states and switch to write-mode.
byteBuffer.compact();

This method resets its states after reading, so you can read again from the beginning.
byteBuffer.rewind();

mark its current states
byteBuffer.mark();
do some reading...
change it to its pervious states
byteBuffer.reset();

Source:
http://www.ibm.com/developerworks/java/tutorials/j-nio/j-nio.html
http://www.tech-recipes.com/rx/1438/java-working-with-buffers/
http://tutorials.jenkov.com/java-nio/buffers.html

Monday, August 25, 2014

Android - Developer options on Samsung S3

How to enable development on a Samsung S3?

It wasn't easy to enable developer options for the Samsung S3 (apparently also S4) as this feature is hidden. To make it unhidden you have to do the following steps:
  • Go to Settings -> More -> About Device
  • Scroll down to Build Number
  • Tap on it multiple times, it than shows a Toast how many times left to tap.
  • Finally you get a message that you've become a developer.
  • Now go to Developer options in Settings -> More.
Good luck :)

iOS - Ad Hoc distribution

Coming soon...

Thursday, April 10, 2014

iOS snippets part 1

Here are some snippets I use for the iOS platform. Since I work on several platforms (MS Windows, Linux, Android and iOS using languages like C, C#, C++, Obj-C, Java, PHP etc...) , I thought it would be better to put a bunch of useful and often used snippets on my blog, so I don't have to google a lot. Once you understand how to program, it's not important anymore what language you use or what platform you're developing for.

I hope those sinppets are useful for you, let's start :-)


Message Box

- (IBAction)btnExit:(id)sender {
    UIAlertView *messageBox = [[UIAlertView alloc] initWithTitle:@"Exit"
                                                      message:@"Are you sure?"
                                                     delegate:self
                                            cancelButtonTitle:@"No"
                                            otherButtonTitles:@"Yes", nil];
    [messageBox show];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    NSString *title = [alertView buttonTitleAtIndex:buttonIndex];
   
    if([title isEqualToString:@"No"]) {
        NSLog(@"No was selected.");
    }
    else if([title isEqualToString:@"Yes"]) {
        NSLog(@"Yes was selected.");
    }
}




Timer 1

- (void) startTimer {
    NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval: 0.1 target:self selector:@selector(fireMe) userInfo:nil repeats:YES];
}

- (void) fireMe {
    NSLog(@"I'm fired!");
}


By setting the repeats on YES, makes the timer execute every 0.1 sec which is 100 ms. By setting it to NO, will execute the timer just once.


Timer 2

- (void) startTimer {
    NSTimer *timer = [[ NSTimer alloc ] initWithFireDate: [NSDate dateWithTimeIntervalSinceNow: 0.0
                                                 interval: 0.1
                                                   target: self
                                                 selector: @selector(fireMe)
                                                 userInfo: nil
                                                  repeats: NO];
}


This is another way to start a timer.



Worker-thread using GCD (Grand Central Dispatch)

dispatch_queue_t myQueue = dispatch_queue_create("my queue",NULL);
...
...
...
dispatch_async(imageQueue, ^{
        // This will run the method in a separate thread
        [self doSomeLongRunningTask];
    });


- (void) doSomeLongRunningTask {
    dispatch_async(dispatch_get_main_queue(), ^{
            NSLog(@"We finished a heavy task!");
        });
}


So, we create a dispatch queue handle for our separated thread, than pass a block ^{} to dispatch_async that will be executed in a separate thread ( NOT in the main thread). If you want to call a method in the main thread from another thread, you call:  dispatch_async(dispatch_get_main_queue(), ^{ }); As you see, dispatch_get_main_queue() gives you the queue handle of the main thread.
For more information, check: GDC



Thread with NSThread

NSThread *thread = [[NSThread alloc] initWithTarget:self
                                     selector:@selector(run:)
                                       object:nil];
[thread start];

...
...
- (void) run: (id) object{
    NSLog(@"I'm running in another thread :D");
}


This is a simple example to create another thread and run it by calling the start method.



TCP Sockets with streams

NSInputStream *inputStream;
NSOutputStream *outputStream;
CFReadStreamRef readStream;
CFWriteStreamRef writeStream;


CFStreamCreatePairWithSocketToHost( NULL, (__bridge CFStringRef)hostIp, hostPort, &readStream, &writeStream );
CFReadStreamSetProperty(readStream, kCFStreamPropertyShouldCloseNativeSocket, kCFBooleanTrue);
CFWriteStreamSetProperty(writeStream, kCFStreamPropertyShouldCloseNativeSocket, kCFBooleanTrue);


inputStream = (__bridge NSInputStream *)readStream;
outputStream = (__bridge NSOutputStream *)writeStream;
...
...
// ope connection
[ inputStream open ];
[ outputStream open ];
...
int len = (int) [outputStream write: buffer maxLength: size];
len = (int) [inputStream read: buffer maxLength: size];


Using streams with NSRunLoop

[inputStream setDelegate:self ]; //This will call stream: handleEvent:

NSRunLoop *runLoop = [ NSRunLoop currentRunLoop ];
[inputStream scheduleInRunLoop: runLoop forMode:NSDefaultRunLoopMode];
[runLoop run]

// This will be called from runLoop
- (void) stream:(NSStream *)aStream handleEvent:(NSStreamEvent)eventCode {
    switch ( eventCode ) {
        case NSStreamEventOpenCompleted: 

            break;
        case NSStreamEventHasSpaceAvailable:
            break;
        case NSStreamEventHasBytesAvailable:

            break;           
        case NSStreamEventErrorOccurred:
            break;
        case NSStreamEventEndEncountered:
            break;
        default:

    }
}




 

NSNotification example