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

Parse JSON file with GSON

Gson gson = new Gson();
JsonReader reader = new JsonReader(new FileReader(filename));
List<Review> data = gson.fromJson(reader, REVIEW_TYPE);

Or

Write

String filename = "myfile.txt";

Vector v = new Vector(10.0f, 20.0f);
Gson gson = new Gson();
String s = gson.toJson(v);

FileOutputStream outputStream;

try {
  outputStream = openFileOutput(filename, Context.MODE_PRIVATE);
  outputStream.write(s.getBytes());
  outputStream.close();
} catch (Exception e) {
  e.printStackTrace();
}

Read

FileInputStream fis = context.openFileInput("myfile.txt", Context.MODE_PRIVATE);
 InputStreamReader isr = new InputStreamReader(fis);
 BufferedReader bufferedReader = new BufferedReader(isr);
 StringBuilder sb = new StringBuilder();
 String line;
 while ((line = bufferedReader.readLine()) != null) {
     sb.append(line);
 }

 String json = sb.toString();
 Gson gson = new Gson();
 Vector v = gson.fromJson(json, Vector.class);

References
https://stackoverflow.com/questions/29965764/how-to-parse-json-file-with-gson
https://stackoverflow.com/questions/19459082/read-and-write-data-with-gson