make-money-468x60

Tìm hiểu Activity trong Android - Activity on Android

Tìm hiểu Activity trong Android - Activity on Android

1. Khái niệm về Activity.

Activity một class kế thừa từ lớp android.app.activity. Mỗi Activity sẽ trình diễn ứng dụng Android. Activity sẽ sử dụng các views để tạo nên giao diện của Android, nó xử lý các các thao tác mà người dùng thực hiện với ứng dụng.
Một ứng dụng có thể có nhiều activities.
Ví dụ khai báo một activity trong Android.
package vn.edu.humg.android_course.HelloWorld;
import android.app.Activity;
import android.os.Bundle;

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


2. Vòng đời hoạt động của Activity
Vòng đời của mỗi Activity trải qua các trạng thái nhất định. Tại mỗi trạng thái sẽ có sự kiện tương ứng được gọi đến. Các sự kiện này được khai báo trong lớp cơ sở (android.app.Activity). Chúng ta có thể nạp chồng các sự kiện này để theo dõi vòng đời của Activity và có những tác động thích hợp. Các sự kiện như vậy bao gồm:
   + onCreate() – được gọi khi Activity được khởi tạo
   + onStart() – được gọi khi Activity bắt đầu hiện ra (chúng ta bắt đầu nhìn thấy giao diện)
   + onResume() – bắt đầu nhận các tương tác với người dùng
   + onPause() – được gọi khi activity bi dừng lại để chuyển qua activity khác
   + onStop() – được gọi khi activity biến mất khỏi màn hình
   + onDestroy() – được gọi khi activity bị hủy (hủy chủ động hoặc bị hủy bởi hệ thống trong trường hợp hệ điều hành xác nhận thiếu RAM)
   + onRestart() – được gọi khi activity được khởi động lại sau khi đã bị dừng
Hình 1. Vòng đời hoạt động của một Activity.
Để hiểu rỏ hơn tôi sẽ lấy ví dụ cho các bạn thấy vòng đời của ứng dụng nó hoạt động như thế nào nhé. Đầu tiên các bạn tạo một Activity đơn giản với các phương thức nạp chồng.
public class Activity101Activity extends Activity {
    String tag = "Lifecycle";

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //---hides the title bar---
        requestWindowFeature(Window.FEATURE_NO_TITLE);

        setContentView(R.layout.main);
        Log.d(tag, "In the onCreate() event");
    }

    public void onStart()
    {
        super.onStart();
        Log.d(tag, "In the onStart() event");
    }

    public void onRestart()
    {
        super.onRestart();
        Log.d(tag, "In the onRestart() event");
    }

    public void onResume()
    {
        super.onResume();
        Log.d(tag, "In the onResume() event");
    }

    public void onPause()
    {
        super.onPause();
        Log.d(tag, "In the onPause() event");
    }

    public void onStop()
    {
        super.onStop();
        Log.d(tag, "In the onStop() event");
    }

    public void onDestroy()
    {
        super.onDestroy();
        Log.d(tag, "In the onDestroy() event");
    }
}


3. Dialog trong Activity.
 Trong các nhiều trường hợp xuất hiện các thông báo để xác nhận các điều khoản khi người dùng muốn hiện thị hay lưu trữ một vấn đề gì đó.
Sau đây là các bước để tạo một dialog trong Activity  android.
Bước 1. Tạo một project trong Android studio
Bước 2. Tạo file layout với tên như sau Main.xml như sau.
<?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" >

<Button
    android:id="@+id/btn_dialog"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Click to display a dialog"
    android:onClick="onClick" />
</LinearLayout>

Bước 3. Để ý tham số android:onClick="onClick" của nút bấm btn_dialog. Tham số này chỉ ra rằng bạn cần khai vào một phương thức tên là onClick trong Activity để xử lý sự kiện khi nút bấm này được chọn.

Bước 4. Thêm đoạn mã sau vào DialogActivity.java:
public class DialogActivity extends Activity {
    CharSequence[] items = { "Google", "Apple", "Microsoft" };
    boolean[] itemsChecked = new boolean [items.length];

    ProgressDialog progressDialog;

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

    public void onClick(View v) {
        showDialog(0);
    }

    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
        case 0:
        return new AlertDialog.Builder(this)
        .setIcon(R.drawable.ic_launcher)
        .setTitle("This is a dialog with some simple text...")
        .setPositiveButton("OK",
            new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog,    int whichButton) {
                    Toast.makeText(getBaseContext(), "OK clicked!",  Toast.LENGTH_SHORT).show();
                }
            })
        .setNegativeButton("Cancel",
            new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                    Toast.makeText(getBaseContext(), "Cancel clicked!", Toast.LENGTH_SHORT).show();
                }
            })
        .setMultiChoiceItems(items, itemsChecked,
            new DialogInterface.OnMultiChoiceClickListener() {                    public void onClick(DialogInterface dialog, int which, boolean isChecked) {
                    Toast.makeText(getBaseContext(), items[which] + (isChecked ? " checked!":" unchecked!"), Toast.LENGTH_SHORT).show();
                }
            }).create();
        }
        return null;
    }
}

4. Các đối tượng Content trong Activity
Trong Android, rất nhiều phương thức lấy một trong những tham số là một đối tượng của lớp Context. Trong ví dụ trên, hàm dựng của lớp AlertDialog.Builder và hàm Toast.makeText đều nhận tham số kiểu Context. Đối tượng kiểu Context này thường dùng để chỉ ra phạm vi, hay ngữ cảnh của phương thức được gọi và thường trỏ đến ứng dụng hoặc activity hiện tại.

Ở ví dụ trên ta thấy đối tượng của lớp AlertDialog.Builder được gọi với tham số this: new AlertDialog.Builder(this). Đối tượng this ở đây là Activity hiện tại (Activity cũng là lớp con cháu của lớp Context), trong khi hàm Toast.makeText nhận tham số Context là getBaseContext() chứ không được dùng con trỏ this nữa, bởi vì phương thức này được gọi bên trong đối tượng của lớp DialogInterface.OnClickListener(), con trỏ this ở đây có kiểu OnClickListener chứ không phải Activity, nên không phải là Context. Vì vậy, ta dùng hàm getBaseContext() để lấy Context cơ sở của đối tượng hiện tại. Một cách khác có thể sử dụng là dùng DialogActivity.this.