Example how to take photo and upload it’s thumbnail to your server using okhttp3 (first I convert it to jpeg)

//part when you click on item and start camera
imageView.setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {
        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        Context context = v.getContext();

        if (takePictureIntent.resolveActivity(context.getPackageManager()) != null) {
            startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);

//part when you get the thumbnail from camera
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == Activity.RESULT_OK) {
        Bundle extras = data.getExtras();
        Bitmap imageBitmap = (Bitmap) extras.get("data");

        new AsyncTask() {
            protected Void doInBackground(Bitmap... bitmaps) {
                OkHttpClient client = new OkHttpClient();

                ByteArrayOutputStream stream = new ByteArrayOutputStream();
                bitmaps[0].compress(Bitmap.CompressFormat.JPEG, 100, stream);
                byte[] byteArray = stream.toByteArray();

                //there are some my custom fields form
                RequestBody requestBody = new MultipartBody.Builder()
                        .addFormDataPart("submit", "")
                        .addFormDataPart("name", "myPhotoName")
                        .addFormDataPart("photo", "tmp_photo_" + System.currentTimeMillis(), RequestBody.create(MediaType.parse("image/jpeg"), byteArray))

                Request request = new Request.Builder()

                Response response = null;
                try {
                    response = client.newCall(request).execute();
                    if (response.isSuccessful()) {
                        Log.d(TAG, "doInBackground: upload success");
                    } else {
                        Log.d(TAG, "doInBackground: upload failed");
                } catch (IOException e) {
                return null;
    } else {
        //another results
        super.onActivityResult(requestCode, resultCode, data);

Wireshark – filter out only results if they are method type POST or GET and not containing in url special word

Example of filtering only that results which have request method as GET or POST and special word is not in url:

(http.request.method == GET or http.request.method == POST) and !http.request.uri contains "css"

Notepad++ with regex, re-using match variables

Here is an simple example how to use regex in notepad++ with reusing selected match variables.

For example we have special code for simulating gcm notifications. We would like to see it in pretty style.
To achieve this we must to move all elements with minus to the new lines. How to do it? Here is the solution.

We have this string:
adb shell am broadcast -a com.google.android.c2dm.intent.RECEIVE -c com.example.android.debug -n com.example.android.google.debug/com.example.android.gcm.GcmBroadcastReceiver --es "aaa" "123" --es "mmm" "bla bla bla" --es "sss" "321" --es "from" "111" --es "type" "yesterday" --es "collapse_key" "do_not_collapse"

By using bellow command in notepad++:

Searching text:


Replace with:


We get the quite pretty result:

adb shell am broadcast
-a com.google.android.c2dm.intent.RECEIVE
-c com.example.android.debug
-n com.example.android.google.debug/com.example.android.gcm.GcmBroadcastReceiver
--es "aaa" "123"
--es "mmm" "bla bla bla"
--es "sss" "321"
--es "from" "111"
--es "type" "yesterday"
--es "collapse_key" "do_not_collapse"

Working example POST in android

Here is another short (IMHO) example how to post in android app.

private void postSms(String text) {
URL url;
HttpURLConnection urlConnection = null;

try {
url = new URL("http://yourserver.com/sendsms");
urlConnection = (HttpURLConnection) url.openConnection();

List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("sms", text));//POST param as "sms"

OutputStream os = urlConnection.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));

String status = new String(Streams.getBytes(urlConnection.getInputStream()));
Log.d(TAG, new Exception().getStackTrace()[0].getMethodName() + ":insert status=" + status);

} catch (MalformedURLException | ProtocolException e) {
} catch (IOException e) {

This is a method for concatenating parameters for POST

Continue reading “Working example POST in android”

GCM notification with custom sound – shorter version (part)

Here is a short example how to create notification with default stuff but different sound:

NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setStyle(new NotificationCompat.BigTextStyle()
.setDefaults(NotificationCompat.DEFAULT_ALL ^ NotificationCompat.DEFAULT_SOUND);

The most important part is here:

.setDefaults(NotificationCompat.DEFAULT_ALL ^ NotificationCompat.DEFAULT_SOUND)



says “except”, so the last part would say “give me default notification except sound setting”

Working example – changing drawable background in runtime, dynamically

Here is a short example code how to do it:
I’ve created xml file shape.xml and one method for flexible changing color of shape.


<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >
<solid android:color="@android:color/holo_blue_bright" />
<corners android:radius="30dp" />
android:width="15dp" />

And here is a method for flexible changing color:

Continue reading “Working example – changing drawable background in runtime, dynamically”

Working example of setting alarm with repeating stuff, checking if alarm was set with pendingIntent

Here is short and quite (imho) understanding part of code:

//starting #1
AlarmManager alarmManager = (AlarmManager) getActivity().getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(getActivity(), MyReceiver.class);
intent.setAction(MyReceiver.ACTION_ALARM_RECEIVER);//my custom string action name
PendingIntent pendingIntent = PendingIntent.getBroadcast(getActivity(), 1001, intent, PendingIntent.FLAG_CANCEL_CURRENT);//used unique ID as 1001
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), aroundInterval, pendingIntent);//first start will start asap

#1 – first we are getting alarm service. We create own intention and setting own action to it to be able handle in onReceive(), in our receiver class. Then the intention is putting into pendingIntent. The complete pendingIntent is used by alarmManager for a start.
I used System.currentTimeMillis() because I wanted start repeating asap.
I used flag PendingIntent.FLAG_CANCEL_CURRENT for pendingIntent but it might be also PendingIntent.FLAG_UPDATE_CURRENT. It is important to use the same flag everywhere, but when you want stop it, you use PendingIntent.FLAG_NO_CREATE. I will write about it later.
Number 1001 in pendingIntent was used just to be know that our intention has unique ID.

Continue reading “Working example of setting alarm with repeating stuff, checking if alarm was set with pendingIntent”

Custom checkable list item with checkbox (layout+code)

Here is simple example how to create simple checkable list item with checbox.

This a code for widget:

public class CheckableTextView extends LinearLayout {

private TextView checkLabel;
private CheckBox checkBox;

public CheckableTextView(Context context) {

public CheckableTextView(Context context, AttributeSet attrs) {
super(context, attrs);


public CheckableTextView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);

private void init() {
View v = inflate(getContext(), R.layout.widget_checkabletextview_merged, this);
checkLabel = ((TextView) v.findViewById(R.id.checkLabel));
checkBox = ((CheckBox) v.findViewById(R.id.checkBox));

v.setOnClickListener(new OnClickListener() {
public void onClick(View view) {

public void setText(CharSequence c) {

public void setText(String c) {

public void setChecked(boolean status)


This is the widget’s layout:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

android:text="Sample text" />

android:focusable="false" />


Example of one item: