2012年5月31日 星期四

網路檔案下載─FTP



網路檔案下載─FTP: 從中華電信提供的網路存放空間,下載檔案。

使用外部元件: Apache Commons NET
   commons-net-3.0.1-src.zip 的class : 下載點

     1. Unzip it.
     2. 到Eclipse的android作業平台上的 File -> Import -> General -> File System
    

          

       3. 然後 Browse 剛才Unzip後 存放 commons-net-3.0.1-src 的夾子,找到 java 的子目錄,然後按『確定』。

4. 你的作業環境,應該會呈現下圖的樣子,如果如圖所示,表示成功,便可以開始使用了。





需開啟之權限: 
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.INTERNET"/>


main.java


import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.http.util.EncodingUtils;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.widget.TextView;

public class FTPDownloadFileActivity extends Activity {
    /** Called when the activity is first created. */

private TextView tv;
private TextView tvContent;
private String fileName = "myFile.txt"; //網站上準備要下載的檔名


private final String SD_PATH = Environment.getExternalStorageDirectory().getAbsolutePath();
private final String FILE_PATH = "/download";
private final String FILE_NAME = "copy_" + fileName; //下載進手機後的檔名
private final String ENCODING = "UTF-8";
private FileInputStream fis = null;


        private ProgressDialog mProgressDialog;
 
private Handler handler = new Handler(){  //使用handler, thread 防止下載檔案太大

@Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
super.handleMessage(msg);
mProgressDialog.dismiss(); //close
readFile();
}

};

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
     
        tv = (TextView)findViewById(R.id.textview);
        tvContent = (TextView) findViewById(R.id.textviewContent);
        processThread();
     
    }
 
 
 
    private void ftpDownload() {  //使用FTP 下載檔案
    FTPClient ftpClient = new FTPClient();
    try {
//     ftpClient.connect(InetAddress.getByName("203.66.87.21"));//與以下的String 意義一樣
    ftpClient.connect(InetAddress.getByName("ftp.myweb.hinet.net")); //中華電信的網頁IP ADDRESS
    ftpClient.login("username", "password");
    tv.setText(String.valueOf(ftpClient.isConnected()));
    ftpClient.changeWorkingDirectory("/");
    File localfile = new File ("/sdcard/download/" + FILE_NAME);
    OutputStream os = new FileOutputStream(localfile);
    ftpClient.enterLocalPassiveMode();
    ftpClient.retrieveFile(fileName, os);
    ftpClient.logout();
    ftpClient.disconnect();
    }catch (Exception e) {
    e.printStackTrace();
    }
    }
 
 
    public void readFile () {  //將內容顯示到螢幕上
     
        String result = "";
        try {
       
         File mFilePath = new File (SD_PATH + FILE_PATH);
         String mFileName = mFilePath + "/" + FILE_NAME;
         File fileText = new File (mFileName);
       
         fis = new FileInputStream(fileText);
         int length = fis.available();
         byte [] buffer = new byte [length];
         fis.read(buffer);
         result = EncodingUtils.getString(buffer, ENCODING);
         fis.close();
         tvContent.setText(result);
       
        } catch (Exception e) {
         e.printStackTrace();
        }
       }
 
 
    private void processThread() {
    mProgressDialog = ProgressDialog.show(this, "文件下載", "正在下載...");
    new Thread () {

@Override
public void run() {
// TODO Auto-generated method stub
//super.run();
ftpDownload();
prolongedActionMethod(); //做測試用的
handler.sendEmptyMessage(0);
}
   
    }.start();
    }
 
 
    private void prolongedActionMethod() { //故意延遲十秒鐘,做測試用的
    try {
    Thread.sleep(10000);
    }catch (Exception e){
    e.printStackTrace();
    }
    }
}


*************************************************
res/layout/main.xml:


<?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" >

    <TextView
        android:id="@+id/textview"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello"
        />
    <!--  將 TextView 包在 ScrollView 裡,當內容太長,可以捲動。  -->
     <ScrollView
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:fadingEdge="vertical"
        android:paddingTop="10dip"
        android:scrollbars="vertical" >

        <TextView
            android:id="@+id/textviewContent"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:paddingTop="10dip"
            android:text=""
            android:textSize="20dp"
            android:textColor="#00FF00" />
    </ScrollView>

</LinearLayout>

2012年5月30日 星期三

背景:重複動畫




重複讓背景淡出、深入的動作:





import android.app.Activity;
import android.os.Bundle;

import android.view.animation.Animation;
import android.view.animation.AnimationUtils;


import android.widget.LinearLayout;

public class BackgroundDemoActivity extends Activity {

    private LinearLayout mLinearLayout;
    private Animation alphaAnim;


   @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
     
        mLinearLayout = (LinearLayout) findViewById(R.id.LinearLayout01);
        alphaAnim = AnimationUtils.loadAnimation(this, R.anim.alpha);
        mLinearLayout.setAnimation(alphaAnim);
      }
}


************************************************
res/anim/alpha.xml:


<?xml version="1.0" encoding="utf-8"?>
<set android:shareInterpolator="false" xmlns:android="http://schemas.android.com/apk/res/android">
   <alpha android:fromAlpha="1.0"
        android:toAlpha="0.6"
        android:startOffset="0"
        android:duration="5000"
        android:repeatCount="infinite"
        android:repeatMode="reverse"
        />
</set>
********************************
res/layout/main.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/LinearLayout01"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    android:background="@drawable/gradient_selector"
    >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello" />

</LinearLayout>

*********************************
res/drawable/gradient_selector.xml:

<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item>
        <shape>
            <gradient 
                android:angle="90" 
                android:endColor="#FF00FF00" 
                android:startColor="#FFFF0000" 
                android:type="linear" />
        </shape>
        
     </item>

</selector>

**********************************************
**********************************************
當然也可以換成:traslate

res/anim/translate.xml:


<?xml version="1.0" encoding="utf-8"?>
<set android:shareInterpolator="false" xmlns:android="http://schemas.android.com/apk/res/android">

    <scale android:fromXScale="1"
          android:toXScale="5"
          android:fromYScale="1"
          android:toYScale="5"
          android:pivotX="50%"
          android:pivotY="50%"
          android:duration="3000"
          android:repeatCount="infinite"
 android:repeatMode="reverse"/>
 
<translate
android:fromXDelta="0"
android:toXDelta="20"
android:fromYDelta="0"
android:toYDelta="20"
android:startOffset="10"
android:duration="3000"
android:repeatCount="infinite"
android:repeatMode="reverse" />

</set>


***********************************************
***********************************************
或是
res/anim/rotate.xml:


<?xml version="1.0" encoding="utf-8"?>
<set android:shareInterpolator="false" xmlns:android="http://schemas.android.com/apk/res/android">

    <scale android:fromXScale="3"
          android:toXScale="3"
          android:fromYScale="3"
          android:toYScale="3"
          android:pivotX="50%"
          android:pivotY="50%"
          android:duration="5000"
          android:repeatCount="infinite"
 android:repeatMode="restart"/>
    <rotate
        android:fromDegrees="0"
        android:toDegrees="360"
        android:pivotX="50%"
android:pivotY="50%"
  android:startOffset="10"
android:duration="5000"
android:repeatCount="infinite"
android:repeatMode="restart"/>
 
</set>

2012年5月21日 星期一

Handler -- v3. thread

Handler 下載網路的圖,如遇上restart,thread 還是能保存下來。


Manifest.xm:


<uses-permission android:name="android.permission.INTERNET"/>

**************************
res/layout/main.xml:


<?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" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello" />

    <LinearLayout
        android:id="@+id/linearLayout1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" >

        <Button
            android:id="@+id/button1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="下載" />

        <Button
            android:id="@+id/button2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="重整" />

    </LinearLayout>

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_launcher" />

</LinearLayout>



*********************************

public class Cq_Handler_vogella03Activity extends Activity {
    /** Called when the activity is first created. */
private static ProgressDialog dialog;
private static ImageView mImageView;
private static Bitmap downloadBitmap;
private static Handler handler;
private Thread downloadThread;
private Button downloadBtn;
private Button resetBtn;
 
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        //Create a handler to update the UI
        handler = new Handler();
        mImageView = (ImageView) findViewById(R.id.imageView1);
        
        //Did we already download the image?
        if (downloadBitmap != null) {
        mImageView.setImageBitmap(downloadBitmap);
        }
        
        //Check if the thread is already running
        downloadThread = (Thread) getLastNonConfigurationInstance();
        if (downloadThread != null && downloadThread.isAlive()) {
        dialog = ProgressDialog.show(this, "下載狀況", "下載中...");
        }
        
        //Setup buttons
        downloadBtn = (Button) findViewById(R.id.button1);
        resetBtn = (Button) findViewById(R.id.button2);
        
        downloadBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
downloadPicture(v);
}
});
        
        resetBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
resetPicture(v);
}
});
    }
    
    
    
    public void downloadPicture (View view) {
    
    dialog = ProgressDialog.show(this, "下載狀況", "下載中...");
    downloadThread = new MyThread();
    downloadThread.start();
    
    }
    
    public void resetPicture(View view) {
    if (downloadBitmap != null) {
    downloadBitmap = null;
    }
    mImageView.setImageResource(R.drawable.ic_launcher);
    }


    //SAVE the thread
@Override
public Object onRetainNonConfigurationInstance() {
// TODO Auto-generated method stub
//return super.onRetainNonConfigurationInstance();
return downloadThread;
}


    // Dismiss dialog if activity is destroyed
@Override
protected void onDestroy() {
// TODO Auto-generated method stub
if (dialog != null && dialog.isShowing()) {
dialog.dismiss();
dialog = null;
}
super.onDestroy();
}
    
    // Utility method to download image from the internet
static private Bitmap downloadBitmap (String url) throws IOException {
HttpUriRequest request = new HttpGet(url.toString());
HttpClient httpClient = new DefaultHttpClient();
HttpResponse response = httpClient.execute(request);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
byte [] bytes = EntityUtils.toByteArray(entity);
Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
return bitmap;
}else {
throw new IOException("Download failed, HTTP response code " + statusCode + " - "
+ statusLine.getReasonPhrase());
}
}
   
static public class MyThread extends Thread {

@Override
public void run() {
// TODO Auto-generated method stub
//super.run();
try {
//Simulate a slow network
try {
new Thread().sleep(5000);
}catch (InterruptedException e) {
e.printStackTrace();
}
downloadBitmap = downloadBitmap("http://www.vogella.com/img/lars/LarsVogelArticle7.png");
handler.post(new MyRunnable());
}catch (IOException e) {
e.printStackTrace();
}finally {
}
}
}// end of MyThread
    
static public class MyRunnable implements Runnable {

@Override
public void run() {
// TODO Auto-generated method stub
mImageView.setImageBitmap(downloadBitmap);
dialog.dismiss();
}
     }// end of MyRunnable
}

Handler -- Async Task

Handler: Async Task
使用 Async Task (非同步任務)的方式下載網頁的內容。當背景下載完成時,才載入TextView 裡顯現出來。

參考:http://www.vogella.com/articles/AndroidPerformance/article.html






res/layout/main.xml:


<?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" >

    <Button
        android:id="@+id/button1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Load Webpage" />
     <ScrollView
        android:id="@+id/scrollView"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:fadingEdge="vertical"
        android:paddingTop="10dip"
        android:scrollbars="vertical" >

     <TextView
            android:id="@+id/textView01"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:paddingTop="10dip"
            android:text="Taipei Times (台北時報)"
            android:textColor="#00FF00"
           />
    </ScrollView>

      
</LinearLayout>

****************************************
main.java:

/**
 *  Async Task  using Android HttpClient
 * */
public class HandlerAsyncTaskActivity extends Activity {
    /** Called when the activity is first created. */
private TextView tv;
private Button btn;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        tv = (TextView) findViewById(R.id.textView01);
      
        btn = (Button) findViewById(R.id.button1);
        btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
readWebpage(tv);
}
});
    }
    
    
    private class DownloadWebPageTask extends AsyncTask<String, Void, String>{

@Override
protected String doInBackground(String... urls) {
// TODO Auto-generated method stub
String response = "";
for (String url : urls) {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse execute = client.execute(httpGet);
InputStream content = execute.getEntity().getContent();
BufferedReader buffer = new BufferedReader(new InputStreamReader(content));
String s = "";
while ((s = buffer.readLine()) != null) {
response += s;
}
}catch (Exception e) {
e.printStackTrace();
}
}
return response;
}

@Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
//super.onPostExecute(result);
tv.setText(result);
}
    
    }
    
    public void readWebpage (View view) {
    DownloadWebPageTask task = new DownloadWebPageTask();
    task.execute(new String[] {"http://www.taipeitimes.com"});
    }
}


Handler-- ProgressBar

Handler
參考:http://www.vogella.com/articles/AndroidPerformance/article.html





res/layout/main.xml:


<?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" >

    <TextView
        android:id="@+id/textView"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Handler" />

    <ProgressBar
        android:id="@+id/progressBar1"
        style="?android:attr/progressBarStyleHorizontal"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:indeterminate="false"
        android:max="10"
        android:padding="4dip" />

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Start Progress" 
        android:onClick="startProgress"/>

</LinearLayout>

*******************************

main.java:


public class Cq_Handler_vogella01Activity extends Activity {
    /** Called when the activity is first created. */
private Handler mHandler;
private ProgressBar mProgressBar;
private Button mBtn;
private TextView tv;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        mProgressBar = (ProgressBar) findViewById(R.id.progressBar1);
        mBtn = (Button) findViewById(R.id.button1);
        tv = (TextView) findViewById(R.id.textView);
        
        mHandler = new Handler();
        mBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
startProgress();
}
});
    }
    
    public void startProgress () {
    //Do something long
    Runnable runnable = new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
for (int i = 0; i<= 10; i++) {
final int value = i;
try {
Thread.sleep(2000);
}catch (InterruptedException e) {
e.printStackTrace();
}
mHandler.post(new Runnable () {// 用來更新 View

@Override
public void run() {
// TODO Auto-generated method stub
mProgressBar.setProgress(value);
tv.setText("the value = " + value );
}
});
}
}
};
new Thread(runnable).start();
    }
}

2012年5月20日 星期日

Handler 03 + Timer



Handler and Timer

http://weizhulin.blog.51cto.com/1556324/323922



import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;

public class Cq_Handler04Activity extends Activity {
    /** Called when the activity is first created. */

private int title = 0;
private Handler mHandler = new Handler() {

@Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
//super.handleMessage(msg);
switch (msg.what) {
case 1:
updateTitle();
break;
}
}
};


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
     
        Timer timer = new Timer();
        timer.scheduleAtFixedRate(new MyTask(), 1, 1000);
    }
 
    private class MyTask extends TimerTask{

@Override
public void run() {
// TODO Auto-generated method stub
Message message = new Message();
message.what = 1;
mHandler.sendMessage(message);
}
   
    }
 
 
    public void updateTitle() {
    setTitle("Welcome to CQ's palace: " + title);
    title ++;
    }
}

Handler 01-- MainThread


MainHandler






package com.cq.practice.handler01;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.res.Resources;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;


public class Cq_Handler01Activity extends Activity {
    /** Called when the activity is first created. */

private Button mButton;
private ProgressDialog mProgressDialog;

private Handler handler = new Handler(){

@Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
super.handleMessage(msg);
mProgressDialog.dismiss(); //close
}

};

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
     
        Resources res = this.getResources();
        mButton = (Button) findViewById(R.id.button1);
        mButton.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
processThread();
}
});
     
    }
 
 
 
    private void processThread() {
    mProgressDialog = ProgressDialog.show(this, "文件下載", "正在下載...");
   
    new Thread() {
   
   
    @Override
public void run() {
// TODO Auto-generated method stub
//super.run();
    prolongedActionMethod();
    handler.sendEmptyMessage(0);
}


    }.start();
    }
 
 
    private void prolongedActionMethod() {
    try {
    Thread.sleep(10000);
    }catch (Exception e){
    e.printStackTrace();
    }
    }
 
}

參考:
http://android.yaohuiji.com/archives/770

2012年5月19日 星期六

TextView 滾動 ─利用 ScrollView


只要用 ScrollView 包起來,TextView 裡的內容便可以滾動。



res/layout/main.xml:



<?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" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="測試 TextView 的內容可以滾動"
        android:textSize="25dp" />

    <ScrollView
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:fadingEdge="vertical"
        android:paddingTop="10dip"
        android:scrollbars="vertical" >

        <TextView
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:paddingTop="10dip"
            android:text="@string/text_content"
            android:textSize="20dp" />
    </ScrollView>

</LinearLayout>

*******************************

res/values/strings:

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

    <string name="hello">Hello World, Cq_TextView01Activity!</string>
    <string name="app_name">Cq_TextView01</string>
    <string name="text_content">歐美經濟情勢動盪不安,連帶影響國際油價持續走跌,預計台灣中油於下周一起,汽柴油價格可望降價1角,是從上個月油價調漲後,連續第7次調價。
現在的92無鉛汽油每公升是32.6元,自4月2日一次調漲2.3元;而95無鉛每公升為34.1元,從4月2日一次調升3.1元;此外,98無鉛每公升為36.1元,4月2日則一次增3.6元;柴油每公升是31.7元,4月2日一次調漲3.2元。
國際油價走跌,指標原油價格自上周每桶109.92美元跌到108.67美元;依據浮動油價公式以及減半調降機制初步估計,台灣中油從下周一凌晨起,可望再度調降國內汽柴油的價格,每公升調降約1角。
    </string>

</resources>



2012年5月18日 星期五

android -- Camera



Manifest:


<uses-permission android:name="android.permission.CAMERA"/>
    <uses-feature android:name="android.hardware.camera"/>
    <uses-feature android:name="android.hardware.camera.autofocus"/>
    <uses-feature android:name="android.hardware.camera.flash"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>



<activity
            android:label="@string/app_name"
            android:name=".Cq_MyCameraActivity"
            android:screenOrientation="landscape" >


*********************************

Main.java:


public class Cq_MyCameraActivity extends Activity {
 

final int latchedOrientation = 90;
private Camera mCamera;

// Create surface for preview
private SurfaceHolder.Callback mSurfaceListener =
new SurfaceHolder.Callback() {

@Override
public void surfaceDestroyed(SurfaceHolder holder) {
// TODO Auto-generated method stub
mCamera.release();
mCamera = null;
}

@Override
public void surfaceCreated(SurfaceHolder holder) {
// TODO Auto-generated method stub
mCamera = Camera.open();
try {
mCamera.setPreviewDisplay(holder);
}catch (Exception e) {
e.printStackTrace();
}
}

@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
// TODO Auto-generated method stub
Camera.Parameters params = mCamera.getParameters();
params.set("jpeg-quality", 85);
mCamera.setParameters(params);
mCamera.startPreview();
}
};// end of mSurfaceListener


// Auto focus to take a photo
private Camera.AutoFocusCallback mAutoFocusListener =
new Camera.AutoFocusCallback() {

@Override
public void onAutoFocus(boolean success, final Camera camera) {
// TODO Auto-generated method stub
camera.autoFocus(null);
camera.takePicture(mShutterListener, null, mPictureListener);
new Thread() {

@Override
public void run() {
// TODO Auto-generated method stub
//super.run();
try {
Thread.sleep(3000);
}catch (InterruptedException e) {
e.printStackTrace();
}
camera.startPreview();
}

}.start(); // end of Thread
}
};// end of mAutoFocusListener


// Listener for Shut process
private Camera.ShutterCallback mShutterListener =
new Camera.ShutterCallback() {

@Override
public void onShutter() {
// TODO Auto-generated method stub

}
};// end of mShutterListener

// Listener for Picture process
private Camera.PictureCallback mPictureListener =
new Camera.PictureCallback() {

@Override
public void onPictureTaken(byte[] data, Camera camera) {
// TODO Auto-generated method stub
FileOutputStream fos = null;
try {
fos = new FileOutputStream("/sdcard/MyCamera.jpg");
fos.write(data);
}catch (IOException e) {
e.printStackTrace();
}finally {
if (fos != null){
try {
fos.close();
}catch (IOException e) {
e.printStackTrace();
}
}

}
}
};// end of mPictureListener


// Press Camera photo button
private View.OnClickListener mButtonListener =
new View.OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (mCamera != null) {
mCamera.autoFocus(mAutoFocusListener);
}
}
};// end of mButtonListener


/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
     
        final Window win = getWindow();
      //No Status Bar
        win.addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
      //No Title Bar
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        requestWindowFeature(Window.FEATURE_PROGRESS);
        setContentView(R.layout.main);
     // Camera preview
        SurfaceView surface = (SurfaceView) findViewById(R.id.surfaceView1);
        SurfaceHolder holder = surface.getHolder();
        holder.addCallback(mSurfaceListener);
        holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
     // Camera photo button
        ImageButton button = (ImageButton) findViewById(R.id.imageButton1);
        button.setOnClickListener(mButtonListener);
    }
}


******************************************

<?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="horizontal" >

    <ImageButton
        android:id="@+id/imageButton1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:src="@drawable/camera" />

    <SurfaceView
        android:id="@+id/surfaceView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</LinearLayout>