2015年5月9日 星期六

Android應用程式縮小後在背景執行

要做一個Service要先了解,service無法自己啟動,必須要靠startService()才能啟動。

同樣的啟動後也必須要使用stopService()關閉。

在這邊需要注意的有幾點

1) startService()

2) stopService()

3) AndroidManiFest.xml增加service權限

第一點為開啟service必要條件,當然你要new一個intent
所以就是:
Intent intent = new Intent(MainActivity.this,service_class.class);
startService(intent);

MainActivity為你目前的class,service_class則是另外開的java檔(那邊則是寫service做的事情)

第二點跟第一點很類似,只有差在start / stop的差別
Intent intent = new Intent(MainActivity.this,service_class.class);
stopService(intent);
第三點就是你需要在Android ManiFest.xml裡面新增權限
  <service android:name="service_class"></service>

Intent傳遞資料

傳遞資料A到B方法1
A.class
                //new一個intent物件,並指定Activity切換的class
                Intent intent = new Intent();
                intent.setClass(MainActivity.this, B.class);
                intent.putExtra("name", name);//可放所有基本類別
                //切換Activity
                startActivity(intent);
B.class
Intent intent = this.getIntent();
//取得傳遞過來的資料   
String name = intent.getStringExtra("name");  
傳遞資料A到B方法2
A.class
//new一個intent物件,並指定Activity切換的class
Intent intent = new Intent();
intent.setClass(A.this,B.class);
 
//new一個Bundle物件,並將要傳遞的資料傳入
Bundle bundle = new Bundle();
bundle.putDouble("age",age );//傳遞Double
bundle.putString("name",name);//傳遞String
 
//將Bundle物件傳給intent
intent.putExtras(bundle);
 
//切換Activity
startActivity(intent);
B.class
Bundle bundle = getIntent().getExtras();  
String name = bundle.getString("name");
double age = bundle.getDouble("age");
A到B,B傳到A
A.class
Intent intent = new Intent(A.this,B.class);
//requestCode(識別碼) 型別為 int ,從B傳回來的物件將會有一樣的requestCode
startActivityForResult(intent,requestCode);
B.class
Intent intent = getIntent();
Bundle bundle = new Bundle();
bundle.putString("name",name);  
intent.putExtras(bundle); 
setResult(requestCode, intent); //requestCode需跟A.class的一樣 
B.this.finish();

download: 參考資料:
http://cookiesp.pixnet.net/blog/post/84190702-android-intent%26bundle-%E5%82%B3%E9%81%9E%E8%B3%87%E6%96%99

2015年5月8日 星期五

ListView加載聯絡人資料

製作一個清單的XML
main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >
    <ListView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/listview" />

</RelativeLayout>
可以利用這樣的方法取得電話與人名
Cursor cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
Final_code
package com.givemepass.providercontactdemo;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.SimpleAdapter;

public class ProviderContactDemoActivity extends Activity {
    /**
     * Called when the activity is first created.
     */
    private ListView listView;
    private SimpleAdapter adapter;
    private static final String NAME = "name";
    private static final String NUMBER = "number";
    private Map contactsMap;
    ArrayList> contactsArrayList;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        listView = (ListView) findViewById(R.id.listview);

        contactsArrayList = new ArrayList>();
        getPhoneBookData();
        adapter = new SimpleAdapter(this,
                contactsArrayList,
                android.R.layout.simple_list_item_2, new String[]{NAME,
                NUMBER}, new int[]{android.R.id.text1,
                android.R.id.text2});
        listView.setAdapter(adapter);
    }

    public void getPhoneBookData() {
  /*取得聯絡人姓名和電話*/
        Cursor cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
        String phoneNumber = "";
        String name = "";

        while (cursor.moveToNext()) {
            contactsMap = new HashMap();

            name = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
            phoneNumber = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
            contactsMap.put(NAME, name);
            contactsMap.put(NUMBER, phoneNumber);
            contactsArrayList.add(contactsMap);
        }
    }
}
參考資料:
http://givemepass.blogspot.tw/2011/11/phone-book-contentresolver.html
Download_code:
http://uploadingit.com/file/st6wlycv8dxdanmr/ProviderContactDemo.rar

2015年5月7日 星期四

ListView電話簿找聯絡人

main.xml//主頁
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" android:layout_height="match_parent">

    <LinearLayout
        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="New Text"
            android:id="@+id/txt_print" />

        <Button
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="New Button"
            android:id="@+id/button" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="New Text"
            android:id="@+id/txt_add_contact" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="New Text"
            android:id="@+id/txt_print_name" />
    </LinearLayout>

</LinearLayout>
listview_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <EditText
        android:id="@+id/search"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" >

        <requestFocus />
    </EditText>

    <ListView
        android:id="@+id/listview"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_below="@+id/search" />

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="New Text"
        android:id="@+id/textView"
        android:background="#ffacff89" />

</RelativeLayout>
listview_item.xml//清單裡載入的項目
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <TextView
        android:id="@+id/txt_name"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:background="#ff91c6ff" />

    <TextView
        android:id="@+id/txt_number"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/txt_name" />

</RelativeLayout>
Main.java
package com.androidbegin.filterlistviewtutorial;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

/**
 * Created by win7 on 2015/3/31.
 */
public class Main extends Activity {
    private Button button;
    private TextView textView,txt_print_name,txt_add_contact;
    String name;
    String number;
    public void onCreate(Bundle savedInstance){
        super.onCreate(savedInstance);
        setContentView(R.layout.main);
        textView=(TextView)findViewById(R.id.txt_print);
        txt_add_contact=(TextView)findViewById(R.id.txt_add_contact);
        txt_print_name=(TextView)findViewById(R.id.txt_print_name);
        // Retrieve data from MainActivity on item click event
        Intent i = getIntent();
        // Get the results of rank
        name = i.getStringExtra("name");//檢索來自意圖擴展的數據
        // Get the results of country
        number = i.getStringExtra("number");//檢索來自意圖擴展的數據

        txt_add_contact.setText(name);
        txt_print_name.setText(number);

        button=(Button)findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent_select_contact = new Intent(Main.this,MainActivity.class);
                startActivity(intent_select_contact);

            }
        });
    }

}
MainActivity.java
package com.androidbegin.filterlistviewtutorial;

import android.app.Activity;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.Locale;

public class MainActivity extends Activity {

    // Declare Variables
    ListView list;
    ListViewAdapter adapter;
    EditText editsearch;
    TextView textView;
    String[] name;//儲存連絡人名子
    String[] number;//儲存連絡人電話
    int c = 0;
    int totalpeople = 0;
    ArrayList arraylist = new ArrayList();

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.listview_main);
        textView = (TextView) findViewById(R.id.textView);
        /*取得聯絡人姓名和電話*/
        getPhoneBookData();

        String s = String.valueOf(totalpeople);
        textView.setText(s);
        list = (ListView) findViewById(R.id.listview);
        // Pass results to ListViewAdapter Class
        adapter = new ListViewAdapter(this, arraylist);
        // Binds the Adapter to the ListView
        list.setAdapter(adapter);
        // Locate the EditText in listview_main.xml
        editsearch = (EditText) findViewById(R.id.search);
        // Capture Text in EditText
        editsearch.addTextChangedListener(new TextWatcher() {

            @Override
            public void afterTextChanged(Editable arg0) {
                // TODO Auto-generated method stub
                String text = editsearch.getText().toString().toLowerCase(Locale.getDefault());
                adapter.filter(text);
            }

            @Override
            public void beforeTextChanged(CharSequence arg0, int arg1,
                                          int arg2, int arg3) {
                // TODO Auto-generated method stub
            }

            @Override
            public void onTextChanged(CharSequence arg0, int arg1, int arg2,
                                      int arg3) {
                // TODO Auto-generated method stub
            }
        });
    }

    public void getPhoneBookData() {

        Cursor cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
        totalpeople = cursor.getCount();//聯絡人總人數
        name = new String[totalpeople];
        number = new String[totalpeople];

        while (cursor.moveToNext()) {
            name[c] = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
            number[c] = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
            c++;
            if (totalpeople == c) {
                for (int i = 0; i < name.length; i++) {
                    WorldPopulation wp = new WorldPopulation(name[i], number[i]);
                    // Binds all strings into an array
                    arraylist.add(wp);//把資料加入WorldPopulation創建的wp
                }
                break;
            }

        }

    }

}
ListViewAdapter.java
package com.androidbegin.filterlistviewtutorial;

import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

public class ListViewAdapter extends BaseAdapter {

    // Declare Variables
    Context mContext;
    LayoutInflater inflater;
    private List worldpopulationlist = null;
    private ArrayList arraylist;

    public ListViewAdapter(Context context, List worldpopulationlist) {
        mContext = context;
        this.worldpopulationlist = worldpopulationlist;
        inflater = LayoutInflater.from(mContext);
        this.arraylist = new ArrayList();
        this.arraylist.addAll(worldpopulationlist);
    }

    public class ViewHolder {
        TextView txt_name;
        TextView txt_number;

    }

    @Override
    public int getCount() {
        return worldpopulationlist.size();
    }//worldpopulationlist資料的數量

    @Override
    public WorldPopulation getItem(int position) {
        return worldpopulationlist.get(position);//worldpopulationlist資料的位置
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    public View getView(final int position, View view, ViewGroup parent) {
        final ViewHolder holder;
        if (view == null) {
            holder = new ViewHolder();
            view = inflater.inflate(R.layout.listview_item, null);
            // Locate the TextViews in listview_item.xml
            holder.txt_name = (TextView) view.findViewById(R.id.txt_name);
            holder.txt_number = (TextView) view.findViewById(R.id.txt_number);
            view.setTag(holder);
        } else {
            holder = (ViewHolder) view.getTag();
        }
        // Set the results into TextViews
        holder.txt_name.setText(worldpopulationlist.get(position).getName());
        holder.txt_number.setText(worldpopulationlist.get(position).getNumber());

        // Listen for ListView Item Click
        view.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // Send single item click data to SingleItemView Class
                Intent intent = new Intent(mContext, Main.class);
                // Pass all data rank
                intent.putExtra("name", (worldpopulationlist.get(position).getName()));
                // Pass all data country
                intent.putExtra("number", (worldpopulationlist.get(position).getNumber()));
                mContext.startActivity(intent);
            }
        });

        return view;
    }

    // Filter Class
    public void filter(String charText) {
        charText = charText.toLowerCase(Locale.getDefault());
        worldpopulationlist.clear();
        if (charText.length() == 0) {
            worldpopulationlist.addAll(arraylist);
        } else {
            for (WorldPopulation wp : arraylist) {
                if (wp.getName().toLowerCase(Locale.getDefault()).contains(charText)) {
                    worldpopulationlist.add(wp);
                }
            }
        }
        notifyDataSetChanged();

    }

}
WorldPopulatio.java
package com.androidbegin.filterlistviewtutorial;
public class WorldPopulation {
 private String name;
 private String number;

 public WorldPopulation(String rank, String country) {
  this.name = rank;
  this.number = country;
 }
 public String getName() {
  return this.name;
 }
 public String getNumber() {
  return this.number;
 }

}
參考資料:
http://cookiesp.pixnet.net/blog/post/84190702-android-intent%26bundle-%E5%82%B3%E9%81%9E%E8%B3%87%E6%96%99%28%E5%8C%85%E5%90%AB%E5%82%B3%E9%81%9E%E8%87%AA%E5%AE%9A%E7%BE%A9%E7%89%A9
http://www.androidhive.info/2012/09/android-adding-search-functionality-to-listview/

2015年3月13日 星期五

Android Call Phone

activity_main.xml
<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: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:orientation="vertical"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent">

        <EditText
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:inputType="textPersonName"
            android:text=""
            android:ems="10"
            android:id="@+id/edt_PhoneNumber"
             />

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="New Button"
            android:id="@+id/btn_CallPhone" />
    </LinearLayout>

</RelativeLayout>

MainActivity.java
package com.example.win7.make_a_call;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;


public class MainActivity extends Activity {
    private EditText edt_PhoneNumber;
    private Button btn_CallPhone;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        edt_PhoneNumber=(EditText)findViewById(R.id.edt_PhoneNumber);
        btn_CallPhone=(Button)findViewById(R.id.btn_CallPhone);
        btn_CallPhone.setOnClickListener(new Button.OnClickListener(){

            @Override
            public void onClick(View view) {
                try {
                    /*getText()取得使用者輸入號碼*/
                    String phonenumber = edt_PhoneNumber.getText().toString();
                    //建立一個Intent並且在建構式中加入action.CALL字串用來設定所建立的Intent物件是用來打電話
                    //第二個參數使用Uri.parse()方法,並將使用者輸入號碼傳入
                    Intent intent_CallPhone = new Intent("android.intent.action.CALL", Uri.parse("tel:"+phonenumber));
                    startActivity(intent_CallPhone);
                    edt_PhoneNumber.setText("");
                }catch (Exception ex){
                    ex.printStackTrace();
                }

            }
            //start
        });
    }
}



AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.win7.make_a_call" >

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            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-permission android:name="android.permission.CALL_PHONE"></uses-permission>
</manifest>

2015年3月11日 星期三

Android控制項Toast and Notification

Toast用來快顯訊息,顯示後自行消失
Notification用來顯示裝態列訊息

activity_main.xml

<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: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:orientation="vertical"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_alignParentTop="true"
        android:layout_alignParentStart="true">

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Toast Demo"
            android:id="@+id/btn_Toast" />

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Notification Demo"
            android:id="@+id/btn_Notification" />
    </LinearLayout>
</RelativeLayout>
MainActivity.java
package com.example.win7.toast_and_notification;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;


public class MainActivity extends Activity {
    private Button btn_Toast,btn_Notification;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        setupViewComent();
    }
    private void setupViewComent(){
        btn_Toast=(Button)findViewById(R.id.btn_Toast);
        btn_Toast.setOnClickListener(ocl_Toast);

        btn_Notification=(Button)findViewById(R.id.btn_Notification);
        btn_Notification.setOnClickListener(ocl_Notification);
    }

   private Button.OnClickListener ocl_Toast = new Button.OnClickListener(){

       @Override
       public void onClick(View view) {
           setTitle("Toast Demo");
           Intent intent_Toast = new Intent(MainActivity.this,SampleToast.class);
           startActivity(intent_Toast);
       }
   };

    private Button.OnClickListener ocl_Notification = new Button.OnClickListener(){

        @Override
        public void onClick(View view) {
            setTitle("Notification");
            Intent intent_Notification = new Intent(MainActivity.this,SampleNotification.class);
            startActivity(intent_Notification);
        }
    };
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

sample_toast.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" android:layout_height="match_parent">

    <LinearLayout
        android:orientation="vertical"
        android:layout_width="wrap_content"
        android:layout_height="match_parent">

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="短時間顯示Toast"
            android:id="@+id/btn_Display_Short" />

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="長時間顯示Toast"
            android:id="@+id/btn_Display_Long" />
    </LinearLayout>
</LinearLayout>
toast_content.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" android:layout_height="match_parent"
    android:weightSum="1">


    <FrameLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent">

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

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/txv_Toast_Cntent"
            android:layout_gravity="center_vertical" />
    </FrameLayout>

</LinearLayout>
SampleToast.java

package com.example.win7.toast_and_notification;

import android.app.Activity;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

/**
 * Created by win7 on 2015/3/9.
 */
public class SampleToast extends Activity {
    private Button btn_Display_Short,btn_Display_Long;
    private TextView txv_Toast_Cntent;
    private Toast tot_Toast;
    private LayoutInflater lia_LayoutInflater;
    private NotificationManager nom_notificationManager;
    private static int NOTIFICATIONS_ID = R.layout.sample_toast;
    private View viw_InflateView;
    private PendingIntent pei_pendingIntent;
    public void onCreate(Bundle savedInsatnceState){
        super.onCreate(savedInsatnceState);
        setContentView(R.layout.sample_toast);
        setupViewComent();
    }
    private void setupViewComent(){
        btn_Display_Short=(Button)findViewById(R.id.btn_Display_Short);
        btn_Display_Short.setOnClickListener(ocl_Display_Short);

        btn_Display_Long=(Button)findViewById(R.id.btn_Display_Long);
        btn_Display_Long.setOnClickListener(ocl_Display_Long);
    }
    private Button.OnClickListener ocl_Display_Short =new Button.OnClickListener(){

        @Override
        public void onClick(View view) {
            setTitle("短時間顯示Toast");
            DisplayToast(Toast.LENGTH_SHORT);
        }
    };

    private Button.OnClickListener ocl_Display_Long =new Button.OnClickListener(){

        @Override
        public void onClick(View view) {
            setTitle("長時間顯示Toast");
            DisplayToast(Toast.LENGTH_LONG);
        }
    };
    /*定義顯示Toasr快顯方法*/
    protected void DisplayToast(int type){
        /*使用InflateView()方 法,傳入layout的id取得Toasr的View物件參考*/
        viw_InflateView = InflateView(R.layout.toast_content);
        txv_Toast_Cntent=(TextView)viw_InflateView.findViewById(R.id.txv_Toast_Cntent);
        txv_Toast_Cntent.setText("善意提醒你長時間看螢幕傷眼睛");
        /*文字訊息設定好後,建立在Toast物件上呼叫setView()將剛剛自準備好的View物件指派給Toast物件*/
        tot_Toast = new Toast(this);
        tot_Toast.setView(viw_InflateView);
        /*使用傳入的type型態*/
        tot_Toast.setDuration(type);
        tot_Toast.show();
    }
    /*定義InflateView()方法,使用傳入的resource id以取得layout所定義的view物件*/
    private View InflateView(int resource) {
        lia_LayoutInflater =(LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        return lia_LayoutInflater.inflate(resource,null);
    }
}
sample_notification.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" android:layout_height="match_parent">

    <LinearLayout
        android:orientation="vertical"
        android:layout_width="wrap_content"
        android:layout_height="match_parent">

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="電量不足,請充電!"
            android:id="@+id/btn_LowBattery" />

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="充電中"
            android:id="@+id/btn_InCharging" />

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="使用AC電源中"
            android:id="@+id/btn_ACAdapter" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="進階Notification"
            android:id="@+id/txv_AdvancedNotification" />

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="只發出聲音"
            android:id="@+id/btn_Voice" />

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="只產生振動的Notification"
            android:id="@+id/btn_Vibrate" />

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="同時發出聲音也產生震動"
            android:id="@+id/btn_VibrateAndVoice" />

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="回覆初始的Notification"
            android:id="@+id/btn_Resore" />
    </LinearLayout>

</LinearLayout>
SampleNotification.java
package com.example.win7.toast_and_notification;

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

/**
 * Created by win7 on 2015/3/9.
 */
public class SampleNotification extends Activity {
    private Button btn_LowBattery,btn_InCharging,btn_ACAdapter;
    private Button btn_Voice,btn_Vibrate,btn_VibrateAndVoice,btn_Resore;
    /*取得notification layout的id*/
    private static int NOTIFICATIONS_ID = R.layout.sample_notification;
    private NotificationManager nim_notificationManager;
    private PendingIntent pei_pendingIntent;
    private String s_Title;
    private String s_Content;
    public void onCreate(Bundle savedInstanceState ){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.sample_notification);
        setupViewComent();
        /*呼叫Context.getSystemService()方法取得NotificationManager實體參考*/
        nim_notificationManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);

    }
    private void setupViewComent(){

        btn_LowBattery=(Button)findViewById(R.id.btn_LowBattery);
        btn_LowBattery.setOnClickListener(new Button.OnClickListener(){

            @Override
            public void onClick(View view) {
                setStatus("電量不足","電源狀態","電量不足,請充電",R.drawable.battery);
               // txv_AdvancedNotification.setText("123");
            }
        });

        btn_InCharging=(Button)findViewById(R.id.btn_InCharging);
        btn_InCharging.setOnClickListener(new Button.OnClickListener(){

            @Override
            public void onClick(View view) {
                setStatus("充電中","電源狀態","充電中",R.drawable.battery);
            }
        });
        btn_ACAdapter=(Button)findViewById(R.id.btn_ACAdapter);
        btn_ACAdapter.setOnClickListener(new Button.OnClickListener(){

            @Override
            public void onClick(View view) {
                setStatus("使用AC電源中","電源狀態","使用AC電源中",R.drawable.battery);
            }
        });
        btn_Voice=(Button)findViewById(R.id.btn_Voice);
        btn_Voice.setOnClickListener(new Button.OnClickListener(){

            @Override
            public void onClick(View view) {
                Initial(Notification.DEFAULT_SOUND);
            }
        });
        btn_Vibrate=(Button)findViewById(R.id.btn_Vibrate);
        btn_Vibrate.setOnClickListener(new Button.OnClickListener(){

            @Override
            public void onClick(View view) {
                Initial(Notification.DEFAULT_VIBRATE);
            }
        });
        btn_VibrateAndVoice=(Button)findViewById(R.id.btn_VibrateAndVoice);
        btn_VibrateAndVoice.setOnClickListener(new Button.OnClickListener(){

            @Override
            public void onClick(View view) {
                Initial(Notification.DEFAULT_ALL);
            }
        });
        btn_Resore=(Button)findViewById(R.id.btn_Resore);
        btn_Resore.setOnClickListener(new Button.OnClickListener(){

            @Override
            public void onClick(View view) {
                nim_notificationManager.cancel(NOTIFICATIONS_ID);
            }
        });

    }
    private void setStatus(String tickerText,String title,String content,int drawable){
        /*建立一個Notifcation*/
        Notification noc_Notification = new Notification(drawable,tickerText,System.currentTimeMillis());
        /*建立一個PendingIntent*/
        PendingIntent pei_pendingIntent =  PendingIntent.getActivity(this,0,new Intent(this,MainActivity.class),0);
        /*呼叫setLatestEventInfo來配置Notification的外觀*/
        noc_Notification.setLatestEventInfo(this,title,content,pei_pendingIntent);
        /*呼叫Notification Manager的notify()方法,傳入Notification物件完成呼叫*/
        nim_notificationManager.notify(NOTIFICATIONS_ID,noc_Notification);
    }

     private void Initial(int defaults){
         /*呼叫靜態方法getActivity()取得PendingIntent實體*/
        pei_pendingIntent = PendingIntent.getActivity(this,0,new Intent(this,MainActivity.class),0);
        s_Title="電原狀態";
        s_Content="電量不足,請充電";
         /*建立一個Notifcation*/
        final Notification notification = new Notification(R.mipmap.battery,s_Content,System.currentTimeMillis());
         /*呼叫setLatestEventInfo()方法設定Notification的Title與Content,注意這裡主要將建立PendingIntent物件傳入*/
        notification.setLatestEventInfo(this,s_Title,s_Content,pei_pendingIntent);
         /*指派Notification的形態,DEFAULT_SOUND(聲音),DEFAULT_VIBRATE(震動),DEFAULT_LIGHT(閃光)*/
        notification.defaults=defaults;
         /*呼叫NotificationManager的notify()方法將Notification物件傳入來啟動Notification*/
        nim_notificationManager.notify(NOTIFICATIONS_ID,notification);
     }
}

2015年3月8日 星期日

Android控制項Dialog

對話框,所有應用程式或系統程式要回應使用者的主要方式,好的對話框可以讓使用者非常清楚應用程式目前狀態。

重點
建議在設計應用程式之初,獨立一個資料夾去設計並且加入對話框,每個地方需要使用到對話框的時候乎叫共同的程式碼,如此一來整個應用程式有統一的對話架構。

activity_main.xml
<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: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:orientation="vertical"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_alignParentTop="true"
        android:layout_alignParentStart="true">

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="基本對話框"
            android:id="@+id/btn_SimpleDialog" />

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="擁有兩個Button的對話框"
            android:id="@+id/btn_DoubleDialog" />

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="擁有三個Button的對話框"
            android:id="@+id/btn_Tripleialog" />

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="進行登入驗證的對話框"
            android:id="@+id/btn_AuthenticationDialog" />

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="顯是進度的對話框 "
            android:id="@+id/btn_ProgressDialog" />
    </LinearLayout>
</RelativeLayout>


authentication_dialog
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" android:layout_height="match_parent">

    <LinearLayout
        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="登入帳號"
            android:id="@+id/username_view" />

        <EditText
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:inputType="textPersonName"
            android:text="Name"
            android:ems="10"
            android:id="@+id/username_edit" />

        <TextView
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="登入密碼"
            android:id="@+id/password_view" />

        <EditText
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:inputType="textPersonName"
            android:text="Name"
            android:ems="10"
            android:id="@+id/password_edit" />

    </LinearLayout>
</LinearLayout>

string.xml
<resources>
    <string name="app_name">Dialog</string>

    <string name="hello_world">Hello world!</string>
    <string name="action_settings">Settings</string>
    <string name="alert_simple_dialog_title">這是個提示框。請按確定返回</string>
    <string name="alert_double_dialog_title">這是個提示框。請任點選下列按鈕返回</string>
    <string name="alert_double_dialog_message">是否退出遊戲</string>
    <string name="alert_double_dialog_context">確定要退出遊戲請點選確定按鈕。如果要繼續遊戲請點選取消按鈕。如果想要了解最高分可以點選最高紀錄按鈕</string>
    <string name="alert_double_dialog_ok">確定</string>
    <string name="alert_double_dialog_hide">隱藏</string>
    <string name="alert_double_dialog_something">最高紀錄</string>
    <string name="alert_double_dialog_cancel">取消</string>
    <string name="alert_double_dialog_entry">請輸入</string>
</resources>

MainActivity.java
package com.example.win7.dialog;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;


public class MainActivity extends Activity {
    /*設定5個int來作為五個對話框識別,使用Menu來產生*/
    private static final int Dialog1 = Menu.FIRST;
    private static final int Dialog2 = Menu.FIRST+1;
    private static final int Dialog3 = Menu.FIRST+2;
    private static final int Dialog4 = Menu.FIRST+3;
    private static final int Dialog5 = Menu.FIRST+4;
    private Button btn_SimpleDialog,btn_DoubleDialog,btn_Tripleialog,btn_AuthenticationDialog,btn_ProgressDialog;
    private AlertDialog.Builder alb_SimpleDialog;
    private AlertDialog.Builder alb_DoubleDialog;
    private AlertDialog.Builder alb_Tripleialog;
    private AlertDialog.Builder alb_AuthenticationDialog;
    private LayoutInflater lai_AuthenticationDialog;
    private ProgressDialog prd_ProgressDialog;
    /*覆寫Activity的onCreateDialog方法,當成是執行到Activity的showDialog()方法時
    * onCreateDialog()方法會自動乎叫並且傳入id*/
    protected Dialog onCreateDialog(int id){
        switch (id){
            case Dialog1:
                setTitle("目前點選是:基本對話框");
            /*呼叫BuildDialog()方法來建立對話框*/
                return BuildDialog1(MainActivity.this);
            case Dialog2:
                setTitle("目前點選是:擁有兩個Button的對話框");
                return BuildDialog2(MainActivity.this);
            case Dialog3:
                setTitle("目前點選是:擁有三個Button的對話框");
                return BuildDialog3(MainActivity.this);
            case Dialog4:
                setTitle("目前點選是:進行登入對話框");
                return BuildDialog4(MainActivity.this);
            case Dialog5:
                setTitle("目前點選是:顯示進度");
                return BuildDialog5(MainActivity.this);
        }
        return null;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        /*showDialog()方法建立對話框視窗*/
        setupViewComponent();
     }
    private void setupViewComponent(){
        btn_SimpleDialog=(Button)findViewById(R.id.btn_SimpleDialog);
        btn_SimpleDialog.setOnClickListener(Go_SimpleDialog);

        btn_DoubleDialog=(Button)findViewById(R.id.btn_DoubleDialog);
        btn_DoubleDialog.setOnClickListener(Go_DoubleDialog);

        btn_Tripleialog=(Button)findViewById(R.id.btn_Tripleialog);
        btn_Tripleialog.setOnClickListener(Go_Tripleialog);

        btn_AuthenticationDialog=(Button)findViewById(R.id.btn_AuthenticationDialog);
        btn_AuthenticationDialog.setOnClickListener(Go_AuthenticationDialog);

        btn_ProgressDialog=(Button)findViewById(R.id.btn_ProgressDialog);
        btn_ProgressDialog.setOnClickListener(Go_ProgressDialog);
    }
    private Button.OnClickListener Go_SimpleDialog = new Button.OnClickListener(){

        @Override
        public void onClick(View view) {
            showDialog(Dialog1);
        }
    };

    private Button.OnClickListener Go_DoubleDialog = new Button.OnClickListener(){

        @Override
        public void onClick(View view) {
            showDialog(Dialog2);
        }
    };

    private Button.OnClickListener Go_Tripleialog = new Button.OnClickListener(){

        @Override
        public void onClick(View view) {
            showDialog(Dialog3);
        }
    };

    private Button.OnClickListener Go_AuthenticationDialog = new Button.OnClickListener(){

        @Override
        public void onClick(View view) {
            showDialog(Dialog4);
        }
    };

    private Button.OnClickListener Go_ProgressDialog = new Button.OnClickListener(){

        @Override
        public void onClick(View view) {
            showDialog(Dialog5);
        }
    };
    private Dialog BuildDialog1(Context context){
        /*呼叫AlertDialog.Builder()方法建立對話視窗*/
        alb_SimpleDialog = new AlertDialog.Builder(context);
        alb_SimpleDialog.setTitle(R.string.alert_simple_dialog_title);
        alb_SimpleDialog.setIcon(R.mipmap.ic_launcher);
        /*在基本對話框上面配置確定按鈕*/
        alb_SimpleDialog.setPositiveButton(R.string.alert_double_dialog_ok,
            new DialogInterface.OnClickListener(){
                public void onClick(DialogInterface dialog,int whichButton){
                setTitle("點選了基本對話框的確定鍵");
            }
        });
        /*呼叫create()方法將使得對話框實體被建立出來,但是要直到呼叫show()或者showDialog()方法,該對話框式視窗才會顯示出來*/
        return alb_SimpleDialog.create();
    }

    private Dialog BuildDialog2(Context context){
        alb_DoubleDialog = new AlertDialog.Builder(context);
        alb_DoubleDialog.setTitle(R.string.alert_double_dialog_title);
        alb_DoubleDialog.setIcon(R.mipmap.ic_launcher);
        alb_DoubleDialog.setPositiveButton(R.string.alert_double_dialog_ok,
                new DialogInterface.OnClickListener(){
                    public void onClick(DialogInterface dialog,int whichButton){
                        setTitle("點選了有兩個對話框的確定鍵");
                    }
                });
        alb_DoubleDialog.setNegativeButton(R.string.alert_double_dialog_cancel,
                new DialogInterface.OnClickListener(){

                    @Override
                    public void onClick(DialogInterface dialog, int whichButton) {
                        setTitle("點選了有兩個對話框的取消鍵");
                    }
                } );
        return alb_DoubleDialog.create();
    }

    private Dialog BuildDialog3(Context context){
        alb_Tripleialog = new AlertDialog.Builder(context);
        alb_Tripleialog.setTitle(R.string.alert_double_dialog_message);
        alb_Tripleialog.setMessage(R.string.alert_double_dialog_context);
        alb_Tripleialog.setIcon(R.mipmap.ic_launcher);
        alb_Tripleialog.setPositiveButton(R.string.alert_double_dialog_ok,
                new DialogInterface.OnClickListener(){
                    public void onClick(DialogInterface dialog,int whichButton){
                        setTitle("點選了有三個對話框的確定鍵");
                    }
                });
        alb_Tripleialog.setNeutralButton(R.string.alert_double_dialog_something,
                new DialogInterface.OnClickListener(){

                    @Override
                    public void onClick(DialogInterface dialog, int whichButton) {
                        setTitle("點選了有三個對話框的最高分數鍵");
                    }
                } );
        alb_Tripleialog.setNegativeButton(R.string.alert_double_dialog_cancel,
                new DialogInterface.OnClickListener(){

                    @Override
                    public void onClick(DialogInterface dialog, int whichButton) {
                        setTitle("點選了有三個對話框的取消鍵");
                    }
                } );
        return alb_Tripleialog.create();
    }

    private Dialog BuildDialog4(Context context){
        lai_AuthenticationDialog = LayoutInflater.from(this);
        final View textEntryView = lai_AuthenticationDialog.inflate(
                R.layout.authentication_dialog,null);

        alb_AuthenticationDialog = new AlertDialog.Builder(context);
        alb_AuthenticationDialog.setTitle(R.string.alert_double_dialog_entry);
        alb_AuthenticationDialog.setIcon(R.mipmap.ic_launcher);

        alb_AuthenticationDialog.setView(textEntryView);

        alb_AuthenticationDialog.setPositiveButton(R.string.alert_double_dialog_ok,
                new DialogInterface.OnClickListener(){

                    @Override
                    public void onClick(DialogInterface dialog, int whichButton) {
                        setTitle("點選了驗證框的確定鍵");
                    }
                });
        alb_AuthenticationDialog.setNegativeButton(R.string.alert_double_dialog_cancel,
                new DialogInterface.OnClickListener(){

                    @Override
                    public void onClick(DialogInterface dialog, int whichButton) {
                        setTitle("點選了驗證框的取消鍵");
                    }
                });
        return alb_AuthenticationDialog.create();
    }

    private Dialog BuildDialog5(Context context){
        prd_ProgressDialog = new ProgressDialog(context);
        prd_ProgressDialog.setTitle("資料處理中");
        prd_ProgressDialog.setMessage("請稍候....");

        return prd_ProgressDialog;
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}