Mad Practical

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 45

GYANMANJARI INSTITUTE OF TECHNOLOGY MAD- 3161612

INDEX

Sr
Topic PAGE DATE REMARKS SIGN
.
NO.
No

1 Write an Android application


for calculator.

Write an Android application to


2 convert into different currencies for
example, Rupees to dollar.

3 Write an android application to


count library overdue.

Write an android application to convert


a ball from size of radius 2(colour red)
4 to radius 4(colour blue) to radius 6
(colour green). The ball must rotate in
circle for 1 minute before changing size
and colour.

5 Write an application to mark the


daily route of travel in map.

Write an application to record video


6 and audio on topic “Intent” and play
the audio and video.
1. Write an Android application for calculator.

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

<?xml version="1.0" encoding="utf-8"?>


<LinearLayout xmlns:android=""
xmlns:app="" xmlns:tools="" android:id="@+id/relative1" android:layout_width="match_parent" android:layout_
<include
layout="@layout/input_layout" android:layout_width="match_parent" android:layout_marginTop="10dp" android:l
<RelativeLayout android:layout_width="match_parent" android:gravity="bottom" android:background="@color/bla
<include
android:layout_width="match_parent" android:layout_height="wrap_content" layout="@layout/button"/>
</RelativeLayout>

inputlayout.xml

<?xml version="1.0" encoding="utf-8"?>


<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/black"
android:gravity="end"
android:orientation="vertical">

<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

<?xml version="1.0" encoding="utf-8"?>


<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">

<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);

btnConvert.setOnClickListener(new View.OnClickListener() { @Override


public void onClick(View v) { convertToEuro();
}
});
}

public void convertToEuro(){


EditText editText = (EditText) findViewById(R.id.edtText); int rupee = Integer.parseInt(editText.getT
double result = dollars * rupee ;
txtResult.setText("Converted Amount: "+Double.toString(result));
// Toast.makeText(CurrencyActivity.this, Double.toString(result), Toast.LENGTH_LONG).show();
}
}

activity_currency.xml

<?xml version="1.0" encoding="utf-8"?>


<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:padding="25dp">

<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.

<?xml version="1.0" encoding="utf-8"?>


<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<LinearLayout
android:id="@+id/idLLsearch"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:weightSum="5">
<EditText
android:id="@+id/idEdtSearchBooks"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="4" />
<ImageButton
android:id="@+id/idBtnSearch"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:src="@drawable/ic_search" />
</LinearLayout>
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/idRVBooks"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="@id/idLLsearch" />
<ProgressBar
android:id="@+id/idLoadingPB"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:visibility="gone" />
</RelativeLayout>

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;

public class RotateActivity extends AppCompatActivity

{ 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);

//Animation rotation = new RotateAnimation(0,


360); rotation.setInterpolator(new
LinearInterpolator());
rotation.setRepeatCount(Animation.INFINITE);
rotation.setDuration(2000);
rotation.setFillAfter(true);
relativeLayout.startAnimation(rotation);
}

public void startViewAnimation() {


final Timer timer = new
Timer();
timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
if (i < 70) { // Please change '70' according to how long you want
to go
runOnUiThread(new Runnable()
{ @Override
public void run() {
//int baseRadius=30; // base radius is basic radius of
circle from which to start animation
//customView.updateView(i+baseRadius);

//897 1080 224 540


int basex1 = 897;
int basey1 =
1080; int basex2
= 224; int basey2
= 540;
i+basey2); customView.updateView(basex1-i,basey1-i, i+basex2,

} i=i+30;
});
} else {

i = 0;
}
}
}, 0, 1500); // change '500' to milliseconds for how frequent you want to
update radius
}

public class CustomView extends View


{ Paint paint;
int x1, x2, y1, y2 = 0;
//int radius = 0;

public CustomView(Context context)


{ super(context);
init();
}

private void init() {


paint = new
Paint();
paint.setStyle(Paint.Style.STROKE);
paint.setColor(Color.RED);
paint.setAntiAlias(true);
paint.setStrokeWidth(5f);
}
public void updateView(int x1, int y1, int x2, int y2)
{ this.x1 = x1;
this.y1 =
y1; this.x2
= x2;
this.y2 =
y2;
invalidate();
}

@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);

canvas.drawColor(Color.WHITE); Paint paint = new Paint();


//Log.v("DS",""+x1+" "+y1+" "+x2+" "+y2);

// 856 1039 265 581

// 836 1019 285 601


// 897 1080 224 540
// 877 1060 244 560
if (x1 >= 836 && x1<856) {
paint.setColor(Color.RED);
}
if(x1 >= 856 && x1 < 877){ paint.setColor(Color.BLUE);
}
if(x1 >=877 ){
paint.setColor(Color.GREEN);
}
///////////////
// canvas.drawCircle(width / 2, height * 6, radius, paint);
//canvas.drawCircle(width/2 , height/2, radius, paint);
// canvas.drawRect(width/2, height, width/8, height/2, paint );
canvas.drawRect(x1, y1, x2, y2, paint );

}
}
}

activity_rotate.xml

<?xml version="1.0" encoding="utf-8"?>


<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/rootView"
android:background="@android:color/black"
tools:context=".RotateActivity">

</RelativeLayout>
Output
5. Write an application to mark the daily route of travel in map.

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>


<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.enrouteapp">

<!--
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" />

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


</intent-filter>
</activity>
</application>

</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;

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {

private GoogleMap mMap;


ArrayList markerPoints= new ArrayList();

@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();
}

// Adding new item to the ArrayList


markerPoints.add(latLng);

// Creating MarkerOptions
MarkerOptions options = new MarkerOptions();

// Setting the position of the marker


options.position(latLng);

if (markerPoints.size() == 1) {

options.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREE
N));
} else if (markerPoints.size() == 2) {

options.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED)
);
}

// Add new marker to the Google Map Android API V2


mMap.addMarker(options);

// Checks, whether start and end locations are captured


if (markerPoints.size() >= 2) {
LatLng origin = (LatLng)
markerPoints.get(0); LatLng dest = (LatLng)
markerPoints.get(1);

// Getting URL to the Google Directions API


String url = getDirectionsUrl(origin, dest);

DownloadTask downloadTask = new

DownloadTask();

// Start downloading json data from Google Directions API


downloadTask.execute(url);
}

}
});

}
private class DownloadTask extends AsyncTask<String, Void, String> {

@Override
protected String doInBackground(String... url)

{ String data = "";

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 parserTask = new ParserTask();

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>>>> {

// Parsing the data in non-ui thread


@Override
protected List<List<HashMap<String, String>>> doInBackground(String...
jsonData) {

JSONObject jObject;
List<List<HashMap<String, String>>> routes =

null; try {

jObject = new JSONObject(jsonData[0]);


DirectionsJSONParser parser = new
DirectionsJSONParser();

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();

List<HashMap<String, String>> path =

result.get(i); for (int j = 0; j < path.size(); j+

+) {
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);

// Drawing polyline in the Google Map for the i-th route


mMap.addPolyline(lineOptions);
}
}

private String getDirectionsUrl(LatLng origin, LatLng dest) {

// 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";

// Building the url to the web service


String url = "https://maps.googleapis.com/maps/api/directions/" + output +
"?" + parameters;

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);

urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.connect();


iStream = urlConnection.getInputStream();

BufferedReader br = new BufferedReader(new InputStreamReader(iStream)); StringBuffer sb = new S


String line = "";
while ((line = br.readLine()) != null) { sb.append(line);
}

data = sb.toString(); br.close();


} catch (Exception e) { Log.d("Exception", e.toString());
} finally {
iStream.close();
urlConnection.disconnect();
}
return data;

}
}
activity_maps.xml

<?xml version="1.0" encoding="utf-8"?>


<fragment
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:map="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MapsActivity" />

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;

//import static com.example.mymediaplayer.R.color.material_on_background_disabled;


import static com.example.mymediaplayer.SongsManager.RUNTIME_PERMISSION_CODE;

public class AndroidBuildingMusicPlayerActivity extends


Activity implements MediaPlayer.OnCompletionListener,
SeekBar.OnSeekBarChangeListener {

private ImageButton btnPlay;


private ImageButton btnForward;
private ImageButton
btnBackward; private
ImageButton btnNext; private
ImageButton btnPrevious;
private ImageButton
btnPlaylist; private
ImageButton btnRepeat; private
ImageButton btnShuffle; private
SeekBar songProgressBar;
private TextView
songTitleLabel;
private TextView songCurrentDurationLabel;
private TextView songTotalDurationLabel;
// Media Player
private MediaPlayer mp;
// Handler to update UI timer, progress bar
etc,. private Handler mHandler = new Handler();;
private SongsManager songManager;
private Utilities utils;
private int seekForwardTime = 5000; // 5000 milliseconds
private int seekBackwardTime = 5000; // 5000
milliseconds private int currentSongIndex = 0;
private boolean isShuffle =
false; private boolean isRepeat =
false;
private ArrayList<HashMap<String, String>> songsList =
new ArrayList<HashMap<String, String>>();
private Boolean isPlaying = false;

@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

// Getting all songs list


songsList = songManager.getPlayList();

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) {

// check for repeat is ON or OFF


if(isRepeat){
// repeat is on play same song again
playSong(currentSongIndex);
} else if(isShuffle){
// shuffle is on - play a random song
Random rand = new Random();
currentSongIndex = rand.nextInt((songsList.size() - 1) - 0 + 1) +
0; playSong(currentSongIndex);
} else{
// no repeat or shuffle ON - play next song
if(currentSongIndex < (songsList.size() - 1))
{ playSong(currentSongIndex + 1);
currentSongIndex = currentSongIndex + 1;
}else{
// play first song
playSong(0);
currentSongIndex =
0;
}
}
}

/**
* 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);

// forward or backward to certain seconds


mp.seekTo(currentPosition);

// update timer progress again


updateProgressBar();
}

/**
* Background Runnable thread
* */
private Runnable mUpdateTimeTask = new Runnable()
{ public void run() {
long totalDuration = mp.getDuration();
long currentDuration = mp.getCurrentPosition();

// Displaying Total Duration time

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);

// Running this thread after 100 milliseconds


mHandler.postDelayed(this, 100);
}
};

/**
* 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);

// Changing Button Image to pause image


btnPlay.setImageResource(R.drawable.pause);

// set Progress bar values


songProgressBar.setProgress(0);
songProgressBar.setMax(100);

// Updating progress bar


updateProgressBar();
} catch (IllegalArgumentException e)
{ e.printStackTrace();
} catch (IllegalStateException e)
{ e.printStackTrace();
} catch (IOException e)
{ e.printStackTrace(
);
}
}

// Creating Runtime permission function.


public void AndroidRuntimePermission(){

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))
{

AlertDialog.Builder alert_builder = new


AlertDialog.Builder(AndroidBuildingMusicPlayerActivity.this);
alert_builder.setMessage("External Storage Permission is
Required.");
alert_builder.setTitle("Please Grant
Permission.");
alert_builder.setPositiveButton("OK", new
DialogInterface.OnClickListener() {

@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);

AlertDialog dialog = alert_builder.create();

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:{

if(grantResults.length > 0 && grantResults[0]


== PackageManager.PERMISSION_GRANTED){

}
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;

public class VideoRecorder extends AppCompatActivity {

private Camera mCamera;


private CameraPreview mPreview;
private MediaRecorder mediaRecorder;
private Button capture,
switchCamera; private Context
myContext;
private LinearLayout cameraPreview;
private boolean cameraFront =
false;

@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;
}
}
});

private void initialize() {

capture = findViewById(R.id.button_capture);
switchCamera = findViewById(R.id.button_ChangeCamera);

private int findFrontFacingCamera()


{ int cameraId = -1;
// Search for the front facing camera
int numberOfCameras =
Camera.getNumberOfCameras(); for (int i = 0; i <
numberOfCameras; i++) {
Camera.CameraInfo info = new
Camera.CameraInfo(); Camera.getCameraInfo(i,
info);
if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT)
{ cameraId = i;
cameraFront =
true; break;
}
}
return cameraId;
}

private int findBackFacingCamera()


{ int cameraId = -1;
// Search for the back facing camera
// get the number of cameras
int numberOfCameras = Camera.getNumberOfCameras();
// for every camera check
for (int i = 0; i < numberOfCameras; i++)
{ CameraInfo info = new CameraInfo();
Camera.getCameraInfo(i, info);
if (info.facing == CameraInfo.CAMERA_FACING_BACK)
{ cameraId = i;
cameraFront =
false; break;
}
}
return cameraId;
}

public void onResume()


{ super.onResume();
if (!hasCamera(myContext)) {
Toast toast = Toast.makeText(myContext, "Sorry, your phone does not
have a camera!", Toast.LENGTH_LONG);
toast.show();
finish();
}
if (mCamera == null) {
// if the front facing camera does not exist
if (findFrontFacingCamera()==1) {
// release the old camera instance
// switch camera, from the front and the back and vice versa

releaseCamera();
chooseCamera();
} else {
Toast toast = Toast.makeText(myContext, "Sorry, your phone has only
one camera!", Toast.LENGTH_LONG);
toast.show();
}
}
}

public void chooseCamera() {


// if the camera preview is the front
if (cameraFront) {
int cameraId =
findBackFacingCamera();
Log.v("DS",""+cameraId);
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);
}
} 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;
}
}

private void releaseCamera() {


// stop and release camera
if (mCamera != null)
{ mCamera.release(
); mCamera =
null;
}
}

boolean recording = false;


View.OnClickListener captrureListener = 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;
}*/
}
};

private void releaseMediaRecorder()


{ if (mediaRecorder != null) {
mediaRecorder.reset(); // clear recorder configuration
mediaRecorder.release(); // release the recorder object
mediaRecorder = null;
mCamera.lock(); // lock camera for later use
}
}

private boolean prepareMediaRecorder() {

mediaRecorder = new MediaRecorder(); mCamera = Camera.open(0); mCamera.unlock(); mediaRecorder.setCa

mediaRecorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER); mediaRecorder.setVideoSource(Medi

mediaRecorder.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_720P));

mediaRecorder.setOutputFile("/sdcard/myvideo.mp4"); mediaRecorder.setMaxDuration(600000); //set maximum

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);

VideoView videoView =(VideoView)findViewById(R.id.vdVw);


//Set MediaController to enable play, pause, forward, etc options.
MediaController mediaController= new MediaController(this); mediaController.setAnchorView(videoView);
//Location of Media File
Uri uri = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.video1);
//Starting VideView By Setting MediaController and URI videoView.setMediaController(mediaController); vide
videoView.requestFocus(); videoView.start();
}
}

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;

public class VideoStreaming extends AppCompatActivity {

// Declare variables
ProgressDialog pDialog;
VideoView videoview;

// Insert your Video URL


String VideoURL = "https://www.androidbegin.com/tutorial/AndroidCommercial.3gp";

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

// Find your VideoView in your video_main.xml layout


videoview = (VideoView) findViewById(R.id.videoView);
// Execute StreamVideo AsyncTask

// 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

} catch (Exception e) { Log.e("Error", e.getMessage()); e.printStackTrace();


}

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;

public class PlayListActivity extends ListActivity {

// 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);

ArrayList<HashMap<String, String>> songsListData = new


ArrayList<HashMap<String, String>>();

SongsManager plm = new SongsManager(PlayListActivity.this);


// get all songs from sdcard
this.songsList = plm.getPlayList();
// looping through playlist
for (int i = 0; i < songsList.size(); i++) {
// creating new HashMap
HashMap<String, String> song = songsList.get(i);

// adding HashList to ArrayList


songsListData.add(song);
}

// Adding menuItems to ListView


ListAdapter adapter = new SimpleAdapter(this, songsListData,
R.layout.playlist_item, new String[] { "songTitle" }, new int[] {
R.id.songTitle });

setListAdapter(adapter);

// selecting single ListView item


ListView lv = getListView();
// listening to single listitem click
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {

@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();
});
}
}

You might also like