Manifest
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera"
/>
above <application>
XML
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:layout_gravity="center"
tools:context="np.com.sitalmandal.project_traning.MainActivity">
<Button
tools:ignore="MissingConstraints"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:id= "@+id/button"
android:onClick="TorchONButtonClick"
android:text="torch_on"
android:gravity="center"
/>
<Button
tools:ignore="MissingConstraints"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/button2"
android:onClick="TorchOFFButtonClick"
android:text="torch_off"
android:gravity="center"
/>
</LinearLayout>
MainActivity.java
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.content.Context;
import android.hardware.camera2.CameraAccessException;
import android.hardware.camera2.CameraManager;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private CameraManager cameraManager;
private String cameraID;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
cameraManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
try {
cameraID = cameraManager.getCameraIdList()[0]; // 0 is for back camera and 1 is for front camera
} catch (Exception e) {
e.printStackTrace();
}
}
public void TorchOFFButtonClick(View view){
try {
Toast.makeText(getApplicationContext(), "OFF", Toast.LENGTH_SHORT).show();
cameraManager.setTorchMode(cameraID, false);
} catch (Exception e) {
e.printStackTrace();
}
}
public void TorchONButtonClick(View view) {
try {
Toast.makeText(getApplicationContext(), "On", Toast.LENGTH_SHORT).show();
cameraManager.setTorchMode(cameraID, true);
} catch (Exception e) {
e.printStackTrace();
}
}
}
No comments:
Post a Comment