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:

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 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é.

Full screen Android app

  public void onCreate(Bundle savedInstanceState) {
        
super.onCreate(savedInstanceState);        
        
requestWindowFeature(Window.FEATURE_NO_TITLE);
        
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREENWindowManager.LayoutParams.FLAG_FULLSCREEN);
        
setContentView(R.layout.main);
    }

[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();

[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"
/>

[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):

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

Popular Posts