Professional Documents
Culture Documents
Mad Practical
Mad Practical
Mad Practical
INDEX
Sr
Topic PAGE DATE REMARKS SIGN
.
NO.
No
calculator.java
package com.example.calculator;
import
androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import org.mozilla.javascript.Context;
import org.mozilla.javascript.Scriptable;
import org.mozilla.javascript.ast.Scope;
public class calculator extends AppCompatActivity
{ Button
btn0,btn1,btn2,btn3,btn4,btn5,btn6,btn7,btn8,btn9,b
tncl,btnpa,btndi,btnx,btnsu,btnadd,btnans,btnbr,btn
do;
TextView tvinput,tvoutput;
String process;
boolean checkBracket;
@Override
protected void
onCreate(Bundle
savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.calculator);
btn0=findViewById(R.id.btn0);
btn1=findViewById(R.id.btn1);
btn2=findViewById(R.id.btn2);
btn3=findViewById(R.id.btn3);
btn4=findViewById(R.id.btn4);
btn5=findViewById(R.id.btn5);
btn6=findViewById(R.id.btn6);
btn7=findViewById(R.id.btn7);
btn8=findViewById(R.id.btn8);
btn9=findViewById(R.id.btn9);
btnadd=findViewById(R.id.btnadd);
btnsu=findViewById(R.id.btnsu);
btnx=findViewById(R.id.btnx);
btndi=findViewById(R.id.btndi);
btnpa=findViewById(R.id.btnpa);
btnbr=findViewById(R.id.btnbr);
btnans=findViewById(R.id.btnans);
btncl=findViewById(R.id.btncl);
btndo=findViewById(R.id.btndo);
tvinput=findViewById(R.id.tvinput);
tvoutput=findViewById(R.id.tvoutput);
btncl.setOnClickListener(new
View.OnClickListener() {
@Override
public void onClick(View v)
{ tvinput.setText("");
tvoutput.setText("");
}
});
btn0.setOnClickListener(new
View.OnClickListener() {
public void onClick(View v) {
process=tvinput.getText().toString();
tvinput.setText(process+"0");
}
});
btn1.setOnClickListener(new
View.OnClickListener() {
@Override
public void onClick(View v) {
process=tvinput.getText().toString();
tvinput.setText(process+"1");
}
});
btn2.setOnClickListener(new
View.OnClickListener() {
@Override
public void onClick(View v) {
process=tvinput.getText().toString();
tvinput.setText(process+"2");
}
});
btn3.setOnClickListener(new
View.OnClickListener() {
@Override
public void onClick(View v) {
process=tvinput.getText().toString();
tvinput.setText(process+"3");
}
});
btn4.setOnClickListener(new
View.OnClickListener() {
@Override
public void onClick(View v) {
process=tvinput.getText().toString();
tvinput.setText(process+"4");
}
});
btn5.setOnClickListener(new
View.OnClickListener() {
@Override
public void onClick(View v) {
process=tvinput.getText().toString();
tvinput.setText(process+"5");
}
});
btn6.setOnClickListener(new
View.OnClickListener() {
@Override
public void onClick(View v) {
process=tvinput.getText().toString();
tvinput.setText(process+"6");
}
});
btn7.setOnClickListener(new
View.OnClickListener() {
@Override
public void onClick(View v) {
process=tvinput.getText().toString();
tvinput.setText(process+"7");
}
});
btn8.setOnClickListener(new
View.OnClickListener() {
@Override
public void onClick(View v) {
process=tvinput.getText().toString();
tvinput.setText(process+"8");
}
});
btn9.setOnClickListener(new
View.OnClickListener() {
@Override
public void onClick(View v) {
process=tvinput.getText().toString();
tvinput.setText(process+"9");
}
});
btnadd.setOnClickListener(new
View.OnClickListener() {
@Override
public void onClick(View v) {
process=tvinput.getText().toString();
tvinput.setText(process+"+");
}
});
btnsu.setOnClickListener(new
View.OnClickListener() {
@Override
public void onClick(View v) {
process=tvinput.getText().toString();
tvinput.setText(process+"-");
}
});
btnx.setOnClickListener(new
View.OnClickListener() {
@Override
public void onClick(View v) {
process=tvinput.getText().toString();
tvinput.setText(process+"x");
}
});
btndi.setOnClickListener(new
View.OnClickListener() {
@Override
public void onClick(View v) {
process=tvinput.getText().toString();
tvinput.setText(process+"/");
}
});
btnpa.setOnClickListener(new
View.OnClickListener() {
@Override
public void onClick(View v) {
process=tvinput.getText().toString();
tvinput.setText(process+"%");
}
});
btndo.setOnClickListener(new
View.OnClickListener() {
@Override
public void onClick(View v) {
process=tvinput.getText().toString();
tvinput.setText(process+".");
}
});
btnbr.setOnClickListener(new
View.OnClickListener() {
@Override
public void onClick(View v)
{ if (checkBracket){
process=tvinput.getText().toString();
tvinput.setText(process+")");
checkBracket=false;
}else {
process=tvinput.getText().toString();
tvinput.setText(process+"(");
checkBracket=true;
}
}
});
btnans.setOnClickListener(new
View.OnClickListener() {
@Override
public void onClick(View v)
{ process=tvinput.getText().toString();
process=process.replaceAll("x","*");
process=process.replaceAll("%","/100");
Context rhino =
Context.enter();
rhino.setOptimizationLevel(-1);
String finalResult="";
try {
Scriptable scriptable
=rhino.initStandardObjects();
finalResult=rhino.evaluateString(scriptable,process
,"javascript",1,null).toString();
}catch (Exception e)
{ finalResult="0
";
}
tvoutput.setText(finalResult);
}
});
}
}
calculator.xml
inputlayout.xml
<TextView
android:id="@+id/tvinput"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text=""
android:gravity="end"
android:background="@color/black"
android:textSize="30sp"
android:padding="10dp"
android:textColor="@color/white"
/>
<TextView
android:id="@+id/tvoutput"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text=""
android:textSize="50sp"
android:gravity="end"
android:padding="10dp"
android:background="@color/black"
android:textColor="@color/white"
/>
</LinearLayout>
button.xml
<GridLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:rowCount="5"
android:columnCount="6">
<Button
android:id="@+id/btncl"
android:layout_width="wrap_content"
android:layout_height="100dp"
android:text="AC"
android:textStyle="bold"
android:textSize="25sp"
android:textColor="#F44336"
android:background="@color/black"
android:layout_row="0"
android:layout_column="0"
android:layout_columnWeight="1"/>
<Button
android:id="@+id/btnbr"
android:layout_width="wrap_content"
android:layout_height="100dp"
android:text="()"
android:textSize="25sp"
android:textColor="@color/white"
android:background="@color/black"
android:layout_row="0"
android:layout_column="1"
android:layout_columnWeight="1"/>
<Button
android:id="@+id/btnpa"
android:layout_width="wrap_content"
android:layout_height="100dp"
android:text="%"
android:textSize="25sp"
android:textColor="@color/white"
android:background="@color/black"
android:layout_row="0"
android:layout_column="2"
android:layout_columnWeight="1"/>
<Button
android:id="@+id/btndi"
android:layout_width="wrap_content"
android:layout_height="100dp"
android:text="/"
android:textSize="25sp"
android:textColor="@color/white"
android:background="@color/black"
android:layout_row="0"
android:layout_column="3"
android:layout_columnWeight="1"/>
<Button
android:id="@+id/btn7"
android:layout_width="wrap_content"
android:layout_height="100dp"
android:text="7"
android:textSize="25sp"
android:textColor="@color/white"
android:background="@color/black"
android:layout_row="1"
android:layout_column="0"
android:layout_columnWeight="1"/>
<Button
android:id="@+id/btn8"
android:layout_width="wrap_content"
android:layout_height="100dp"
android:text="8"
android:textSize="25sp"
android:textColor="@color/white"
android:background="@color/black"
android:layout_row="1"
android:layout_column="1"
android:layout_columnWeight="1"/>
<Button
android:id="@+id/btn9"
android:layout_width="wrap_content"
android:layout_height="100dp"
android:text="9"
android:textSize="25sp"
android:textColor="@color/white"
android:background="@color/black"
android:layout_row="1"
android:layout_column="2"
android:layout_columnWeight="1"/>
<Button
android:id="@+id/btnx"
android:layout_width="wrap_content"
android:layout_height="100dp"
android:text="X"
android:textSize="25sp"
android:textColor="@color/white"
android:background="@color/black"
android:layout_row="1"
android:layout_column="3"
android:layout_columnWeight="1"/>
<Button
android:id="@+id/btn4"
android:layout_width="wrap_content"
android:layout_height="100dp"
android:text="4"
android:textSize="25sp"
android:textColor="@color/white"
android:background="@color/black"
android:layout_row="2"
android:layout_column="0"
android:layout_columnWeight="1"/>
<Button
android:id="@+id/btn5"
android:layout_width="wrap_content"
android:layout_height="100dp"
android:text="5"
android:textSize="25sp"
android:textColor="@color/white"
android:background="@color/black"
android:layout_row="2"
android:layout_column="1"
android:layout_columnWeight="1"/>
<Button
android:id="@+id/btn6"
android:layout_width="wrap_content"
android:layout_height="100dp"
android:text="6"
android:textSize="25sp"
android:textColor="@color/white"
android:background="@color/black"
android:layout_row="2"
android:layout_column="2"
android:layout_columnWeight="1"/>
<Button
android:id="@+id/btnsu"
android:layout_width="wrap_content"
android:layout_height="100dp"
android:text="_"
android:textSize="25sp"
android:textColor="@color/white"
android:background="@color/black"
android:layout_row="2"
android:layout_column="3"
android:layout_columnWeight="1"/>
<Button
android:id="@+id/btn1"
android:layout_width="wrap_content"
android:layout_height="100dp"
android:text="1"
android:textSize="25sp"
android:textColor="@color/white"
android:background="@color/black"
android:layout_row="3"
android:layout_column="0"
android:layout_columnWeight="1"/>
<Button
android:id="@+id/btn2"
android:layout_width="wrap_content"
android:layout_height="100dp"
android:text="2"
android:textSize="25sp"
android:textColor="@color/white"
android:background="@color/black"
android:layout_row="3"
android:layout_column="1"
android:layout_columnWeight="1"/>
<Button
android:id="@+id/btn3"
android:layout_width="wrap_content"
android:layout_height="100dp"
android:text="3"
android:textSize="25sp"
android:textColor="@color/white"
android:background="@color/black"
android:layout_row="3"
android:layout_column="2"
android:layout_columnWeight="1"/>
<Button
android:id="@+id/btnadd"
android:layout_width="wrap_content"
android:layout_height="100dp"
android:text="+"
android:textSize="25sp"
android:textColor="@color/white"
android:background="@color/black"
android:layout_row="3"
android:layout_column="3"
android:layout_columnWeight="1"/>
<Button
android:id="@+id/btn0"
android:layout_width="wrap_content"
android:layout_height="100dp"
android:text="0"
android:textSize="25sp"
android:textColor="@color/white"
android:background="@color/black"
android:layout_row="4"
android:layout_column="0"
android:layout_columnWeight="1"/>
<Button
android:id="@+id/btndo"
android:layout_width="wrap_content"
android:layout_height="100dp"
android:text="."
android:textSize="25sp"
android:textColor="@color/white"
android:background="@color/black"
android:layout_row="4"
android:layout_columnSpan="2"
android:layout_column="1"
android:layout_columnWeight="1"/>
<Button
android:id="@+id/btnans"
android:layout_width="wrap_content"
android:layout_height="100dp"
android:text="="
android:textSize="25sp"
android:textColor="@color/white"
android:background="@color/orange"
android:layout_row="4"
android:layout_column="3"
android:layout_columnWeight="1"/>
</GridLayout>
</RelativeLayout>
Output
2. Write an Android application to convert into different currencies for example, Rupees to dollar.
CurrencyActivity.java
package com.example.currencyconverter;
import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle;
import android.view.View; import android.widget.Button; import android.widget.EditText; import android.wi
public class CurrencyActivity extends AppCompatActivity { Button btnConvert;
TextView txtResult;
@Override
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(
btnConvert = findViewById(R.id.button);
txtResult = findViewById(R.id.txtResult);
activity_currency.xml
<TextView
android:id="@+id/textviewname"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Currency Converter"
android:textSize="40sp"
android:layout_marginTop="45dp"
android:gravity="center"/>
<TextView
android:id="@+id/textview"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Enter Currency in rupees"
android:textSize="20sp"
android:layout_marginTop="25dp"
android:layout_below="@+id/textviewname"/>
<EditText
android:id="@+id/edtText"
android:layout_below="@+id/textview"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="number"
android:hint="Enter Rupee"/>
<Button
android:id="@+id/button"
android:layout_below="@+id/edtText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:layout_centerHorizontal="true"
android:text="CONVERT"
android:textSize="20sp"
/>
<TextView
android:layout_below="@+id/button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:id="@+id/txtResult"
android:text="Converted Amount:"
android:textSize="20sp"/>
</RelativeLayout>
Output
3. Write an android application to count library overdue.
Output
4. Write an android application to convert a ball from size of radius 2(colour red) to radius
4(colour blue)to radius 6 (colour green). The ball must rotate in circle for 1 minute before changing
size and colour.
RotateActivity.Java
package com.example.rotatingball;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.LinearInterpolator;
import android.view.animation.RotateAnimation;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import java.util.Timer;
import java.util.TimerTask;
{ private int i = 1;
CustomView customView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_rotate);
RelativeLayout relativeLayout = (RelativeLayout)
findViewById(R.id.rootView);
customView = new CustomView(this);
relativeLayout.addView(customView);
//relativeLayout.setBackgroundColor(Color.BLACK);
setContentView(relativeLayout);
startViewAnimation();
Animation rotation = new RotateAnimation(0,
360, Animation.RELATIVE_TO_SELF, .5f,
Animation.RELATIVE_TO_SELF, .5f);
} i=i+30;
});
} else {
i = 0;
}
}
}, 0, 1500); // change '500' to milliseconds for how frequent you want to
update radius
}
@Override
protected void onDraw(Canvas canvas) {
//super.onDraw(canvas);
//////////
Display display = getWindowManager().getDefaultDisplay();
int width =
display.getHeight(); int height
= display.getWidth();
Bitmap bitmap = Bitmap.createBitmap(width, height/3,
Bitmap.Config.ARGB_4444);
}
}
}
activity_rotate.xml
</RelativeLayout>
Output
5. Write an application to mark the daily route of travel in map.
AndroidManifest.xml
<!--
The ACCESS_COARSE/FINE_LOCATION permissions are not required to use
Google Maps Android API v2, but you must specify either coarse or fine
location permissions for the "MyLocation" functionality.
-->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
<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/Theme.EnrouteApp">
<!--
The API key for Google Maps-based APIs is defined as a string
resource.
(See the file "res/values/google_maps_api.xml").
Note that the API key is linked to the encryption key used to sign
the APK.
You need a different API key for each encryption key, including the
release key that is used to
sign the APK for publishing.
You can define the keys for the debug and release targets in
src/debug/ and src/release/.
-->
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="@string/google_maps_key" />
<activity
android:name=".MapsActivity2"
android:label="@string/title_activity_maps2"></activity>
<activity android:name=".MapsActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
</manifest>
MapsActivity.java
package com.example.enrouteapp;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import androidx.fragment.app.FragmentActivity;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.PolylineOptions;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
@Override
protected void onCreate(Bundle savedInstanceState)
{ super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to
be used.
SupportMapFragment mapFragment = (SupportMapFragment)
getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera.
In this case,
* we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user will
be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once
the user has
* installed Google Play services and returned to the app.
*/
@Override
public void onMapReady(GoogleMap googleMap)
{ mMap = googleMap;
LatLng sydney = new LatLng(-34, 151);
//mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in
Sydney"));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(sydney, 16));
mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
@Override
public void onMapClick(LatLng latLng) {
if (markerPoints.size() > 1)
{ markerPoints.clear();
mMap.clear();
}
// Creating MarkerOptions
MarkerOptions options = new MarkerOptions();
if (markerPoints.size() == 1) {
options.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREE
N));
} else if (markerPoints.size() == 2) {
options.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED)
);
}
DownloadTask();
}
});
}
private class DownloadTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... url)
try {
data = downloadUrl(url[0]);
} catch (Exception e) {
Log.d("Background Task", e.toString());
}
return data;
}
@Override
protected void onPostExecute(String result)
{ super.onPostExecute(result);
parserTask.execute(result);
}
}
/**
* A class to parse the Google Places in JSON format
*/
private class ParserTask extends AsyncTask<String,
Integer, List<List<HashMap<String, String>>>> {
JSONObject jObject;
List<List<HashMap<String, String>>> routes =
null; try {
routes = parser.parse(jObject);
Log.e("DS",""+routes.toString());
} catch (Exception e) {
e.printStackTrace();
}
return routes;
}
@Override
protected void onPostExecute(List<List<HashMap<String, String>>> result) {
ArrayList points = null;
PolylineOptions lineOptions = null;
MarkerOptions markerOptions = new MarkerOptions();
for (int i = 0; i < result.size(); i++)
{ points = new ArrayList();
lineOptions = new PolylineOptions();
+) {
HashMap<String, String> point = path.get(j);
double lat =
Double.parseDouble(point.get("lat")); double lng
= Double.parseDouble(point.get("lng")); LatLng
position = new LatLng(lat, lng);
points.add(position);
}
lineOptions.addAll(points);
lineOptions.width(12);
lineOptions.color(Color.RED);
lineOptions.geodesic(true);
// Origin of route
String str_origin = "origin=" + origin.latitude + "," + origin.longitude;
// Destination of route
String str_dest = "destination=" + dest.latitude + "," + dest.longitude;
// Sensor enabled
String sensor =
"sensor=false"; String mode =
"mode=driving";
// Building the parameters to the web service
mode; String parameters = str_origin + "&" + str_dest + "&" + sensor + "&" +
// Output format
String output = "json";
Log.e("DS","url "+url);
return url;
/**
* A method to download json data from url
*/
private String downloadUrl(String strUrl) throws IOException {
String data = "";
InputStream iStream = null; HttpURLConnection urlConnection = null; try {
URL url = new URL(strUrl);
}
}
activity_maps.xml
Output
6. Write an application to record video and audio on topic “Intent” and play the audio and video.
BuildingMusicPlayerActivity.java
package com.example.mymediaplayer;
import android.Manifest;
import android.annotation.SuppressLint; import android.app.Activity;
import android.content.DialogInterface; import android.content.Intent;
import android.content.pm.PackageManager;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.ImageButton;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.core.app.ActivityCompat;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Random;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState)
{ super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// All player buttons
btnPlay = (ImageButton) findViewById(R.id.btnPlay);
btnForward = (ImageButton) findViewById(R.id.btnForward);
btnBackward = (ImageButton) findViewById(R.id.btnBackward);
btnNext = (ImageButton) findViewById(R.id.btnNext);
btnPrevious = (ImageButton) findViewById(R.id.btnPrevious);
btnPlaylist = (ImageButton) findViewById(R.id.btnPlaylist);
btnRepeat = (ImageButton) findViewById(R.id.btnRepeat);
btnShuffle = (ImageButton) findViewById(R.id.btnShuffle);
songProgressBar = (SeekBar) findViewById(R.id.songProgressBar);
songTitleLabel = (TextView) findViewById(R.id.songTitle);
songCurrentDurationLabel = (TextView)
findViewById(R.id.songCurrentDurationLabel);
songTotalDurationLabel = (TextView)
findViewById(R.id.songTotalDurationLabel);
AndroidRuntimePermission();
// Mediaplayer
mp = new MediaPlayer();
songManager = new SongsManager(AndroidBuildingMusicPlayerActivity.this);
utils = new Utilities();
// Listeners
songProgressBar.setOnSeekBarChangeListener(this); //
Important mp.setOnCompletionListener(this); // Important
btnPlaylist.setOnClickListener(new View.OnClickListener()
@Override
public void onClick(View arg0) {
Intent i = new
Intent(getApplicationContext(), PlayListActivity.class);
startActivityForResult(i, 100);
}
});
/**
* Forward button click event
* Forwards song specified seconds
**/
btnForward.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
// get current song position
int currentPosition = mp.getCurrentPosition();
// check if seekForward time is lesser than song duration
if(currentPosition + seekForwardTime <= mp.getDuration()){
// forward song
mp.seekTo(currentPosition + seekForwardTime);
}else{
// forward to end position
mp.seekTo(mp.getDuration());
}
}
});
/**
* Backward button click event
* Backward song to specified seconds
* */
btnBackward.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
// get current song position
int currentPosition = mp.getCurrentPosition();
// check if seekBackward time is greater than 0 sec
if(currentPosition - seekBackwardTime >= 0){
// forward song
mp.seekTo(currentPosition - seekBackwardTime);
}else{
// backward to starting position
mp.seekTo(0);
}
}
});
/**
* Next button click event
* Plays next song by taking currentSongIndex + 1
* */
btnNext.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
// check if next song is there or not
if(currentSongIndex < (songsList.size() - 1))
{ playSong(currentSongIndex + 1);
currentSongIndex = currentSongIndex + 1;
}else{
// play first song
playSong(0);
currentSongIndex =
0;
}
}
});
/**
* Back button click event
* Plays previous song by currentSongIndex - 1
* */
btnPrevious.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0)
{ if(currentSongIndex > 0){
playSong(currentSongIndex - 1);
currentSongIndex = currentSongIndex -
1;
}else{
// play last song
playSong(songsList.size() - 1);
currentSongIndex = songsList.size() -
1;
}
}
});
/**
* Button Click event for Repeat button
* Enables repeat flag to true
* */
btnRepeat.setOnClickListener(new View.OnClickListener() {
@SuppressLint("ResourceAsColor")
@Override
public void onClick(View arg0)
{ if(isRepeat){
isRepeat = false;
Toast.makeText(getApplicationContext(), "Repeat is OFF",
Toast.LENGTH_SHORT).show();
btnRepeat.setImageResource(R.drawable.repeat);
}else{
// make repeat to true
isRepeat = true;
Toast.makeText(getApplicationContext(), "Repeat is ON",
Toast.LENGTH_SHORT).show();
// make shuffle to false
isShuffle = false;
//btnRepeat.setImageResource(R.drawable.btn_repeat_focused);
btnShuffle.setImageResource(R.drawable.shuffle);
}
}
});
/**
* Button Click event for Shuffle button
* Enables shuffle flag to true
* */
btnShuffle.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0)
{ if(isShuffle){
isShuffle = false;
Toast.makeText(getApplicationContext(), "Shuffle is OFF",
Toast.LENGTH_SHORT).show();
btnShuffle.setImageResource(R.drawable.shuffle);
}else{
// make repeat to true
isShuffle= true;
Toast.makeText(getApplicationContext(), "Shuffle is ON",
Toast.LENGTH_SHORT).show();
// make shuffle to false
isRepeat = false;
//btnShuffle.setImageResource(R.drawable.btn_shuffle_focused);
btnRepeat.setImageResource(R.drawable.repeat);
}
}
});
btnPlay.setOnClickListener(new View.OnClickListener()
{ @Override
public void onClick(View v) {
if(!isPlaying){
playSong(0);
isPlaying =
true;
Log.v("DS","is playing false");
int currentPosition = mp.getCurrentPosition();
}
else if(isPlaying){
mp.stop();
isPlaying =
false;
btnPlay.setImageResource(R.drawable.play);
Log.v("DS","is playing true");
}
}
});
}
/**
* On Song Playing completed
* if repeat is ON play same song again
* if shuffle is ON play random song
* */
@Override
public void onCompletion(MediaPlayer arg0) {
/**
* Receiving song index from playlist view
* and play the song
* */
@Override
protected void onActivityResult(int requestCode,
int resultCode, Intent data)
{ super.onActivityResult(requestCode, resultCode, data);
if(resultCode == 100){
currentSongIndex = data.getExtras().getInt("songIndex");
// play selected song
playSong(currentSongIndex);
}
}
/**
* Update timer on seekbar
* */
public void updateProgressBar() {
mHandler.postDelayed(mUpdateTimeTask, 100);
}
/**
*
* */
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromTouch)
{
/**
* When user starts moving the progress handler
* */
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
// remove message Handler from updating progress bar
mHandler.removeCallbacks(mUpdateTimeTask);
}
/**
* When user stops moving the progress hanlder
* */
@Override
public void onStopTrackingTouch(SeekBar seekBar)
{ mHandler.removeCallbacks(mUpdateTimeTask);
int totalDuration = mp.getDuration();
int currentPosition = utils.progressToTimer(seekBar.getProgress(),
totalDuration);
/**
* Background Runnable thread
* */
private Runnable mUpdateTimeTask = new Runnable()
{ public void run() {
long totalDuration = mp.getDuration();
long currentDuration = mp.getCurrentPosition();
songTotalDurationLabel.setText(""+utils.milliSecondsToTimer(totalDuration));
// Displaying time completed playing
songCurrentDurationLabel.setText(""+utils.milliSecondsToTimer(currentDuration));
// Updating progress bar
int progress = (int)(utils.getProgressPercentage(currentDuration,
totalDuration));
//Log.d("Progress", ""+progress);
songProgressBar.setProgress(progress);
/**
* Function to play a song
* @param songIndex - index of song
* */
public void playSong(int songIndex){
// Play song
try {
mp.reset();
mp.setDataSource(songsList.get(songIndex).get("songPath"));
mp.prepare();
mp.start();
// Displaying Song title
String songTitle = songsList.get(songIndex).get("songTitle");
songTitleLabel.setText(songTitle);
if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.M){
if(checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE)!=
PackageManager.PERMISSION_GRANTED){
if(shouldShowRequestPermissionRationale(Manifest.permission.READ_EXTERNAL_STORAGE))
{
@Override
public void onClick(DialogInterface dialogInterface, int i)
{
ActivityCompat.requestPermissions( AndroidBuild
ingMusicPlayerActivity.this, new
String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
RUNTIME_PERMISSION_CODE
);
}
});
alert_builder.setNeutralButton("Cancel",null);
dialog.show();
}
else {
ActivityCompat.requestPermissions( AndroidBuild
ingMusicPlayerActivity.this, new
String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
RUNTIME_PERMISSION_CODE
);
}
}else {
}
}
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions,
int[] grantResults){
switch(requestCode){
case RUNTIME_PERMISSION_CODE:{
}
else {
}
}
}
}
}
VideoRecorder.java
package com.example.mymediaplayer;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.hardware.Camera;
import android.media.CamcorderProfile;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.Toast;
import android.hardware.Camera.CameraInfo;
import java.io.IOException;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_video_recorder);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
myContext = this;
initialize();
//chooseCamera();
prepareMediaRecorder();
capture.setOnClickListener(new View.OnClickListener()
{ @Override
public void onClick(View v) {
if (recording) {
// stop recording and release camera
mediaRecorder.stop(); // stop the recording
releaseMediaRecorder(); // release the MediaRecorder
object Toast.makeText(VideoRecorder.this, "Video
captured!",
Toast.LENGTH_LONG).show();
recording = false;
} else {
if (!prepareMediaRecorder()) {
Toast.makeText(VideoRecorder.this, "Fail in
prepareMediaRecorder()!\n - Ended -", Toast.LENGTH_LONG).show();
finish();
}
// work on UiThread for better performance
runOnUiThread(new Runnable()
{ public void run() {
// If there are stories, add them to the table
try {
mediaRecorder.start();
} catch (final Exception ex) {
// Log.i("---","Exception in thread");
}
}
});
recording = true;
}
}
});
capture = findViewById(R.id.button_capture);
switchCamera = findViewById(R.id.button_ChangeCamera);
releaseCamera();
chooseCamera();
} else {
Toast toast = Toast.makeText(myContext, "Sorry, your phone has only
one camera!", Toast.LENGTH_LONG);
toast.show();
}
}
}
mCamera = Camera.open(cameraId);
// mPicture = getPictureCallback();
mPreview = new CameraPreview(VideoRecorder.this,mCamera);
mPreview.refreshCamera(mCamera);
}
} else
{
int cameraId =
findFrontFacingCamera(); if (cameraId
>= 0) {
// open the backFacingCamera
// set a picture callback
// refresh the preview
mCamera = Camera.open(cameraId);
// mPicture = getPictureCallback();
mPreview = new CameraPreview(VideoRecorder.this,mCamera);
mPreview.refreshCamera(mCamera);
}
}
}
@Override
protected void onPause()
{ super.onPause();
// when on Pause, release camera in order to be used from other
// applications
releaseCamera();
}
private boolean hasCamera(Context context) {
// check if the device has camera
if
(context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA))
{
return true;
} else {
return false;
}
}
try {
mediaRecorder.start();
} catch (final Exception ex) {
// Log.i("---","Exception in thread");
}
}
});
recording = true;
}*/
}
};
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER); mediaRecorder.setVideoSource(Medi
mediaRecorder.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_720P));
try {
mediaRecorder.prepare();
} catch (IllegalStateException e) { releaseMediaRecorder();
return false;
} catch (IOException e) { releaseMediaRecorder(); return false;
}
return true;
VideoActivity.java
package com.example.mymediaplayer;
import androidx.appcompat.app.AppCompatActivity; import android.net.Uri;
import android.os.Bundle;
import android.widget.MediaController; import android.widget.VideoView;
public class VideoActivity extends AppCompatActivity { @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); setContentView(R.layout.activity_video);
VideoStreaming.java
package com.example.mymediaplayer;
import androidx.appcompat.app.AppCompatActivity;
import android.app.ProgressDialog;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.widget.MediaController;
import android.widget.VideoView;
import java.io.FileNotFoundException;
// Declare variables
ProgressDialog pDialog;
VideoView videoview;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_video_streaming);
// Create a progressbar
pDialog = new ProgressDialog(VideoStreaming.this);
// Set progressbar title
pDialog.setTitle("Android Video Streaming Tutorial");
// Set progressbar message
pDialog.setMessage("Buffering...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
// Show progressbar
pDialog.show();
try {
// Start the MediaController
MediaController mediacontroller = new MediaController( VideoStreaming.this);
mediacontroller.setAnchorView(videoview);
// Get the URL from String VideoURL
Uri video = Uri.parse(VideoURL); videoview.setMediaController(mediacontroller); videoview.setVideo
videoview.requestFocus();
videoview.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
// Close the progress bar and play the video
public void onPrepared(MediaPlayer mp) { pDialog.dismiss(); videoview.start();
}
});
}
}
PlayListActivity.java
package com.example.mymediaplayer;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import java.util.ArrayList;
import java.util.HashMap;
// Songs list
public ArrayList<HashMap<String, String>> songsList =
new ArrayList<HashMap<String, String>>();
@Override
public void onCreate(Bundle savedInstanceState)
{ super.onCreate(savedInstanceState);
setContentView(R.layout.playlist);
setListAdapter(adapter);
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting listitem index
int songIndex position;
=
intent
// Starting Intent(getApplicationContext(),
new
Intent in =
new
AndroidBuildingMusicPlayerActivity.class);
// Sending songIndex to
PlayerActivity
in.putExtra("songIndex", songIndex);
setResult(100, in);
// Closing PlayListView
} finish();
});
}
}