25 Sep

Deteksi Multitouch di Android

Kita perlu melakukan deteksi multitouch untuk keperluan khusus, misalnya saja kita ingin membuat alat musik digital di Android. Berikut ulasan javaclopedia tentang Multitouch di Android:
1. Kita Buat kelas Extends View. Kita sebut saja MultitouchView

public class MultitouchView extends View {
        public MultitouchView(Context context) {
                super(context);
        } 
}

2. Di dalamnya perlu kita masukkan 2 konstruktur sbb:

        public MultitouchView(Context context, AttributeSet attrs, int defStyle) {
                super(context, attrs, defStyle);
 
        }
 
        public MultitouchView(Context context, AttributeSet attrs) {
                super(context, attrs);
 
        }

3. Masuk ke main.xml (res/layout/main/xml) untuk mengatur layoutnya:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >
 
<com.helloandroid.multitouchexample.MultitouchView
        android:id="@+id/touchView"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" />
 
</LinearLayout>

4. Buat activity sebagai main class:

public class Main extends Activity {
        @Override
        protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.main);
        }
}

5. Tambahkan method berikut di kelas MultitouchView:

@Override
        public boolean onTouchEvent(MotionEvent event) {
                super.onTouchEvent(event);
 
               
                int action = event.getAction() & MotionEvent.ACTION_MASK;
       
                switch (action) {
                case MotionEvent.ACTION_DOWN: {
                        Log.d("MultitouchExample","Action Down");
                        break;
                }
                case MotionEvent.ACTION_MOVE: {
                        Log.d("MultitouchExample","Action Move");
                        break;
                }
 
                case MotionEvent.ACTION_POINTER_DOWN: {
                        Log.d("MultitouchExample","Pointer Down");
                break;
                }
                case MotionEvent.ACTION_POINTER_UP: {
                        Log.d("MultitouchExample","Pointer up");
 
                        break;
                }
                case MotionEvent.ACTION_UP: {
                        Log.d("Multitouch", "Action up");
               
                        break;
                }
                }
 
                return true;
        }

Berikut event-event yang dapat ditangani:
ACTION_DOWN dipanggil ketika jari user pertama menyentuh screen.
ACTION_MOVE dipanggil ketika user menggeser jarinya di screen.
ACTION_POINTER_DOWN dipanggil ketika jari user kedua kalinya menyentuk screen (multitouch).

13 Sep

Background ListView becomes black when scrolling

When we scroll ListView, the background become black when scrolling.
The solution is we can set on ListView XML:

android:cacheColorHint="#00000000"

Ketika kita melakukan scroll pada listview, akan muncul background warna hitam.
Caranya adalah dengan menambahkan atribute pada list view di definisi XML sbb:
android:cacheColorHint=”#00000000″

Semoga bermanfaat

18 Jun

Camera Picture Taken on Android

public class MakePhotoActivity extends Activity {

	private final static String DEBUG_TAG = "MakePhotoActivity"; 
	private Camera camera; 
	private int cameraId = 0;
        public void onClick(View view) { 
	    camera.takePicture(null, null, 
	    new PhotoHandler(getApplicationContext())); 
        }

        protected void onPause() { 
	    if (camera != null) { 
		camera.release(); 
		camera = null; 
	    } 
	    super.onPause(); 
        }
        private int findFrontFacingCamera() { 
	    int cameraId = -1; 

	    int numberOfCameras = Camera.getNumberOfCameras(); 
            for (int i = 0; i < numberOfCameras; i++) { 	
                CameraInfo info = new CameraInfo(); 	
                Camera.getCameraInfo(i, info); 
		if (info.facing == CameraInfo.CAMERA_FACING_FRONT) { 
			Log.d(DEBUG_TAG, "Camera found"); 
			cameraId = i; break; 
		} 
	} 
	return cameraId; 
}
public class PhotoHandler implements PictureCallback
{ 
	
	private final Context context; 
	public PhotoHandler(Context context) {
		this.context = context; 
	}
        private File getDir() { 
	File sdDir = Environment
		.getExternalStoragePublicDirectory(
		Environment.DIRECTORY_PICTURES); 
	return new File(sdDir, &quot;CameraAPIDemo&quot;); 
}
public void onPictureTaken(
  byte[] data, Camera camera) { 

	File pictureFileDir = getDir(); 
	if (!pictureFileDir.exists() && !pictureFileDir.mkdirs()) { 	
              Log.d(Constants.DEBUG_TAG, 
		  "Can't create directory to save image."); 
		Toast.makeText(context, 
		  "Can't create directory to save image.", 
		  Toast.LENGTH_LONG).show(); 
	return; 
} 

18 Jun

Video Recording On Android

public class VideoCapture extends Activity 
	implements OnClickListener, 
	SurfaceHolder.Callback {    
     MediaRecorder recorder;
     SurfaceHolder holder;
     boolean recording = false;

public void surfaceCreated(SurfaceHolder holder) {
	prepareRecorder();
}
public void surfaceChanged(SurfaceHolder holder, 
	int format, int width, int height) {
}
public void surfaceDestroyed(SurfaceHolder holder) {    
        if (recording) {        
                  recorder.stop();        
                  recording = false;    
        }    
        recorder.release();    
        finish();
}
private void prepareRecorder() {  recorder.setPreviewDisplay(holder.getSurface());    try {        recorder.prepare();    } catch (IllegalStateException e) {        e.printStackTrace();        finish();    } catch (IOException e) {        e.printStackTrace();        finish();    }}
public void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);
  requestWindowFeature(Window.FEATURE_NO_TITLE);
  getWindow().setFlags(
		WindowManager.LayoutParams.FLAG_FULLSCREEN,
 		WindowManager.LayoutParams.FLAG_FULLSCREEN);
	setRequestedOrientation(
		ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);recorder = new MediaRecorder();initRecorder();setContentView(R.layout.main);

	SurfaceView cameraView = 
		(SurfaceView)findViewById(R.id.CameraView);
	holder = cameraView.getHolder();
	holder.addCallback(this);
  holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);cameraView.setClickable(true);cameraView.setOnClickListener(this);
}
private void initRecorder() {
	recorder.setAudioSource(
		MediaRecorder.AudioSource.DEFAULT);
	recorder.setVideoSource(
		MediaRecorder.VideoSource.DEFAULT);
	CamcorderProfile cpHigh = CamcorderProfile
		.get(CamcorderProfile.QUALITY_HIGH);
	recorder.setProfile(cpHigh);
	recorder.setOutputFile("/sdcard/
		videocapture_example.mp4");
	recorder.setMaxDuration(50000); // 50 s
         recorder.setMaxFileSize(5000000); // 5 mb
}
public void onClick(View v) {    
        if (recording) {        
              recorder.stop();        
              recording = false;

	     // selalu panggil init untuk record ulang        
              initRecorder();        
               prepareRecorder();    
        } else {        
             recording = true;        
             recorder.start();    
        }
}

18 Jun

Read Write SD Card on Android

pertama yang harus dilakukan adalah membuka AndroidManifest.xml dan tambahkan Permission berikut:

android.permission.WRITE_EXTERNAL_STORAGE

Cara Menulis Data ke File SD Card

File file = new File("/sdcard/mysdfile.txt");
file.createNewFile();
FileOutputStream fos = 
		new FileOutputStream(file); 

OutputStreamWriter osw = 
		new OutputStreamWriter(fos);
osw.append(txtData.getText());
osw.close();
fos.close();

Cara Membaca Data dari File SD Card

File file = new File("/sdcard/mysdfile.txt");
FileInputStream fis = 
	new FileInputStream(file);
BufferedReader myReader = 
	new BufferedReader(new InputStreamReader(fis)); 
String aDataRow = ""; 
String aBuffer = ""; 
while ((aDataRow = myReader.readLine()) != null) {
	aBuffer += aDataRow + "\n"; 
} 
txtData.setText(aBuffer); 
myReader.close();