懐中電灯アプリを実行する最も単純で最も平凡な方法
// XML コード
<?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"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.android.torcia.MainActivity">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="ON"
android:id="@+id/flash_button"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:onClick="turnOnOff"/>
</RelativeLayout>
//Java コード
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
Button flashButton;
String buttonText;
public void checkState(String buttonText) {
switch (buttonText) {
case "ON":
flashButton.setText("OFF");
flashOn();
break;
case "OFF":
flashButton.setText("ON");
flashOff();
break;
}
}
public void turnOnOff(View view) {
flashButton = (Button) findViewById(R.id.flash_button);
buttonText = flashButton.getText().toString();
checkState(this.buttonText);
}
public void flashOn() {
Camera camera = Camera.open();
Camera.Parameters parameters = camera.getParameters();
parameters.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
camera.setParameters(parameters);
camera.startPreview();
}
public void flashOff() {
Camera camera2 = Camera.open();
Camera.Parameters parameters2 = camera2.getParameters();
parameters2.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
camera2.setParameters(parameters2);
camera2.stopPreview();
}
}
// AndroidManifest
<?xml version="1.0" encoding="utf-8"?>
<uses-permission android:name="android.permission.CAMERA"/>
<uses-permission android:name="android.permission.FLASHLIGHT"/>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
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>
</application>