Formula for color contrast between text and background

In my Android app a user can choose the color of an item. This color is then shown in background with a text on it. I want to display the text either in black or white - depending on the background color.

Is there a formula to calculate when it is better to show a text in white and not in black? I guess I am looking for the darkness of a color and the exact value when it is more black than white.