2016年7月24日 星期日

facial detection in android

Ref  1:  http://androidbite.blogspot.tw/2012/11/android-face-detection-example.html

Ref 2 ; http://code.tutsplus.com/tutorials/an-introduction-to-face-detection-on-android--cms-25212


說明:  直接用 Ref 1 可以跑...  但是  Ref 2 有些問題...直接把Ref 2的sample code import 又可以跑

           還沒有try 出來


         


package jacky.idv.facedetectiondemo;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PointF;
import android.media.FaceDetector;
import android.media.FaceDetector.Face;
import android.os.Bundle;
import android.view.View;



public class MainActivity extends Activity {



    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(new myView(this));

    }



    private class myView extends View {



        private int imageWidth, imageHeight;

        private int numberOfFace = 5;

        private FaceDetector myFaceDetect;

        private FaceDetector.Face[] myFace;

        float myEyesDistance;

        int numberOfFaceDetected;



        Bitmap myBitmap;



        public myView(Context context) {

            super(context);



            BitmapFactory.Options BitmapFactoryOptionsbfo = new BitmapFactory.Options();

            BitmapFactoryOptionsbfo.inPreferredConfig = Bitmap.Config.RGB_565;

            //myBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.jennifer_lopez, BitmapFactoryOptionsbfo);            myBitmap = BitmapFactory.decodeResource(getResources(), R.raw.face , BitmapFactoryOptionsbfo);
            //
            imageWidth = myBitmap.getWidth();

            imageHeight = myBitmap.getHeight();

            myFace = new FaceDetector.Face[numberOfFace];

            myFaceDetect = new FaceDetector(imageWidth, imageHeight,

                    numberOfFace);

            numberOfFaceDetected = myFaceDetect.findFaces(myBitmap, myFace);



        }



        @Override
        protected void onDraw(Canvas canvas) {



            canvas.drawBitmap(myBitmap, 0, 0, null);



            Paint myPaint = new Paint();

            myPaint.setColor(Color.GREEN);

            myPaint.setStyle(Paint.Style.STROKE);

            myPaint.setStrokeWidth(3);



            for (int i = 0; i < numberOfFaceDetected; i++) {

                Face face = myFace[i];

                PointF myMidPoint = new PointF();

                face.getMidPoint(myMidPoint);

                myEyesDistance = face.eyesDistance();



                canvas.drawRect((int) (myMidPoint.x - myEyesDistance * 2),

                (int) (myMidPoint.y - myEyesDistance * 2),

                (int) (myMidPoint.x + myEyesDistance * 2),

                (int) (myMidPoint.y + myEyesDistance * 2), myPaint);

            }

        }

    }



}

voice recognition demo


Ref : http://code4reference.com/2012/07/tutorial-android-voice-recognition/

main.xml 如下:

按下   speak button  

會啟動voice recognition 的服務  (呼叫  speak ())



=======================================================


<LinearLayout 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:orientation="vertical" >

    <EditText        android:id="@+id/etTextHint"        android:gravity="top"        android:inputType="textMultiLine"        android:lines="1"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:text="@string/etSearchHint"/>

    <Button        android:id="@+id/btSpeak"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:onClick="speak"
        android:text="@string/btSpeak"        tools:context=".VoiceRecognitionActivity" />

    <Spinner        android:id="@+id/sNoOfMatches"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:entries="@array/saNoOfMatches"        android:prompt="@string/sNoOfMatches"/>

    <TextView        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:text="@string/tvTextMatches"        android:textStyle="bold" />

    <ListView        android:id="@+id/lvTextMatches"        android:layout_width="match_parent"        android:layout_height="wrap_content" />

</LinearLayout>

========================================================================================
String.xml

========================================================================================

<string name="btSpeak">Speak</string>
<string name="menu_settings">Settings</string>
<string name="title_activity_voice_recognition">Voice Recognition</string>
<string name="tvTextMatches">Text Matches</string>
<string name="sNoOfMatches">No of Matches</string>
<string name="etSearchHint">Speech hint here</string>
<string-array name="saNoOfMatches">
    <item>1</item>
    <item>2</item>
    <item>3</item>
    <item>4</item>
    <item>5</item>
    <item>6</item>
    <item>7</item>
    <item>8</item>
    <item>9</item>
    <item>10</item>
</string-array>

========================================================================================

main.java 如下:


重點是 speak()

會啟動 ACTION_RECOGNIZE_SPEECH 服務
 Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);


//Start the Voice recognizer activity for the result.startActivityForResult(intent, VOICE_RECOGNITION_REQUEST_CODE);


最後做完會呼叫 這個   onActivityResult()...是繼承函式

@Overrideprotected void onActivityResult(int requestCode, int resultCode, Intent data) {


最後string 會放在 textMatchList  這個ArrayList裡面

========================================================================================


public class MainActivity extends AppCompatActivity {

    private static final int VOICE_RECOGNITION_REQUEST_CODE = 1001;

    private EditText metTextHint;
    private ListView mlvTextMatches;
    private Spinner msTextMatches;
    private Button mbtSpeak;

    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
       // setContentView(R.layout.activity_voice_recognition);        metTextHint = (EditText) findViewById(R.id.etTextHint);
        mlvTextMatches = (ListView) findViewById(R.id.lvTextMatches);
        msTextMatches = (Spinner) findViewById(R.id.sNoOfMatches);
        mbtSpeak = (Button) findViewById(R.id.btSpeak);
        checkVoiceRecognition();
    }

    public void checkVoiceRecognition() {
        // Check if voice recognition is present        PackageManager pm = getPackageManager();
        List<ResolveInfo> activities = pm.queryIntentActivities(new Intent(
                RecognizerIntent.ACTION_RECOGNIZE_SPEECH), 0);
        if (activities.size() == 0) {
            mbtSpeak.setEnabled(false);
            mbtSpeak.setText("Voice recognizer not present");
            Toast.makeText(this, "Voice recognizer not present",
                    Toast.LENGTH_SHORT).show();
        }
    }

    public void speak(View view) {
        Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);

        // Specify the calling package to identify your application        intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, getClass()
                .getPackage().getName());

        // Display an hint to the user about what he should say.        intent.putExtra(RecognizerIntent.EXTRA_PROMPT, metTextHint.getText()
                .toString());

        // Given an hint to the recognizer about what the user is going to say        //There are two form of language model available        //1.LANGUAGE_MODEL_WEB_SEARCH : For short phrases        //2.LANGUAGE_MODEL_FREE_FORM  : If not sure about the words or phrases and its domain.
        intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
                RecognizerIntent.LANGUAGE_MODEL_WEB_SEARCH);

        // If number of Matches is not selected then return show toast message        if (msTextMatches.getSelectedItemPosition() == AdapterView.INVALID_POSITION) {
            Toast.makeText(this, "Please select No. of Matches from spinner",
                    Toast.LENGTH_SHORT).show();
            return;
        }

        int noOfMatches = Integer.parseInt(msTextMatches.getSelectedItem()
                .toString());
        // Specify how many results you want to receive. The results will be        // sorted where the first result is the one with higher confidence.        intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, noOfMatches);
        //Start the Voice recognizer activity for the result.        startActivityForResult(intent, VOICE_RECOGNITION_REQUEST_CODE);
    }

    @Override    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == VOICE_RECOGNITION_REQUEST_CODE)

            //If Voice recognition is successful then it returns RESULT_OK            if(resultCode == RESULT_OK) {

                //  把data 從 voice recognition 中取出來
                ArrayList<String> textMatchList = data
                        .getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);

                if (!textMatchList.isEmpty()) {
                    // If first Match contains the 'search' word                    // Then start web search.                    if (textMatchList.get(0).contains("search")) {

                        String searchQuery = textMatchList.get(0);
                        searchQuery = searchQuery.replace("search","");
                        Intent search = new Intent(Intent.ACTION_WEB_SEARCH);
                        search.putExtra(SearchManager.QUERY, searchQuery);
                        startActivity(search);
                    } else {
                        // populate the Matches                        mlvTextMatches                                .setAdapter(new ArrayAdapter<String>(this,
                                        android.R.layout.simple_list_item_1,
                                        textMatchList));
                    }

                }
                //Result code for various error.            }else if(resultCode == RecognizerIntent.RESULT_AUDIO_ERROR){
                showToastMessage("Audio Error");
            }else if(resultCode == RecognizerIntent.RESULT_CLIENT_ERROR){
                showToastMessage("Client Error");
            }else if(resultCode == RecognizerIntent.RESULT_NETWORK_ERROR){
                showToastMessage("Network Error");
            }else if(resultCode == RecognizerIntent.RESULT_NO_MATCH){
                showToastMessage("No Match");
            }else if(resultCode == RecognizerIntent.RESULT_SERVER_ERROR){
                showToastMessage("Server Error");
            }
        super.onActivityResult(requestCode, resultCode, data);
    }

    void showToastMessage(String message){
        Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
    }

}




2016年7月23日 星期六

SpinnerDemo




main.xml


<LinearLayout 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:paddingLeft="@dimen/activity_horizontal_margin"    android:paddingRight="@dimen/activity_horizontal_margin"    android:paddingTop="@dimen/activity_vertical_margin"    android:paddingBottom="@dimen/activity_vertical_margin"    tools:context=".MainActivity"    android:orientation="vertical">

    <TextView        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:layout_marginTop="10dp"        android:text="@string/text_tvFood" />

    <Spinner        android:id="@+id/spFood"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:entries="@array/food_array" />

    <TextView        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:layout_marginTop="10dp"        android:text="@string/text_tvPlace" />

    <Spinner        android:id="@+id/spPlace"        android:layout_width="match_parent"        android:layout_height="wrap_content" />

    <TextView        android:id="@+id/tvMessage"        android:layout_width="match_parent"        android:layout_height="60dp"        android:layout_marginTop="30dp"        android:background="#00FFFF"        android:padding="10dp"        android:textAppearance="?android:attr/textAppearanceMedium" />

</LinearLayout>


==========================================================================

main.java

==========================================================================


public class MainActivity extends AppCompatActivity {

    private TextView tvMessage;

    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        findViews();
    }

    private void findViews() {
        tvMessage = (TextView) findViewById(R.id.tvMessage);
        Spinner spFood = (Spinner) findViewById(R.id.spFood);
        spFood.setSelection(0, true);

        // 內容已經在這裡指定了 android:entries="@array/food_array"

        // 註冊 setOnItemSelectedListener監聽器....當使用者改變選項會呼叫onItemSelected()
spFood.setOnItemSelectedListener(listener); Spinner spPlace = (Spinner) findViewById(R.id.spPlace); String[] places = {"Australia", "U.K.", "Japan", "Thailand"};
         // 呼叫ArrayApapter 建構式以建立選項的內容與樣式...選項的內容來自於places 字串陣列;  
         //  樣式則套用系統內建的android.R.layout.simple_spinner_item

        ArrayAdapter<String> adapterPlace = new ArrayAdapter<>(this,
                android.R.layout.simple_spinner_item, places);
        
       
        adapterPlace.setDropDownViewResource(
                   android.R.layout.simple_spinner_dropdown_item);
        spPlace.setAdapter(adapterPlace);
        spPlace.setSelection(0, true);
        spPlace.setOnItemSelectedListener(listener);
    }

    Spinner.OnItemSelectedListener listener = new Spinner.OnItemSelectedListener() {
        @Override        public void onItemSelected(
                AdapterView<?> parent, View view, int pos, long id) {
            tvMessage.setText(parent.getItemAtPosition(pos).toString());
        }

        @Override        public void onNothingSelected(AdapterView<?> parent) {
            tvMessage.setText("Nothing selected!");
        }
    };
}


ScrollViewDemo





main.xml

宣告一個Scroll view...  然後裡面用一個linear layout

====================================================


<LinearLayout 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:orientation="vertical"    android:paddingLeft="@dimen/activity_horizontal_margin"    android:paddingRight="@dimen/activity_horizontal_margin"    android:paddingTop="@dimen/activity_vertical_margin"    android:paddingBottom="@dimen/activity_vertical_margin"    tools:context=".MainActivity">

    <LinearLayout        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:orientation="horizontal"   // 水平方向        android:padding="6dp">

        <Button            android:id="@+id/btAdd"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:onClick="onAddClick"            android:text="@string/text_btAdd" />

        <TextView            android:id="@+id/tvCount"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:layout_marginLeft="50dp" />
    </LinearLayout>

    <ScrollView        android:id="@+id/scrollView"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:padding="6dp">

        <LinearLayout            android:id="@+id/linearLayout"            android:layout_width="match_parent"            android:layout_height="wrap_content"            android:padding="6dp"            android:orientation="vertical" />

    </ScrollView>
</LinearLayout>

==================================================================================


main.java

=====================================================================================


public class MainActivity extends AppCompatActivity {

    private TextView tvCount;
    private ScrollView scrollView;
    private LinearLayout linearLayout;
    private int count = 0;
    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        findViews();
        tvCount.setText(String.valueOf(count));   //  初始值
    }

    private void findViews() {
        tvCount = (TextView) findViewById(R.id.tvCount);
        scrollView = (ScrollView) findViewById(R.id.scrollView);
        linearLayout = (LinearLayout) findViewById(R.id.linearLayout);  // scrollview 裡面的linear layout
    }


    public void onAddClick(View view) {
        count++;
        tvCount.setText(String.valueOf(count));  //  更新目前的 count

        TextView textView = new TextView(this);    // 宣告並初始一個Textview
        textView.setText(String.valueOf(count));    //  textview set text
        linearLayout.addView(textView);            //   增加到linearlayout

        scrollView.post(new Runnable() {               //  更新scroll view.. 使用 Runnable
            @Override            public void run() {
                scrollView.fullScroll(View.FOCUS_DOWN);
            }
        });
    }
}


Layoutdemo


==============================================

main.xml



<?xml version="1.0" encoding="utf-8"?><LinearLayout 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:orientation="vertical"    android:paddingLeft="@dimen/activity_horizontal_margin"    android:paddingRight="@dimen/activity_horizontal_margin"    android:paddingTop="@dimen/activity_vertical_margin"    android:paddingBottom="@dimen/activity_vertical_margin"    tools:context=".MainActivity">

    <!--Child views are drawn in a stack, with the most recently added child on top.-->    <FrameLayout        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:padding="12dp"        android:background="#DDFFDD">

        <ImageView            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:onClick="onImageG1Click"            android:src="@drawable/cat" />

        <ImageView            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:onClick="onImageG1Click"            android:src="@drawable/mouse" />

        <ImageView            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:onClick="onImageG1Click"            android:src="@drawable/dog" />

    </FrameLayout>

    <LinearLayout        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:padding="12dp"        android:background="#DDDDFF"        android:orientation="horizontal">

        <ImageView            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:onClick="onImageG2Click"            android:src="@drawable/cat" />

        <ImageView            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:onClick="onImageG2Click"            android:src="@drawable/mouse" />

        <ImageView            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:onClick="onImageG2Click"            android:src="@drawable/dog" />
    </LinearLayout>

    <Button        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:layout_marginTop="12dp"        android:text="@string/text_btReset"        android:id="@+id/btReset"        android:layout_gravity="center_horizontal"        android:onClick="onResetClick" />

</LinearLayout>



=========================================================================
main.java

=========================================================================

public class MainActivity extends AppCompatActivity {

    List<View> views;
    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        views = new ArrayList<>();
    }

    // 被點擊的ImageView 會被當作參數傳遞給view... 呼叫setVisibility() 將其設定為隱藏...但乃占空間.... 
    將view 加入views內方便之後按下Reset 按鈕後還原成顯示狀態

    // the clicked image becomes invisible    public void onImageG1Click(View view) {
        view.setVisibility(View.INVISIBLE);
        views.add(view);
    }

    // the clicked image becomes invisible and doesn't take any space    public void onImageG2Click(View view) {
        view.setVisibility(View.GONE);
        views.add(view);
    }

    // all the invisible images become visible    public void onResetClick(View view) {
        if (views != null && views.size() > 0) {
            for (View v : views) {
                v.setVisibility(View.VISIBLE);
            }
        }
    }
}

uidemo

Ref :  Android App 開發教戰手冊  ch4

EditText 的輸入type 有很多種...


android:inputType="textPassword"   ->  密碼



android:inputType="phone"         ->   phone

android:inputType="number"         ->   數字





<EditText    android:id="@+id/etUser"    android:hint="@string/hint_etUser"    android:layout_width="match_parent"    android:layout_height="wrap_content"    android:layout_marginTop="34dp" />

<EditText    android:id="@+id/etPassword"    android:hint="@string/hint_etPassword"    android:inputType="textPassword"    android:layout_width="match_parent"    android:layout_height="wrap_content" />

<EditText    android:id="@+id/etPhone"    android:hint="@string/hint_etPhone"    android:inputType="phone"    android:layout_width="match_parent"    android:layout_height="wrap_content" />

<EditText    android:id="@+id/etAge"    android:hint="@string/hint_etAge"    android:inputType="number"    android:layout_width="match_parent"    android:layout_height="wrap_content" />

<Button    android:id="@+id/btSubmit"    android:onClick="onSubmitClick"    android:text="@string/text_btSubmit"    android:layout_width="match_parent"    android:layout_height="wrap_content"    android:layout_marginTop="10dp" />

<Button    android:id="@+id/btClear"    android:text="@string/text_btClear"    android:layout_width="match_parent"    android:layout_height="wrap_content" />

<TextView    android:id="@+id/tvMessage"    android:lines="5"    android:layout_width="match_parent"    android:layout_height="wrap_content"    android:layout_marginTop="10dp"    android:background="#DDDDFF" />



========================================================
main.java   

get string 可以這樣用

 String user = etUser.getText().toString().trim();

.trim() 是去除不必要的空白


========================================================


@Overrideprotected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    findViews();
}

private void findViews() {
    etUser = (EditText) findViewById(R.id.etUser);
    etPassword = (EditText) findViewById(R.id.etPassword);
    etPhone = (EditText) findViewById(R.id.etPhone);
    etAge = (EditText) findViewById(R.id.etAge);
    btClear = (Button) findViewById(R.id.btClear);
    tvMessage = (TextView) findViewById(R.id.tvMessage);

    btClear.setOnClickListener(new View.OnClickListener() {
        @Override        public void onClick(View v) {
            etUser.setText(null);
            etPassword.setText(null);
            etPhone.setText(null);
            etAge.setText(null);
            tvMessage.setText(null);
            Toast.makeText(
                    MainActivity.this,
                    R.string.msg_ClearAllFields,
                    Toast.LENGTH_SHORT            ).show();
        }
    });
}

public void onSubmitClick(View view) {
    String user = etUser.getText().toString().trim();
    String password = etPassword.getText().toString().trim();
    String phone = etPhone.getText().toString().trim();
    String age = etAge.getText().toString().trim();
    String text = "";
    text += "user name = " + user + "\n";
    text += "password = " + password + "\n";
    text += "phone number = " + phone + "\n";
    text += "age = " + age + "\n";
    tvMessage.setText(text);
}