25 thg 5, 2012

Làm việc với Service trong Android.

Bài viết nhằm mục đích hiểu về gọi đến 1 service theo con đường gọi phương thức bindService() trong lập trình Android.
Mục tiêu : Tạo 1 service có chức năng tính toán và trả về kết quả của phương thức cộng 2 số nguyên.

Màn hình chương trình khi gọi phương thức cong2so(5,5) từ 1 service như sau :

Hàm onCreate(bundle) : nhận các đối tượng về từ giao diện :

 @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        tv = (TextView) findViewById(R.id.tv);
        button = (Button) findViewById(R.id.button);
        button.setOnClickListener(this);
    }

Trước hết, tạo 1 lớp có tên là MyService mở rộng từ lớp Service như sau :
public class MyService extends Service {

    // Binder cho cac client
    private final IBinder mBinder = new LocalBinder();
   
    @Override
    public IBinder onBind(Intent intent) {
        // TODO Auto-generated method stub
        return mBinder;
    }
    //phương thức cho các client có thể gọi.
    public int cong2So(int a, int b){
        return a + b ;
    }
   
    public class LocalBinder extends Binder {
        // Trả về đối tượng MyService để cho client có thể gọi public method
        MyService getService(){
            return MyService.this;
           
        }       
    }
}

Trở lại Activity chính của ứng dụng :

Trong hàm OnStart() chúng ta dùng phương thức bindService(parameter) để gọi đến MyService thông qua đối tượng Intent .
 
@Override
    protected void onStart() {
        // TODO Auto-generated method stub
        super.onStart();
        // Bind to MyService
        Intent i = new Intent(this, MyService.class);
        bindService(i, mConnection, Context.BIND_AUTO_CREATE) 
    }

Trong hàm onStop() : Ngắt kết nối đến MyService
    @Override
    protected void onStop() {
        // TODO Auto-generated method stub
        super.onStop();
        //Unbind from Service
        if(mBound){
            mService.unbindService(mConnection);
            mBound = false ;
           
        }
    }

Tạo 1 biến mConnection từ lớp ServiceConnection nhằm Overide 2 phương thức sau nhằm bound đến MyService.
private ServiceConnection mConnection = new ServiceConnection() {
       
        @Override
        public void onServiceDisconnected(ComponentName name) {
            mBound = false;
        }
       
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            // Bound to MyService.
            LocalBinder binder = (LocalBinder) service;
            mService = binder.getService();
            mBound = true;
        }
    };;;

Cuối cùng trong phương thức onClick của button ta gọi đến hàm cong2so(int,int) và hiển thị kết quả của phương thức ra 1 textview như sau :
@Override
    public void onClick(View v) {
        if(v.getId() == R.id.button){
            if(mBound){
                int result = mService.cong2So(5, 5);
                tv.setText(new String().valueOf(result));
            }
        }
    }

Trong Android manifesh.xml thêm dòng này :  <service android:name="MyService"></service> trong thẻ <application>

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

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

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

    <TextView
        android:id="@+id/tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="TextView" />

</LinearLayout>



23 thg 5, 2012

Souce code client server trên Android qua tcp socket programing

Mục tiêu :
- Demo cách thức hoạt động của client server qua giao thức TCP.
- Gửi nhận dữ liệu giữa Server và Client.
- Xây dựng các ứng dụng client/server trên các thiết bị chạy android độc lập, không phụ thuộc vào pc.

Ý tưởng :
- Gửi dữ liệu từ client lên server.
- Hiển thị dữ liệu ra editText.
- Thông báo toast notification khi dữ liệu được gửi đến.

Cần biết :
- Socket và SocketServer.
- Toast Notification.
- Telnet Client.

 Code :
- Cài đặt dịch vụ telnet client trên máy tính.
- Khởi động 2 máy ảo emulator.
- Vào cdm gõ lệnh sau : telnet localhost 5554 .
- Tiếp tục gõ lệnh :  redir add tcp:9999:999 để cấu hình ánh xạ port giữa local port và server port cho máy ảo 5554 qua port 9999.

Làm đúng sẽ có hình như sau :

Bây giờ chúng ta chạy ứng dụng server trên máy ảo 5554, client trên máy ảo 5556.
Kết nối giữa client và server qua port 9999 và ip : 10.0.2.2 . 

Thực hiện đúng chúng ta sẽ có hình minh họa sau : 

 
 Bên trái là server, bên phải là client. Chú ý các phần được bôi khung vàng. Chúc vui.









14 thg 5, 2012

QuickAction UI Android


Hiện thực được QuickAction UI chúng ta sẽ có hình như sau :
Bài này mình kham khảo từ trang web sau : http://www.edumobile.org/android/android-apps/quick-action-demo/ 


Sourcode Code được cung cấp bởi trang web đó. 
Nếu bạn nào có thắc mắc điều gì, thì để lại comment mình sẽ giải thích nếu có thể.
Bạn nào muốn lấy source code thì để lại email nhé. Chúc vui. 
QuickAction là 1 UI Control không có sẵn trong Android SDK nhé. 

Một loại hiển thị khác của QuickAction 3D.


Một số phương thức vẽ các hình thông dụng


Khi nhấp vào các button thì ứng dụng sẽ vẽ các hình trên các View.
Thứ tự như sau :






Source code ứng dụng :   http://and-sungha-blog.googlecode.com/files/Draw.rar

Multi Choice ListView

Cách sử dụng ListView với nhiều sự lựa chọn. Sử dụng với layout ListView đã được hỗ trợ sẵn.
Các bạn hoàn toàn có thể custom lại ListView với nhiều sự lựa chọn tùy vào ngữ cảnh của ứng dụng.
Dễ dàng nhất là chúng ta sử dụng các tài nguyên đã được xây dựng sẵn.

Code :

public class MutilChoiseListViewActivity extends Activity {
    private ListView choiceLV;
    private String[] choice = { "String A", "String B", "String C", "String D" };

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

        choiceLV = (ListView) findViewById(R.id.list);

        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_multiple_choice, choice);
        choiceLV.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
        choiceLV.setAdapter(adapter);
       

    }
}

main.xml

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

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

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

</LinearLayout>

21 thg 4, 2012

[Lập Trình Bada] Làm quen với Bada

Làm quen với bada. Các tạo môi trường làm việc trên hệ điều hành bada của Samsung. 
Ngôn ngữ sử dụng để phát triển trên hệ điều hành này là C++ .
Tuy nhiên Bada IDE có hỗ trợ giao diện trực quan kéo thả và sinh code tự động. 

Download IDE lập trình bada os tại đây : http://developer.bada.com/devtools/sdk
IDE có giao diện nguồn mở, các tính năng và cách sử dụng hoàn toàn giống eclipse. Một điều mà mình ưng ý nhất.
Bada là 1 hệ điều hành còn ít người biết đến, các lập trình viên ít chú ý, tuy rằng Samsung cũng đã có lần tổ chức cuộc thi viết ứng dụng trên hệ điều hành này. 

Dưới đây là source code đơn giản làm quen với bada os . download tại đây .



Bada OS có phát triển hay không, cũng như các OS khác. Một phần nhờ vào sự khám phá của LTV. Hi vọng các bạn sẽ thích thú với OS này. 

[Lập trình BlackBerry Mobile] Làm việc với các UI Control đơn giản


Cách làm việc với các control giao diện đơn giản trong lập trình trên các thiết bị chạy hệ điều hành Black Berry.
Đầu tiên có thể chia làm 3 loại sau :
1. Field: như LabelField, CheckboxField ...
2. Manager.
3. Screen.
Như trên hình các bạn thấy, có các button, checkbox, bitmapField, editField là các thực thể chúng ta cần xử lý.
Đoạn code dưới đây sẽ cho bạn biết cách thực hiện tạo các đối tượng, xử lý các sự kiện trên đối tượng đó.
Mình dùng IDE: Blackberry java Plug-in 1.5 và emulator : BlackBerry 9930.
Code tạo ra các đối tượng và thêm các đối tượng vào Screen :


Bitmap bitmap = Bitmap.getBitmapResource("img/ic_logo.png");
BitmapField bitmapField = new BitmapField(bitmap, Field.FIELD_HCENTER);
add(bitmapField);

add(new SeparatorField());
add(new LabelField("Please enter your infomation ?"));

usernameField = new EditField("Username", "");
passwordField = new EditField("Password", "");
add(usernameField);
add(passwordField);

domainField = new ObjectChoiceField("Domain :", new String[] { "Home",
"Work" });
add(domainField);

rememberChechBox = new CheckboxField("Remember password ?", false);
add(rememberChechBox);

add(new SeparatorField());
clearButton = new ButtonField("Clear", ButtonField.CONSUME_CLICK);
loginButton = new ButtonField("Login", ButtonField.CONSUME_CLICK);

HorizontalFieldManager buttonManager = new HorizontalFieldManager(
Field.FIELD_RIGHT);
buttonManager.add(clearButton);
buttonManager.add(loginButton);
add(buttonManager);

Đăng ký xử lý sự kiện cho 2 button clear and login button như sau :
trước hết chúng ta implements interface : FieldChangeListener.
đăng ký sự kiện :


clearButton.setChangeListener(this);
loginButton.setChangeListener(this);

Và xử lý sự kiện trong phương thức  :   fieldChanged



public void fieldChanged(Field field, int context) {
// TODO Auto-generated method stub
if (field == clearButton) {
// Dialog.inform("clear button clicked!!!");
clearTextFields();
}
if (field == loginButton) {
// Dialog.inform("login button clicked!!!");
login();
}
}



  private void login() {
// TODO Auto-generated method stub
if (usernameField.getTextLength() == 0
|| passwordField.getTextLength() == 0) {
Dialog.inform("Please enter text field!!!");
} else {
String username = usernameField.getText();
String selectedDomain = (String) domainField.getChoice(domainField
.getSelectedIndex());
LoginSuccessScreen loginSuccessScreen = new LoginSuccessScreen(
username, selectedDomain);
UiApplication.getUiApplication().pushScreen(loginSuccessScreen);
}
}




private void clearTextFields() {
// TODO Auto-generated method stub
usernameField.setText("");
passwordField.setText("");
}



Vì BlackBerry thừa hưởng rất nhiều từ nền tảng JavaME nên nếu nắm chắc các điểm quan trọng của ngôn ngữ java bạn sẽ dễ nắm bắt hơn.




Phương thức tạo menu trong lập trình bb :

 protected void makeMenu(Menu menu, int instance) {
// TODO Auto-generated method stub
super.makeMenu(menu, instance);
menu.add(new MenuItem("Login", 20, 10){
public void run() {
// TODO Auto-generated method stub
login();
}
});
menu.add(new MenuItem("Clear", 10, 20){
public void run() {
clearTextFields();
}
});

}



Download project tại đây

Bạn nên thực hành trước khi import project. Nếu có thắc mắc gì, comment ở dưới bài viết này. Thân.






Bản beta đầu tiên

Sau 6 tháng cả team cặm cụi làm việc điên cuồng, bản alpha cũng được giới thiệu ra toàn bộ công ty và được testing nội bộ công ty mà thôi. ...