Modify main.xml to have a button to toggle torch on/off.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
<Button
android:id="@+id/flashcontrol"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>
main code
package com.exercise.AndroidFlashLight;
import android.app.Activity;
import android.hardware.Camera;
import android.hardware.Camera.Parameters;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class AndroidFlashLight extends Activity {
Camera camera = null;
Parameters parameters;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final Button FlashLightControl = (Button)findViewById(R.id.flashcontrol);
FlashLightControl.setText("Set FLASH_MODE_TORCH");
FlashLightControl.setOnClickListener(new Button.OnClickListener(){
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if(camera == null){
camera = Camera.open();
parameters = camera.getParameters();
parameters.setFlashMode(Parameters.FLASH_MODE_TORCH);
camera.setParameters(parameters);
FlashLightControl.setText("Set FLASH_MODE_OFF");
}else{
parameters.setFlashMode(Parameters.FLASH_MODE_OFF);
camera.setParameters(parameters);
camera.release();
camera = null;
FlashLightControl.setText("Set FLASH_MODE_TORCH");
}
}});
}
}
Modify AndroidManifest.xml to grant permission of "android.permission.CAMERA".
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.exercise.AndroidFlashLight"
android:versionCode="1"
android:versionName="1.0">
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".AndroidFlashLight"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<uses-sdk android:minSdkVersion="7" />
<uses-permission android:name="android.permission.CAMERA"/>
</manifest>
Download the files.
No comments:
Post a Comment