Create a Bound Service on Android

AndroidManifest.xml

<service android:name=".MyService"/>

MyService.java

public class MyService extends Service {

    Binder mBinder = new LocalService();

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }


    public class LocalService extends Binder {

        MyService getService() {
            return MyService.this;
        }

    }

    public String getFirstMessage() {
        return "Message 1";
    }

    public String getSecondMessage() {
        return "Message 2";
    }
}

MainActivity.java

public class MainActivity extends AppCompatActivity {

    MyService myService = null;

    Button buttonMessage1;
    Button buttonMessage2;
    TextView textViewOutput;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Intent intent = new Intent(MainActivity.this, MyService.class);
        bindService(intent, serviceConnection, BIND_AUTO_CREATE);

        buttonMessage1 = (Button) findViewById(R.id.buttonMessage1);
        buttonMessage2 = (Button) findViewById(R.id.buttonMessage2);
        textViewOutput = (TextView) findViewById(R.id.textViewOutput);

        buttonMessage1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (myService != null) {
                    textViewOutput.setText(myService.getFirstMessage());
                }
            }
        });

        buttonMessage2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (myService != null) {
                    textViewOutput.setText(myService.getSecondMessage());
                }
            }
        });
    }

    ServiceConnection serviceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            MyService.LocalService localService = (MyService.LocalService) iBinder;
            myService = localService.getService();
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            myService = null;
        }
    };

    @Override
    protected void onStop() {
        super.onStop();

        unbindService(serviceConnection);
        myService = null;
    }
}

References
https://www.youtube.com/watch?v=PUxC6vzEEgg
https://github.com/mhdr/AndroidSamples/tree/master/101

Service Using IntentService on Android

public class MyService extends IntentService {

    int counter = 0;

    public MyService() {
        super("MyServiceThread");
    }

    @Override
    protected void onHandleIntent(@Nullable Intent intent) {

        counter++;
        Handler handler = new Handler(getMainLooper());
        handler.post(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(MyService.this, "Service Stared: " + counter, Toast.LENGTH_SHORT).show();
            }
        });

        for (int i = 0; i < 10; i++) {
            try {
                wait(1500);

            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }

    @Override
    public void onDestroy() {
        Toast.makeText(MyService.this, "Service Stopped", Toast.LENGTH_SHORT).show();
    }
}

References
https://www.youtube.com/watch?v=cpq163QF2nM
https://github.com/mhdr/AndroidSamples/tree/master/100

Using Thread in Android Service

MyService.java

public class MyService extends Service {

    Thread workerThread = null;
    int counter=0;

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        final Handler handler = new Handler(getMainLooper());

        synchronized (this) {
            Runnable runnable = new Runnable() {
                @Override
                public void run() {

                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            counter++;
                            Toast.makeText(MyService.this, "Service Started: " + counter, Toast.LENGTH_SHORT).show();
                        }
                    });


                    for (int i = 0; i < 10; i++) {
                        try {
                            wait(1500);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
            };

            if (workerThread == null) {
                workerThread = new Thread(runnable);
                workerThread.start();
            }
        }

        return Service.START_STICKY;
    }


    @Override
    public void onDestroy() {
        super.onDestroy();

        if (workerThread != null) {
            workerThread.interrupt();
            workerThread = null;
            Toast.makeText(MyService.this, "Service Stopped", Toast.LENGTH_SHORT).show();
        }

    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}

AndroidManifest.xml

<service android:name=".MyService" />

MainActivity.java

public class MainActivity extends AppCompatActivity {

    Button buttonStartService;
    Button buttonStopService;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        buttonStartService = (Button) findViewById(R.id.buttonStartService);
        buttonStopService = (Button) findViewById(R.id.buttonStopService);

        buttonStartService.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(MainActivity.this, MyService.class);
                startService(intent);
            }
        });

        buttonStopService.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(MainActivity.this, MyService.class);
                stopService(intent);
            }
        });
    }
}

References
https://www.youtube.com/watch?v=foGmyYe2bV8
https://github.com/mhdr/AndroidSamples/tree/master/099

Running code in Main thread from another thread using Handler

runOnUiThread() will execute the Runnable immediately. but post() always puts the Runnable at the end of the event queue, even if you are already on the main application thread

// Get a handler that can be used to post to the main thread
Handler mainHandler = new Handler(context.getMainLooper());

Runnable myRunnable = new Runnable() {
    @Override 
    public void run() {....} // This is your code
};
mainHandler.post(myRunnable);
MainActivity.this.runOnUiThread(new Runnable() {
    public void run() {
        Log.d("UI thread", "I am the UI thread");
    }
});

References
https://stackoverflow.com/questions/11123621/running-code-in-main-thread-from-another-thread
https://stackoverflow.com/questions/12850143/android-basics-running-code-in-the-ui-thread

Create a Started Service on Android

MyService.java

public class MyService extends Service {

    private int counter=0;

    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        counter++;

        Toast.makeText(this, "Service Started : " + counter, Toast.LENGTH_SHORT).show();

        return Service.START_STICKY;
    }

    @Override
    public void onDestroy() {
        Toast.makeText(this, "Service Stopped", Toast.LENGTH_SHORT).show();
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}

MainActivity.java

public class MainActivity extends AppCompatActivity {


    Button buttonStartService;
    Button buttonStopService;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        buttonStartService = (Button) findViewById(R.id.buttonStartService);
        buttonStopService = (Button) findViewById(R.id.buttonStopService);

        buttonStartService.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(MainActivity.this, MyService.class);
                startService(intent);
            }
        });

        buttonStopService.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(MainActivity.this, MyService.class);
                stopService(intent);
            }
        });
    }
}

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="pupli.net.a098">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <service android:name=".MyService" />
    </application>

</manifest>

References
https://www.youtube.com/watch?v=HYctmRwYHOg
https://github.com/mhdr/AndroidSamples/tree/master/098

Working with Display orientation on Android

Method

public int getScreenOrientation()
{
    Display getOrient = getWindowManager().getDefaultDisplay();
    int orientation = Configuration.ORIENTATION_UNDEFINED;
    if(getOrient.getWidth()==getOrient.getHeight()){
        orientation = Configuration.ORIENTATION_SQUARE;
    } else{ 
        if(getOrient.getWidth() < getOrient.getHeight()){
            orientation = Configuration.ORIENTATION_PORTRAIT;
        }else { 
             orientation = Configuration.ORIENTATION_LANDSCAPE;
        }
    }
    return orientation;
}

Event

@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);

    // Checks the orientation of the screen
    if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
        Toast.makeText(this, "landscape", Toast.LENGTH_SHORT).show();
    } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
        Toast.makeText(this, "portrait", Toast.LENGTH_SHORT).show();
    }
}

AndroidManifest.xml

<activity android:name=".MyActivity"
          android:configChanges="orientation|keyboardHidden"
          android:label="@string/app_name">

References
https://stackoverflow.com/questions/2795833/check-orientation-on-android-phone
https://stackoverflow.com/questions/5726657/how-to-detect-orientation-change-in-layout-in-android

Show fullscreen Video on Android

final View decorView = getWindow().getDecorView();
            decorView.setOnSystemUiVisibilityChangeListener (new View.OnSystemUiVisibilityChangeListener() {
            @Override
            public void onSystemUiVisibilityChange(int visibility) {
                if ((visibility & View.SYSTEM_UI_FLAG_FULLSCREEN) == 0) {
                    decorView.setSystemUiVisibility(
                            View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                            | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                            | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                            | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                            | View.SYSTEM_UI_FLAG_FULLSCREEN
                            | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
                }
            }
        });

References
https://pupli.net/2017/08/03/create-fullscreen-activity-in-android/
https://stackoverflow.com/questions/21164836/immersive-mode-navigation-becomes-sticky-after-volume-press-or-minimise-restore

Save state of activity when orientation changes on android

private TextView mTextView;
private static final String KEY_TEXT_VALUE = "textValue";

@Override
protected void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   mTextView = (TextView) findViewById(R.id.main);
   if (savedInstanceState != null) {
      CharSequence savedText = savedInstanceState.getCharSequence(KEY_TEXT_VALUE);
      mTextView.setText(savedText);
   }
}

@Override
protected void onSaveInstanceState (Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.putCharSequence(KEY_TEXT_VALUE, mTextView.getText());
}

References
https://stackoverflow.com/questions/13022677/save-state-of-activity-when-orientation-changes-android

Play Video in VideoView on Android

<VideoView
  android:id="@+id/videoView"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
   />
Uri uri = Uri.parse(URL); //Declare your url here.

VideoView mVideoView  = (VideoView)findViewById(R.id.videoview)
mVideoView.setMediaController(new MediaController(this));       
mVideoView.setVideoURI(uri);
mVideoView.requestFocus();
mVideoView.start();

Or

String LINK = "type_here_the_link";
  VideoView mVideoView  = (VideoView) findViewById(R.id.videoview);
  MediaController mc = new MediaController(this);
  mc.setAnchorView(videoView);
  mc.setMediaPlayer(videoView);
  Uri video = Uri.parse(LINK);
  mVideoView.setMediaController(mc);
  mVideoView.setVideoURI(video);
  mVideoView.start();

References
https://stackoverflow.com/questions/10461119/playing-a-video-in-android
https://stackoverflow.com/questions/17399351/how-to-play-mp4-video-in-videoview-in-android