Showing posts with label Android. Show all posts
Showing posts with label Android. Show all posts

Thursday, May 16, 2013

[Android Nâng Cao] Sử Dụng ViewPager Cho Chuyển Đổi View

Xin chào các bạn, hôm nay mình sẽ hướng dẫn các bạn cách sử dụng ViewPager cho việc chuyển Activity đồng thời khi vuốt tay ( giống như khi vào Play Store các bạn vuốt tay qua trái phải để xem Top Paid apps > Top Free apps....).

I. Giới Thiệu ViewPager

Theo android.com, thì ViewPager là một trình quản lý Layout cho phép người dùng vuốt tay qua trái hay qua bên phải để chuyển sang nội dung của trang khác một cách đồng thời. Điểm khác nhau của ViewPager và cách sử dụng Gesture đó là, gesture sẽ chỉ thực hiện khi người dùng thực hiện xong thao tác vuốt tay, trong khi ViewPager thực hiện chuyển màn hình đồng thời với cử chỉ tay người dùng.

II. Code Now


1. Chuẩn bị

ViewPager không phải là một View chuẩn của Android, mà là một thành phần nằm trong gói android.support.v4.View
Nếu bạn chưa có gói này, có thể cài đặt bằng cách, mở Android SDK Manager->Extra-> tick chọn Android Support package->OK

Sau khi cài đặt, các bạn sẽ thấy có thêm một gói android-support-v4.jar nằm trong project của mình.

2. Code Now

a. Tạo mới một project mới, ví dụ đặt tên là MyApps

b. Thay đổi nội dung file main.xml như bên dưới


Mã:
<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"
tools:context=".MainActivity" >

<android.support.v4.view.ViewPager
android:id="@+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
></android.support.v4.view.ViewPager>

</RelativeLayout>

c. Tạo các layout cho các màn hình khác nhau khi vuốt qua trái, qua phải. Ở đây mình tạo 5 file xml cho 5 màn hình.

- layout_1.xml

Mã:
<?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:orientation="vertical" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Nhip"
android:textAppearance="?android:attr/textAppearanceLarge" />
</LinearLayout>

- layout_2.xml

Mã:
<?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:orientation="vertical" >

<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Song"
android:textAppearance="?android:attr/textAppearanceLarge" />

</LinearLayout>

- layout_3.xml

Mã:
<?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:orientation="vertical" >

<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Di"
android:textAppearance="?android:attr/textAppearanceLarge" />

</LinearLayout>

- layout_4.xml

Mã:
<?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:orientation="vertical" >

<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Dong"
android:textAppearance="?android:attr/textAppearanceLarge" />

</LinearLayout>

- layout_5.xml

Mã:
<?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:orientation="vertical" >

<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Nhipsongdidong.vn"
android:textAppearance="?android:attr/textAppearanceLarge" />

</LinearLayout>

Phần thiết kế màn hình coi như xong.

d. Code

Cũng giống như ListView hay các các thành phần khác, ViewPager bắt buộc phải cần một Adapter để có thể xác định nội dung cần hiển thị lên View.

- Tạo một class mới kế thừa từ PagerAdapter , đặt tên là MyPagerAdapter ( chẳng hạn)

Mã:
public class PagerAdapter extends android.support.v4.view.PagerAdapter{


@Override
public int getCount() {
//Do ở đây mình có 5 Activity nên count trả về là 5
return 5;
}

//Hàm khởi tạo View dùng cho việc hiển thị Activity chính xác
//Hàm có chức năng nôm na như hàm getView thường thấy trong Adapter của ListView, hay chính xác hơn là
//makeView trong ImageSwitcher vậy
@Override
public Object instantiateItem(ViewGroup container, int position) {

LayoutInflater li = (LayoutInflater) container.getContext().
getSystemService(Context.LAYOUT_INFLATER_SERVICE);

int resId=0;
switch(position)
{
case 0:
resId = R.layout.layout_1;
break;
case 1:
resId = R.layout.layout_2;
break;
case 2:
resId = R.layout.layout_3;
break;
case 3:
resId = R.layout.layout_4;
break;
case 4:
resId = R.layout.layout_5;
break;
}

View view = li.inflate(resId, null);
container.addView(view, 0);
return view;
}
//View nào ko còn hiển thị nữa thì xóa đi
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);

}
@Override
public boolean isViewFromObject(View arg0, Object arg1) {
return arg0 == (View)arg1;
}
}

- Activity chính của chương trình.

Mã:
public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
PagerAdapter a = new PagerAdapter();
ViewPager p = (ViewPager) findViewById(R.id.pager);
p.setAdapter(a);
p.setCurrentItem(2);
}

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

}

3. Chạy chương trình và trải nghiệm


Các bạn có thắc mắc có thể góp ý tại đây luôn nhé.
Chúc vui.

Tuesday, April 23, 2013

Nền tảng Android – bức tranh nhìn từ trên cao

Vài nét về quá trình ra đời

Ngày nay, điện thoại di động hiện diện ở khắp mọi nơi. Một người có thể không có máy vi tính nhưng gần như không thể không có điện thoại di động. Điện thoại di động ngày càng thông minh và chúng đang dần thay thế các thiết bị di động cá nhân khác như: đồng hồ, máy tính cầm tay, máy ảnh du lịch, máy nghe nhạc MP3, hoặc các thiết bị có khả năng kết nối internet khác. Rõ ràng thị trường di động là một miếng bánh khổng lồ mà không ai có thể một mình nuốt gọn. Các nhà phát triển cũng cảm thấy sức hấp dẫn mà miếng bánh tỏa ra. Nhưng việc phát triển phần mềm cho các thiết bị di động chưa bao giờ là công việc đơn giản. Có hàng loạt các vấn đề mà các nhà phát triển phần mềm cho thiết bi di động trước kia phải đối mặt:

  • Không có mã nguồn của các nền tảng để giúp họ hình dung ra được cơ chế hoạt động đằng sau đó.
  • Giá thành để phát triển một sản phẩm cao do phải trả phí mua bản quyền API hoặc công cụ phát triển.
  • Vướng phải những ràng buộc hoặc giới hạn nhất định về tính năng khi phát triển kể cả khi họ có giấy phép phát triển.
  • Không có một bộ công cụ phát triển (SDK) nào thực sự dễ dàng cho việc xây dựng ứng dụng di động.
  • Không có một cơ chế phân phối sản phẩm hiệu quả đến người dùng cuối cũng như cách thức cài đặt phần mềm đơn giản lên thiết bị của họ.
Vậy chúng ta cần những gì để tạo ra một thiết bị di động tốt hơn, chi phí phát triển rẻ hơn và tạo ra nhiều lợi ích cho người dùng hơn? Đó chính là câu hỏi mà liên minh Open Handset Alliance gồm trên 40 hãng từ nhiều lĩnh vực liên quan do Google khởi sướng muốn giải đáp. Và câu trả lời của họ chính là hệ sinh thái Android.
Hình 1: Các thành viên trong liên minh OHA
Vào tháng 10-2008, thiết bị đầu tiên chạy Android được Google và HTC phối hợp phát triển đã ra đời với tên gọi G1. Từ đó đến nay, Android đã trải qua nhiều phiên bản với nhiều cải tiến, đã có vô số các thiết bị chạy nền tảng này được tung ra thị trường với mức độ đa dạng chưa từng thấy. Hiện Samsung đang là hãng sản xuất và phân phối hàng đầu các thiết bị chạy Android trên toàn cầu.
Nền tảng Android về cơ bản đáp ứng được những đòi hỏi của OHA:

  • Đó là một nền tảng mở vì vậy các nhà phát triển dễ dàng đào sâu tìm hiểu cũng như dễ dàng tạo ra những thành phần tích hợp hoặc tùy biến cho nó.
  • Ngoài ra cộng đồng phát triển Android còn được hỗ trợ bộ công cụ phát triển (SDK) hoàn chỉnh và dễ sử dụng.
  • Kênh phân phối sản phẩm đến tay người sử dụng rất phong phú cả về phần cứng lẫn phần mềm.
Để đạt được những điều đó yêu cầu Android phải có một kiến trúc mềm dẻo, khai thác được tối đa sức mạnh phần cứng cũng như sự thân thiện trong giao diện người dùng. Tuy vậy, Android không phải là không có những nhược điểm so với những nền tảng cạnh tranh khác, tuy nhiên trong phạm vi bài viết này ta sẽ chỉ mô tả bức tranh về Android như là nó vốn thế.

Nền tảng Android

Android được phát triển dựa trên nhân của Linux nên kế thừa được khả năng quản lý tài nguyên tốt từ hệ thống này. Toàn bộ các ứng dụng được thực thi bởi Dalvik VM, một máy ảo tượng tự như JVM nhưng đã được tối ưu cho thiết bị di động. Các ứng dụng được phát triển trên một framework linh hoạt giúp khai thác các tài nguyên của hệ thống. Hình dưới đây cho thấy bức tranh khái quát về các khối phần mềm trong toàn bộ nền tảng Android.

Hình 2: Các khối cơ bản trong nền tảng Android
Điểm đặc biệt đối với các ứng dụng Android là chúng được phát triển trên cùng một cấp, do vậy khái niệm phần mềm hệ thống và phần mềm thông thường chỉ mang tính chất tương đối. Bất cứ một ứng dụng hệ thống cơ bản nào (như ứng dụng gọi điện, nhắn tin, trình duyệt v.v…) cũng có thể bị thay thế bằng các ứng dụng khác tương tự.

Ngôn ngữ phát triển và cách thức biên dịch

Ngôn ngữ lập trình chính để viết các ứng dụng Android là Java, vì vậy nếu bạn có hứng thú phát triển ứng dụng cho nền tảng này thì hãy đầu tư thời gian vào Java căn bản trước khi bắt tay vào nghiên cứu nó.
Các ứng dụng Android có thể được phân làm hai loại căn cứ vào ngôn ngữ phát triển và cách thức biên dịch:
  • Ứng dụng Dalvik: ứng dụng được viết bằng ngôn ngữ lập trình Java, sử dụng các công cụ trong bộ SDK (Google) và JDK (Oracle) biên dịch và đóng gói thành file .apk trước khi cài đặt vào thiết bị.
Hình 4: Quá trình biên dịch từ mã nguồn Java của loại ứng dụng Dalvik
  • Ứng dụng Native: bên cạnh sử dụng mã nguồn Java, ta có thể sử dụng mã nguồn C/C++ kết hợp để xây dựng ứng dụng nhằm tối ưu hóa và tăng tốc độ thực thi hoặc khai thác các thư viện cấp thấp. Để biên dịch được ứng dụng loại này ngoài bộ SDK bạn phải cần thêm bộ NDK.
Hình 5: Quá trình biên dịch của ứng dụng Native
Mặc dù các ứng dụng Android được phát triển và biên dịch thông qua JDK nhưng không phải tất cả mọi thứ trong JDK đều có thể sử dụng được. Dưới đây là hình ảnh tham khảo về API trong JDK và mức độ được sử dụng trong Android:
Hình 6: Một phần Core Java trong Android

Kiến trúc ứng dụng

Ứng dụng Android được xây dựng từ nhiều thành phần có thể coi là những viên gạch cơ bản trong ứng dụng. Những viên gạch này bao gồm nhiều loại có thể chia thành ba nhóm căn cứ vào mục đích sử dụng:
  1. Những thành phần tạo giao diện người dùng: Activity, View/Widget
  2. Những thành phần cung cấp dịch vụ và tích hợp: Service, Broadcast Receiver/Intent.
  3. Những thành phần cung cấp dữ liệu, tài nguyên và cấu hình của ứng dụng: Content Provider, Resource, ApplicationManifest.
Hình 7: Các thành phần cơ bản trong một ứng dụng Android

1. Những thành phần tạo giao diện người dùng

  • Activity: đây chính là không gian cửa sổ nơi mà mọi thứ được hiển thị ra. Tuy nhiên trên màn hình nhỏ thì mỗi Activity sẽ chiếm trọn màn hình thiết bị, người dùng có thể di chuyển qua lại giữa các Activity thông qua thao tác điều hướng. Về mặt kiến trúc Activity tương đương với ViewModel trong kiến trúc MVVM (Model – View – ViewModel) rất quen thuộc trong các nền tảng lập trình khác như Windows Phone, WPF, JavaFX v.v… Với kiến trúc như vậy mỗi Activity được kết hợp với một Layout mô tả bố cục và các thành phần hiển thị trên đó (các View). Những mô tả này sử dụng ngôn ngữ XML và được đặt trong thư mục /res (xem hình 10).
  • View: đây là các thành phần hiển thị trên Activity như Button, CheckBox v.v… nó được thiết kế theo mô hình Composite giống như tất cả các hệ thống GUI khác. Sơ đồ sau đây thể hiện các lớp cơ bản để dựng giao diện trong Android:
Hình 8: Sơ đồ phân cấp của View
  • Widget: về bản chất đây là một ViewGroup, có khả năng hiển thị trên màn hình Home các thành phần cơ bản trong hệ thống View. Nhưng sự khác biệt này làm cho màn hình Home của Android trở nên rất sinh động và hữu dụng.
Hình 9: Hình ảnh về các widget trên màn hình Home

2. Những thành phần cung cấp dịch vụ và tích hợp

Android cung cấp một loại các thành phần nghiệp vụ cho phép các nhà phát triển khai thác các tính năng phần cứng cũng như các dịch vụ cơ bản của hệ thống để tạo nên những ứng dụng phong phú. Có thể chỉ ra một số thành phần cơ bản như:

  • Service: lập trình viên có thể khai thác các dịch vụ có sẵn hoặc tạo ra các dịch vụ chạy ngầm định khác trong hệ thống. Các dịch vụ này có thể được truy cập từ bất cứ ứng dụng nào.
  • Broadcast Receiver: đây là thành phần thú vị giúp ứng dụng của bạn có khả năng phản ứng lại với các sự kiện trong hệ thống hoặc liên quan đến việc xử lý một dữ liệu nào đó. Nhờ nó các ứng dụng trong Android tạo nên một môi trường ứng dụng thống nhất, người dùng thay vì có cảm giác “đang chạy một ứng dụng để làm việc gì đó” sẽ thấy rằng mình “đang làm một việc gì đó trong ngữ cảnh với một ứng dụng phù hợp”.
  • Intent: đây là thành phần cơ bản trong cơ chế quản lý giao tiếp của Android, nó cho phép chuyển đổi, truyền và nhận thông điệp giữa các Activity.

3. Những thành phần cung cấp dữ liệu, tài nguyên và cấu hình ứng dụng

  • Content Provider: có thể hình dung Content Provider giống như một database server thu nhỏ cung cấp khả năng truy vấn vào các nguồn dữ liệu khác nhau (phổ biến là SQLite) thông qua một URI (ví dụ như các dữ liệu Contact, Message v.v…). Kết quả truy vấn của Content Provider luôn trả về đối tượng Cursor (có thể hình dung nó như là ResultSet trong JDBC).
  • Resource: tài nguyên có thể sử dụng trong ứng dụng rất phong phú bao gồm hình ảnh, âm thanh, văn bản, văn bản đa ngôn ngữ, layout, xml v.v… tất cả chúng nằm trong thư mục /res. Mọi thứ trong /res không đơn giản chỉ là một phần được đóng gói đi cùng ứng dụng mà chúng có thể được thao tác và truy xuất từ trong code một cách dễ dàng ở thời điểm chạy cũng như khi đang biên địch (thông qua một lớp được sinh tự động nhằm tối ưu hóa việc truy xuất tài nguyên có tên là R.java).
  • AndroidManifest.xml: đây là file cấu hình cho mỗi ứng dụng android, nó chứa các thông tin cơ bản của ứng dụng cho hệ điều hành như điểm truy xuất, các quyền hạn, các thông tin cài đặt, cấu hình v.v…

Hình 10: Cấu trúc của một Android Project trong Eclipse

Bắt đầu khám phá

Bài viết đến đây mới chỉ là sự khởi đầu, ta vừa nhìn xuống “thành phố Android” từ trên máy bay, khi đó ta chỉ cảm nhận được những mảng, khối cơ bản mà không thấy chi tiết. Nhưng hy vọng với từng đó đã giúp bạn định vị được rằng để tiếp tục cuộc hành trình khám phá “thành phố” này bạn nên bắt đầu từ đâu và như thế nào. Chúc các bạn có một chuyến đi vui vẻ!

Tài nguyên

ebook: Android In Practice by Charlie Collins & Michael Galpin & Matthias Kaeppler
http://www.ibm.com/developerworks/library/os-android-devel/
http://software.intel.com/en-us/articles/android-application-development-and-optimization-on-the-intel-atom-platform
http://vladnevzorov.com/2011/04/30/android-application-architecture-part-ii-architectural-styles-and-patterns/
http://apcmag.com/whats-android.htm
https://vkroz.wordpress.com/category/android/

Nguồn: tapchilaptrinh

Monday, April 15, 2013

Socket trong Android

Trong bài này mình sẽ giới thiệu với các bạn về lập trình Socket(bài này mình chỉ nói đến lập trình Socket cho TCP/IP) trong Android.
Lập trình Socket chắc hẳn rất quen thuộc với các bạn học CNTT, vì thế mình chỉ nói lại một số vấn đề chính liên quan đến Socket:
- Socket là một phương pháp để thiết lập kết nối truyền thông giữa một chương trình yêu cầu dịch vụ ( client) và một chương trình cung cấp dịch vụ (server) trên mạng LAN, WAN hay Internet. Một socket trên máy yêu cầu dịch vụ có địa chỉ mạng được cấp sẵn để gọi một socket trên máy cung cấp dịch vụ. Một khi socket đó được thiết lập phù hợp, hai bên có thể trao đổi dịch vụ và dữ liệu.
-Tóm váy lại là thằng Server thì phải tạo một Server luôn luôn lắng nghe (luôn luôn thấu hiểu) ở một cổng nào đó ví dụ 8888 chẳng hạn. Thằng Client muốn kết nối được đến Server để gửi yêu cầu thì phải xác định được cổng đó và IP của Server.


Cơ bản về lý thuyết chỉ có thế, các bạn muốn tìm hiểu kĩ thì cứ Google mà tra, sau đây là phần Socket cho Android. Mình sẽ làm một ví dụ minh họa: Bên Client sẽ gửi 2 số sang bên Server, Server nhận được sẽ tính tổng 2 số đó và gửi lại Client hiển thị

1.Về Server:
Các bạn có thể viết Server bằng bất kỳ ngôn ngữ j, ở đây mình viết bằng Java cho mọi người dễ hiểu:

-Đầu tiên ta tạo một class ServerSocket với port 9999: (chú ý phải đặt trong try catch)


Code:
ServerSocket ss=new ServerSocket(9999);
-Tạo vòng lặp để luôn lắng nghe yêu cầu của Client:
Code:
while (true){
Socket cl=ss.accept();//Chap nhan client ket noi den
System.out.printf("Client Connect");

BufferedReader br=new BufferedReader(new InputStreamReader(cl.getInputStream())); //Khoi tao luong doc du lieu
String a=br.readLine();
String b=br.readLine();//Doc 2 so a va b client gui den

PrintWriter pr=new PrintWriter(cl.getOutputStream(),true);//Khoi toi luong ghi du lieu
float c=Float.parseFloat(a)+Float.parseFloat(b);
pr.println(c);
cl.close();
}

2.Về bên Client:(Viết trên Android)
Các bạn New một project mới và tạo các file như sau:
-Khởi tạo giao diện: chúng ta thiết kế một layout bao gồm các TextView, EditText để nhập 2 số a, b và hiển thị kết quả. Ngoài ra ta thêm một nút Tinh để gửi a, b cho bên Server.
Code: main.xml

Code:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center_horizontal"
>
<LinearLayout
android:id="@+id/linearLayout1"
android:layout_height="wrap_content"
android:layout_width="wrap_content">
<TextView
android:text="Nhap so thu 1:"
android:layout_width="100dp"
android:layout_height="wrap_content">
</TextView>
<EditText
android:hint=" a "
android:id="@+id/a"
android:layout_width="150dp"
android:layout_height="wrap_content">
</EditText>
</LinearLayout>
<LinearLayout
android:id="@+id/linearLayout2"
android:layout_height="wrap_content"
android:layout_width="wrap_content">
<TextView
android:text="Nhap so thu 2:"
android:layout_width="100dp"
android:layout_height="wrap_content">
</TextView>
<EditText
android:hint=" b "
android:id="@+id/b"
android:layout_width="150dp"
android:layout_height="wrap_content">
</EditText>
</LinearLayout>
<LinearLayout
android:id="@+id/linearLayout3"
android:layout_height="wrap_content"
android:layout_width="wrap_content">
<TextView
android:text="Ketqua: "
android:layout_width="100dp"
android:layout_height="wrap_content">
</TextView>
<EditText
android:hint=" "
android:id="@+id/kqua"
android:layout_width="150dp"
android:layout_height="wrap_content">
</EditText>
</LinearLayout>
<Button
android:text="Tinh"
android:id="@+id/tinh"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</Button>

</LinearLayout>
 
 
-Tiếp theo, ta mở file mainActivity.java (do các bạn tự đặt tên khi tạo Project)

+Tạm thời để cái hàm onCreat sang một bên, ta xử lý sau, ta đi xây
dựng hàm kết nối, gửi nhận dữ liệu với server thông qua IP và port, hàm
này sẽ trả lại cho ta giá trị tổng của 2 số a và b ta nhập vào từ các
EditText:
public String connectSever(final String ip, final String port, final float a,final float b){
String output=null;
try {
Socket cl=new Socket(ip,Integer.parseInt(port));//ket noi server

PrintWriter pw=new PrintWriter(cl.getOutputStream(),true);//tao luong gui du lieu
pw.println(""+a);
pw.println(""+b);

BufferedReader br=new BufferedReader(new InputStreamReader(cl.getInputStream()));//tao luong nhan du lieu
output=br.readLine();
cl.close();
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}


return output;//tra ve ket qua cua a+b
}
 
        +Bây giờ chúng ta chỉ phải hiển thị cái layout và xử lý sự kiện cho nút bấm trong hàm onCreat:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

final EditText ed1=(EditText)findViewById(R.id.a);
final EditText ed2=(EditText)findViewById(R.id.b);
final EditText ed3=(EditText)findViewById(R.id.kqua);
Button tinh=(Button)findViewById(R.id.tinh);

View.OnClickListener tinhOnClick=new OnClickListener() {

public void onClick(View v) {
// TODO Auto-generated method stub
String op=connectSever("10.0.2.2", "9999", Float.parseFloat(ed1.getText().toString()), Float.parseFloat(ed2.getText().toString()));
ed3.setText(op);
}
};
tinh.setOnClickListener(tinhOnClick);
}
 
 
 
 
 



Đọc nội dung file .txt trong sdcard [ For Newbie ]

try{ 
File f = new File(Environment.getExternalStorageDirectory()+"/test.txt");
fileIS = new FileInputStream(f);
BufferedReader buf = new BufferedReader(new InputStreamReader(fileIS));
String readString = new String();
//đọc theo từng dòng
while((readString = buf.readLine())!= null){
// hiển thị ra LOGCAT
Log.d("line: ", readString);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e){
e.printStackTrace();
}
Khi chạy bạn nhớ bật Logcat để xem kết quả. Đoạn code đặt ngay trong hàm onCreate() nhé.

[Code snippets] Download 1 HTTP file với progess notification

try {
// Khai báo url
URL url = new URL("http://somewhere.com/some/webhosted/file");

//tạo HTTP connection
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

//setup phương thức cho HTTP connecton
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);

// kết nối
urlConnection.connect();


// khởi tạo sdcard . Lưu ý phương thức Environment.getExternalStorageDirectory(); trả lại đường dẫn đến sdcard
File SDCardRoot = Environment.getExternalStorageDirectory();
// Tạo 1 file để lưu nội dung trang web
File file = new File(SDCardRoot,"somefile.ext");

//Khai báo FileInputStream để tương tác với InputStream
FileOutputStream fileOutput = new FileOutputStream(file);

//InputStream để đọc dẽ liệu từ url
InputStream inputStream = urlConnection.getInputStream();

//lấy size của dữ liệu tải về
int totalSize = urlConnection.getContentLength();
// khai báo 1 biến để biết dữ liệu tải về ( realtime)
int downloadedSize = 0;

//tạo buffer
byte[] buffer = new byte[1024];
int bufferLength = 0; //used to store a temporary size of the buffer

//đọc dữ liệu từ buffer
while ( (bufferLength = inputStream.read(buffer)) > 0 ) {
//ghi từ buffer vào textfile ở sdcard
fileOutput.write(buffer, 0, bufferLength);
//update downloadSize
downloadedSize += bufferLength;
//dựa vào biến downloadSize để update progess
updateProgress(downloadedSize, totalSize);

}
//đóng outputstream khi hoàn thành
fileOutput.close();

} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

[Code Snippets] Lấy thông tin về Battery

main.xml
[JAVA]
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:eek:rientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>

<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Battery Info."
/>
<TextView
android:id="@+id/batterylevel"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Battery Level:"
/>
<TextView
android:id="@+id/batteryvoltage"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Battery Voltage:"
/>
<TextView
android:id="@+id/batterytemperature"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Battery Temperature:"
/>
<TextView
android:id="@+id/batterytechology"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Technology:"
/>
<TextView
android:id="@+id/batterystatus"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Status:"
/>
<TextView
android:id="@+id/batteryhealth"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Health:"
/>
</LinearLayout>

[/JAVA]

Main Activity

[JAVA]
package com.exercise.AndroidBattery;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.BatteryManager;
import android.os.Bundle;
import android.widget.TextView;

public class AndroidBattery extends Activity {

private TextView batteryLevel, batteryVoltage, batteryTemperature,
batteryTechnology, batteryStatus, batteryHealth;


/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

batteryLevel = (TextView)findViewById(R.id.batterylevel);
batteryVoltage = (TextView)findViewById(R.id.batteryvoltage);
batteryTemperature = (TextView)findViewById(R.id.batterytemperature);
batteryTechnology = (TextView)findViewById(R.id.batterytechology);
batteryStatus = (TextView)findViewById(R.id.batterystatus);
batteryHealth = (TextView)findViewById(R.id.batteryhealth);

this.registerReceiver(this.myBatteryReceiver,
new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
}

private BroadcastReceiver myBatteryReceiver
= new BroadcastReceiver(){

@Override
public void onReceive(Context arg0, Intent arg1) {
// TODO Auto-generated method stub

if (arg1.getAction().equals(Intent.ACTION_BATTERY_CHANGED)){
batteryLevel.setText("Level: "
+ String.valueOf(arg1.getIntExtra("level", 0)) + "%");
batteryVoltage.setText("Voltage: "
+ String.valueOf((float)arg1.getIntExtra("voltage", 0)/1000) + "V");
batteryTemperature.setText("Temperature: "
+ String.valueOf((float)arg1.getIntExtra("temperature", 0)/10) + "c");
batteryTechnology.setText("Technology: " + arg1.getStringExtra("technology"));

int status = arg1.getIntExtra("status", BatteryManager.BATTERY_STATUS_UNKNOWN);
String strStatus;
if (status == BatteryManager.BATTERY_STATUS_CHARGING){
strStatus = "Charging";
} else if (status == BatteryManager.BATTERY_STATUS_DISCHARGING){
strStatus = "Dis-charging";
} else if (status == BatteryManager.BATTERY_STATUS_NOT_CHARGING){
strStatus = "Not charging";
} else if (status == BatteryManager.BATTERY_STATUS_FULL){
strStatus = "Full";
} else {
strStatus = "Unknown";
}
batteryStatus.setText("Status: " + strStatus);

int health = arg1.getIntExtra("health", BatteryManager.BATTERY_HEALTH_UNKNOWN);
String strHealth;
if (health == BatteryManager.BATTERY_HEALTH_GOOD){
strHealth = "Good";
} else if (health == BatteryManager.BATTERY_HEALTH_OVERHEAT){
strHealth = "Over Heat";
} else if (health == BatteryManager.BATTERY_HEALTH_DEAD){
strHealth = "Dead";
} else if (health == BatteryManager.BATTERY_HEALTH_OVER_VOLTAGE){
strHealth = "Over Voltage";
} else if (health == BatteryManager.BATTERY_HEALTH_UNSPECIFIED_FAILURE){
strHealth = "Unspecified Failure";
} else{
strHealth = "Unknown";
}
batteryHealth.setText("Health: " + strHealth);

}
}

};
}

[Code Snippets] Một cách kiểm tra phiên bản mới của ứng dụng

Có nhiều cách để cho người dùng kiểm tra phiên bản mới ứng dụng. Phương pháp sau đây không cần phải có server riêng để kiểm tra phiên bản mà dùng chính Android Market server (đòi hỏi ứng dụng phải có trên Market). Nguyên lý là bạn truy cập trang thông tin ứng dụng của mình để trích xuất thông tin phiên bản, sau đó so sánh với phiên bản hiện tại trong PackageInfo của ứng dụng.

Đoạn code sau đây mình lấy từ chương trình OptiNews (định danh là vn.zerox.optinews, các bạn sẽ thay bằng cái khác):


Tạo thread để check phiên bản:

Mã:
Thread thr = new LoadVersion();
thr.start();
Thread check phiên bản:
Mã:
private class LoadVersion extends Thread {
@Override
public void run() {
handler.sendEmptyMessage(0);

try {
HttpParams params = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(params, 10000);
HttpConnectionParams.setSoTimeout(params, 10000);
HttpClient client = new DefaultHttpClient(params);
HttpGet get = new HttpGet("http://market.android.com/details?id=vn.zerox.optinews");
HttpResponse response = client.execute(get);
HttpEntity entity = response.getEntity();
html = EntityUtils.toString(entity, "utf-8");
} catch (Exception e) {
html = null;
}

handler.sendEmptyMessage(1);
}
}
Handler để hiển thị thông tin kiểm tra phiên bản:
Mã:
private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case 0:
if (oncreate) break;
pd = new ProgressDialog(MainCategory.this);
pd.setMessage("Kiểm tra cập nhật...");
pd.setCancelable(false);
Window window = pd.getWindow();
//window.setFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL,WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL);
window.clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
pd.show();
break;
case 1:
if (!oncreate) pd.dismiss();
if (html == null) {
if (!oncreate) Toast.makeText(MainCategory.this, "Lỗi truy cập thông tin !", Toast.LENGTH_SHORT).show();
} else {
int i = html.indexOf("<dt>Current Version:</dt><dd>");
int j = html.indexOf("</dd>",i+29);
if (i == -1 || j == -1) {
Toast.makeText(MainCategory.this, "Lỗi truy cập thông tin phiên bản !", Toast.LENGTH_SHORT).show();
break;
}
String ver = html.substring(i+29, j);
float nver = Float.parseFloat(ver);
String cur = "1.0";
try {
cur = getPackageManager().getPackageInfo(getPackageName(),0).versionName;
} catch (NameNotFoundException e) {}
float ncur = Float.parseFloat(cur);
String text;
if (ncur >= nver) {
if (oncreate) break;
text = "Bạn đang dùng phiên bản mới nhất !";
}
else text = "Hiện đã có phiên bản mới là " + ver + " !";
AlertDialog.Builder dialog = new AlertDialog.Builder(MainCategory.this);
dialog.setTitle("Kiểm tra cập nhật");
dialog.setMessage(text);
dialog.setNeutralButton("Đóng", null);
dialog.create().show();
}
break;
default:
super.handleMessage(msg);
}
}
};
Chú ý ở đây mình đặt tên phiên bản có dạng n.m (n,m gồm 1 chữ số). Các bạn có thể sửa code để tương thích dạng phiên bản khác như n.mm-beta ...
(Vì trên Market không hiển thị VersionCode nên mình phải dùng VersionName)

Wednesday, April 10, 2013

Android Google Map View Example Tutorial

Step 1 : Obtaining Google API Key
To make use of Google Map or any other Google API you need to have a Google API key.
It is extremely easy to get a Google API Key. You see below I have made a Video which is made up of step-by-step procedure for obtaining the Google API key.

Detailed Steps
  • Proceed to the location exactly where JDK installed.
  • Certainly, there you will see KeyTool.
  • Then simply Copy the path.
  • Start a command prompt then change the directory to the keytool path.
  • copy and paste the below code snippet to command prompt
keytool -list -alias androiddebugkey -keystore
  • At this point we need to copy the path of the debug.keystore
  • Head over to windows/users/[your computer user name]/.android/
  • It’s simple to find the debug.keystore, so copy the path.
  • Next paste the keystore path surrounded with “” combined with the step 5 code snippet.
keytool -list -alias androiddebugkey -keystore "C:.android.keystore" -storepass android -keypass android
  • Last but not least press Enter. You will notice the Certificate Finger Print.

  • At this moment visit this link to sign up to Google API.
  • Enter the Finger print using only number and digits. Stay away from including “:” .
  • After that Tick the Agreement.
  • Simply click Generate API key. You should see the API key now. Copy the actual URL intended for future reference.
Step 2 : Hands-on Google Map in Emulator
Before start to code our Google Map Alert App, we are now going to test it, to ensure we are ready to go.
  • Start a Sample Project named GoogleMapDemo.

  • Choose the Choose bulid SDK to Google API. I choosed Google API Level 16.
  • Then Click Next for the rest, Finally press Finish.

  • Copy the below code to your Layout.
res/layout/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" >
<com.google.android.maps.MapView
android:id="@+id/map"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:clickable="true"
android:apiKey="06Q7KxHWP0w3-i0IpzRr8sSRnDLyHWAfJ_lk8mQ" />
</RelativeLayout>

Here you should enter your apikey otherwise it won’t work.
  • Ok in case you are so curious, then simply run it. You will find the below stopped message.

Just what exactly is the mistake we certainly have done. We have setup every little thing as well as enter the MapView component within our layout.
But It is not sufficient to really make it do the job. We have seen lots of android tutorial for beginners. Therefore by now you should capable of finding out, exactly what do we have to do in order to succeed.
Absolutely yes, you are right, we should tell to the Manifest file that we are going to make use of Google Map for this application, and also Internet access.
Android Manifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.googlemapdemo"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="7"
android:targetSdkVersion="15" />
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/google_map_demo" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<uses-library android:name="com.google.android.maps"/>
</application>
<uses-permission android:name="android.permission.INTERNET"/>
</manifest>
Do you believe that this time, it’s going to run the app and show the map.
I am not going to say anything at the moment, just proceed as well as run the project.


So above is the answer. So for we have extends only Activity, but in order to make use of Google Map, Our Java Code should extends MapActivity. :)
  • Then finally include the unimplemented methods.
src/com.example.androidmapviewdemo/AndroidMapViewDemo.java
package com.example.googlemapdemo;
import com.google.android.maps.MapActivity;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.MenuItem;
import android.support.v4.app.NavUtils;
public class MainActivity extends MapActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
@Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
}

 
 
 
 
Download Code

Monday, January 28, 2013

Combo box / Drop down list box in Android


As usual doing something simple in Android is frustrating - this time: a simple Combo (or DropDownList). The little and important tweak - calling "setDropDownViewResource" to set the style of the items in the dialog box.

XML:
<spinner id="@+id/spinner" layout_width="wrap_content" android:layout_height="wrap_content" />

Code to add the data:
  1. Spinner spinner = (Spinner)this.findViewById(R.id.spinner);  
  2. ArrayAdapter<String> adapter = new ArrayAdapter<String>(  
  3.         this,  
  4.         android.R.layout.simple_spinner_item,  
  5.         new String[] { "1", "2", "3" });  
  6. adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);  
  7. spinner.setAdapter(adapter);  


A common task is to populate a spinner using a string array defined in a resource file. Here's a function which do just that:
  1. public static void populateSpinnerWithArray(Spinner spinner, int stringArrayResId) {  
  2.     ArrayAdapter<String> adapter = new ArrayAdapter<String>(  
  3.             spinner.getContext(),    
  4.             android.R.layout.simple_spinner_item,  
  5.             spinner.getContext().getResources().getStringArray(stringArrayResId));    
  6.     adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);    
  7.     spinner.setAdapter(adapter);    

Tuesday, January 22, 2013

Using Google Maps in Android

Google Maps is one of the many applications bundled with the Android platform. In addition to simply using the Maps application, you can also embed it into your own applications and make it do some very cool things. In this article, I will show you how to use Google Maps in your Android applications and how to programmatically perform the following:
  1. Change the views of Google Maps
  2. Obtain the latitude and longitude of locations in Google Maps
  3. Perform geocoding and reverse geocoding
  4. Add markers to Google Maps

Creating the Project

Using Eclipse, create a new Android project and name GoogleMaps as shown in Figure 1.

Figure 1 Creating a new Android project using Eclipse

Obtaining a Maps API key

Beginning with the Android SDK release v1.0, you need to apply for a free Google Maps API key before you can integrate Google Maps into your Android application. To apply for a key, you need to follow the series of steps outlined below. You can also refer to Google's detailed documentation on the process at http://code.google.com/android/toolbox/apis/mapkey.html.
First, if you are testing the application on the Android emulator, locate the SDK debug certificate located in the default folder of "C:\Documents and Settings\<username>\Local Settings\Application Data\Android". The filename of the debug keystore is debug.keystore. For deploying to a real Android device, substitute the debug.keystore file with your own keystore file. In a future article I will discuss how you can generate your own keystore file.
For simplicity, copy this file (debug.keystore) to a folder in C:\ (for example, create a folder called "C:\Android").
Using the debug keystore, you need to extract its MD5 fingerprint using the Keytool.exe application included with your JDK installation. This fingerprint is needed to apply for the free Google Maps key. You can usually find the Keytool.exe from the "C:\Program Files\Java\<JDK_version_number>\bin" folder.
Issue the following command (see also Figure 2) to extract the MD5 fingerprint.
keytool.exe -list -alias androiddebugkey -keystore "C:\android\debug.keystore" -storepass android -keypass android
Copy the MD5 certificate fingerprint and navigate your web browser to: http://code.google.com/android/maps-api-signup.html. Follow the instructions on the page to complete the application and obtain the Google Maps key.

Figure 2 Obtaining the MD5 fingerprint of the debug keystore
To use the Google Maps in your Android application, you need to modify your AndroidManifest.xml file by adding the <uses-library> element together with the INTERNET permission:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="net.learn2develop.GoogleMaps"
android:versionCode="1"
android:versionName="1.0.0">

<application android:icon="@drawable/icon" android:label="@string/app_name">
 
<uses-library android:name="com.google.android.maps" />
 
<activity android:name=".MapsActivity"
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.INTERNET" />
 
</manifest>
</xml>

Displaying the Map

To display the Google Maps in your Android application, modify the main.xml file located in the res/layout folder. You shall use the <com.google.android.maps.MapView> element to display the Google Maps in your activity. In addition, let's use the <RelativeLayout> element to position the map within the activity:
<?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">

 
<com.google.android.maps.MapView
android:id="@+id/mapView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:enabled="true"
android:clickable="true"
android:apiKey="0l4sCTTyRmXTNo7k8DREHvEaLar2UmHGwnhZVHQ"
/>

 
</RelativeLayout>
Notice from above that I have used the Google Maps key that I obtained earlier and put it into the apiKey attribute.
In the MapsActivity.java file, modify the class to extend from the MapActivity class, instead of the normal Activity class:
package net.learn2develop.GoogleMaps;
 
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapView;
import android.os.Bundle;
 
public class MapsActivity extends MapActivity
{
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
 
@Override
protected boolean isRouteDisplayed() {
return false;
}
}
Observe that if your class extends the MapActivity class, you need to override the isRouteDisplayed() method. You can simply do so by setting the method to return false.
That's it! That's all you need to do to display the Google Maps in your application. Press F11 in Eclipse to deploy the application onto an Android emulator. Figure 3 shows the Google map in all its glory.

Figure 3 Google Maps in your application
At this juncture, take note of a few troubleshooting details. If your program does not run (i.e. it crashes), then it is likely you forgot to put the following statement in your AndroidManifest.xml file:
    <uses-library android:name="com.google.android.maps" />
If your application manages to load but you cannot see the map (all you see is a grid), then it is very likely you do not have a valid Map key, or that you did not specify the INTERNET permission:
    <uses-permission android:name="android.permission.INTERNET" />

Displaying the Zoom View

The previous section showed how you can display the Google Maps in your Android device. You can drag the map to any desired location and it will be updated on the fly. However, observe that there is no way to zoom in or out from a particular location. Thus, in this section, you will learn how you can let users zoom into or out of the map.
First, add a <LinearLayout> element to the main.xml file as shown below:
<?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">

 
<com.google.android.maps.MapView
android:id="@+id/mapView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:enabled="true"
android:clickable="true"
android:apiKey="0l4sCTTyRmXTNo7k8DREHvEaLar2UmHGwnhZVHQ"
/>

 
<LinearLayout android:id="@+id/zoom"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
/>

 
</RelativeLayout>
You will use the <LinearLayout> element to hold the two zoom controls in Google Maps (you will see this shortly).
In the MapsActivity.java file, add the following imports:
import com.google.android.maps.MapView.LayoutParams;  
import android.view.View;
import android.widget.LinearLayout;
and add the following code after the line setContentView(R.layout.main);
        mapView = (MapView) findViewById(R.id.mapView);
LinearLayout zoomLayout = (LinearLayout)findViewById(R.id.zoom);
View zoomView = mapView.getZoomControls();
 
zoomLayout.addView(zoomView,
new LinearLayout.LayoutParams(
LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT));
mapView.displayZoomControls(true);
The complete MapsActivity.java file is given below:
package net.learn2develop.GoogleMaps;
 
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapView;
import com.google.android.maps.MapView.LayoutParams;
 
import android.os.Bundle;
import android.view.View;
import android.widget.LinearLayout;
 
public class MapsActivity extends MapActivity
{
MapView mapView;
 
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
 
 
mapView = (MapView) findViewById(R.id.mapView);
LinearLayout zoomLayout = (LinearLayout)findViewById(R.id.zoom);
View zoomView = mapView.getZoomControls();
 
zoomLayout.addView(zoomView,
new LinearLayout.LayoutParams(
LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT));
mapView.displayZoomControls(true);
 
}
 
@Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
}
Basically, you obtain the MapView instance on the activity, obtain its zoom controls and then add it to the LinearLayout element you added to the activity earlier on. In the above case, the zoom control will be displayed at the bottom of the screen. When you now press F11 in Eclipse, you will see the zoom controls when you touch the map (see Figure 4).

Figure 4 Using the zoom controls in Google Maps
Using the zoom control, you can zoom in or out of a location by simply touching the "+ or "-" buttons on the screen.
Alternatively, you can also programmatically zoom in or out of the map using the zoomIn() and zoomOut() methods from the MapController class:
package net.learn2develop.GoogleMaps;
 
//...
import android.os.Bundle;
import android.view.KeyEvent;
 
public class MapsActivity extends MapActivity
{
MapView mapView;
 
public boolean onKeyDown(int keyCode, KeyEvent event)
{
MapController mc = mapView.getController();
switch (keyCode)
{
case KeyEvent.KEYCODE_3:
mc.zoomIn();
break;
case KeyEvent.KEYCODE_1:
mc.zoomOut();
break;
}
return super.onKeyDown(keyCode, event);
}
 
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
//...
}
 
@Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
}
In the above code, when the user presses the number 3 on the keyboard the map will zoom in into the next level. Pressing number 1 will zoom out one level.

Changing Views of the Map

By default, the Google Maps displays in the map mode. If you wish to display the map in satellite view, you can use the setSatellite() method of the MapView class, like this:
        mapView.setSatellite(true);
You can also display the map in street view, using the setStreetView() method:
        mapView.setStreetView(true);
Figure 5 shows the Google Maps displayed in satellite and street views, respectively.

Figure 5 Displaying Google Maps in satellite and street views

Displaying a Particular Location

Be default, the Google Maps displays the map of the United States when it is first loaded. However, you can also set the Google Maps to display a particular location. In this case, you can use the animateTo() method of the MapController class.
The following code shows how this is done:
package net.learn2develop.GoogleMaps;
 
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.MapView.LayoutParams;
 
import android.os.Bundle;
import android.view.View;
import android.widget.LinearLayout;
 
public class MapsActivity extends MapActivity
{
MapView mapView;
MapController mc;
GeoPoint p;
 
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
 
mapView = (MapView) findViewById(R.id.mapView);
LinearLayout zoomLayout = (LinearLayout)findViewById(R.id.zoom);
View zoomView = mapView.getZoomControls();
 
zoomLayout.addView(zoomView,
new LinearLayout.LayoutParams(
LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT));
mapView.displayZoomControls(true);
 
mc = mapView.getController();
String coordinates[] = {"1.352566007", "103.78921587"};
double lat = Double.parseDouble(coordinates[0]);
double lng = Double.parseDouble(coordinates[1]);
 
p = new GeoPoint(
(int) (lat * 1E6),
(int) (lng * 1E6));
 
mc.animateTo(p);
mc.setZoom(17);
mapView.invalidate();
}
 
@Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
}
In the above code, you first obtain a controller from the MapView instance and assign it to a MapController object (mc). You use a GeoPoint object to represent a geographical location. Note that for this class the latitude and longitude of a location are represented in micro degrees. This means that they are stored as integer values. For a latitude value of 40.747778, you need to multiply it by 1e6 to obtain 40747778.
To navigate the map to a particular location, you can use the animateTo() method of the MapController class (an instance which is obtained from the MapView object). The setZoom() method allows you to specify the zoom level in which the map is displayed. Figure 6 shows the Google Maps displaying the map of Singapore.

Figure 6 Navigating to a particular location on the map

Adding Markers

Very often, you may wish to add markers to the map to indicate places of interests. Let's see how you can do this in Android. First, create a GIF image containing a pushpin (see Figure 7) and copy it into the res/drawable folder of the project. For best effect, you should make the background of the image transparent so that it does not block off parts of the map when the image is added to the map.

Figure 7 Adding an image to the res/drawable folder
To add a marker to the map, you first need to define a class that extends the Overlay class:
package net.learn2develop.GoogleMaps;
 
import java.util.List;
 
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.MapView.LayoutParams;
 
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Point;
import android.os.Bundle;
import android.view.View;
import android.widget.LinearLayout;
 
public class MapsActivity extends MapActivity
{
MapView mapView;
MapController mc;
GeoPoint p;
 
class MapOverlay extends com.google.android.maps.Overlay
{
@Override
public boolean draw(Canvas canvas, MapView mapView,
boolean shadow, long when)
{
super.draw(canvas, mapView, shadow);
 
//---translate the GeoPoint to screen pixels---
Point screenPts = new Point();
mapView.getProjection().toPixels(p, screenPts);
 
//---add the marker---
Bitmap bmp = BitmapFactory.decodeResource(
getResources(), R.drawable.pushpin);
canvas.drawBitmap(bmp, screenPts.x, screenPts.y-50, null);
return true;
}
}
 
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
//...
}
 
@Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
}
In the MapOverlay class that you have defined, override the draw() method so that you can draw the pushpin image on the map. In particular, note that you need to translate the geographical location (represented by a GeoPoint object, p) into screen coordinates.
As you want the pointed tip of the push pin to indicate the position of the location, you would need to deduct the height of the image (which is 50 pixels) from the y-coordinate of the point (see Figure 8) and draw the image at that location.

Figure 8 Adding an image to the map
To add the marker, create an instance of the MapOverlap class and add it to the list of overlays available on the MapView object:
    @Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
 
//...
 
mc.animateTo(p);
mc.setZoom(17);
 
//---Add a location marker---
MapOverlay mapOverlay = new MapOverlay();
List<Overlay> listOfOverlays = mapView.getOverlays();
listOfOverlays.clear();
listOfOverlays.add(mapOverlay);
 
mapView.invalidate();
}
Figure 9 shows how the pushpin looks like when added to the map.

Figure 9 Adding a marker to the map

Getting the Location that was touched

After using Google Maps for a while, you may wish to know the latitude and longitude of a location corresponding to the position on the screen that you have just touched. Knowing this information is very useful as you can find out the address of a location, a process known as Geocoding (you will see how this is done in the next section).
If you have added an overlay to the map, you can override the onTouchEvent() method within the Overlay class. This method is fired every time the user touches the map. This method has two parameters - MotionEvent and MapView. Using the MotionEvent parameter, you can know if the user has lifted his finger from the screen using the getAction() method. In the following code, if the user has touched and then lifted his finger, you will display the latitude and longitude of the location touched:
    class MapOverlay extends com.google.android.maps.Overlay
{
@Override
public boolean draw(Canvas canvas, MapView mapView,
boolean shadow, long when)
{
//...
}
 
@Override
public boolean onTouchEvent(MotionEvent event, MapView mapView)
{
//---when user lifts his finger---
if (event.getAction() == 1) {
GeoPoint p = mapView.getProjection().fromPixels(
(int) event.getX(),
(int) event.getY());
Toast.makeText(getBaseContext(),
p.getLatitudeE6() / 1E6 + "," +
p.getLongitudeE6() /1E6 ,
Toast.LENGTH_SHORT).show();
}
return false;
}
}
Figure 10 shows this in action.

Figure 10 Displaying the latitude and longitude of a point touched on the map

Geocoding and Reverse Geocoding

If you know the latitude and longitude of a location, you can find out its address using a process known as Geocoding. Google Maps in Android supports this via the Geocoder class. The following code shows how you can find out the address of a location you have just touched using the getFromLocation() method:
    class MapOverlay extends com.google.android.maps.Overlay
{
@Override
public boolean draw(Canvas canvas, MapView mapView,
boolean shadow, long when)
{
//...
}
 
@Override
public boolean onTouchEvent(MotionEvent event, MapView mapView)
{
//---when user lifts his finger---
if (event.getAction() == 1) {
GeoPoint p = mapView.getProjection().fromPixels(
(int) event.getX(),
(int) event.getY());
 
Geocoder geoCoder = new Geocoder(
getBaseContext(), Locale.getDefault());
try {
List<Address> addresses = geoCoder.getFromLocation(
p.getLatitudeE6() / 1E6,
p.getLongitudeE6() / 1E6, 1);
 
String add = "";
if (addresses.size() > 0)
{
for (int i=0; i<addresses.get(0).getMaxAddressLineIndex();
i++)
add += addresses.get(0).getAddressLine(i) + "\n";
}
 
Toast.makeText(getBaseContext(), add, Toast.LENGTH_SHORT).show();
}
catch (IOException e) {
e.printStackTrace();
}
return true;
}
else
return false;
}
}
Figure 11 shows the above code in action.

Figure 11 Performing Geocoding in Google Maps
If you know the address of a location but want to know its latitude and longitude, you can do so via reverse-Geocoding. Again, you can use the Geocoder class for this purpose. The following code shows how you can find the exact location of the Empire State Building by using the getFromLocationName() method:
        Geocoder geoCoder = new Geocoder(this, Locale.getDefault());    
try {
List<Address> addresses = geoCoder.getFromLocationName(
"empire state building", 5);
String add = "";
if (addresses.size() > 0) {
p = new GeoPoint(
(int) (addresses.get(0).getLatitude() * 1E6),
(int) (addresses.get(0).getLongitude() * 1E6));
mc.animateTo(p);
mapView.invalidate();
}
} catch (IOException e) {
e.printStackTrace();
}
Once the location is found, the above code navigates the map to the location. Figure 12 shows the code in action.

Figure 12 Navigating to the Empire State Building

Summary

In this article, you have learnt a few tricks for the Google Maps in Android. Using Google Maps, there are many interesting projects you can work on, such as geo-tagging, geo-tracking, etc. If you have cool ideas on building cool location-based services, share with us in the comments box below. Have fun!

from: http://mobiforge.com/developing/story/using-google-maps-android