Daily Archives: 03/06/2016

Android – Hiển thị Notification

Notification (thông báo) là một tin nhắn được nhắn tới cho người dùng ở bên ngoài giao diện của ứng dụng. Các thông báo được hệ điều hành hiển thị trên vùng thông báo, khi có tin nhắn thông báo, hệ điều hành sẽ hiển thị biểu tượng của tin nhắn, nếu người dùng muốn xem nội dung thông báo thì phải mở phần thông báo đó ra (bằng cách dùng tay kéo), đây là khu vực được quản lý bởi hệ điều hành, người dùng có thể xem bất kỳ lúc nào.

Tạo thông báo

Chúng ta dùng lớp android.app.Notification để tạo thông báo, tuy nhiên chúng ta không tạo trực tiếp từ lớp này mà dùng lớp Notification.Builder. Việc quản lý các thông báo được thực hiện bởi lớp android.app.NotificationManager, khi muốn hiển thị thông báo thì chúng ta sử dụng phương thức NotificationManager.notify().

Một đối tượng Notification cần có ít nhất 3 thông tin sau:

  • Biểu tượng của tin nhắn, được thiết lập bằng phương thức setSmallIcon().
  • Tiêu đề của tin nhắn, thiết lập bằng phương thức setContentTitle().
  • Nội dung tin nhắn, thiết lập bằng phương thức setContentText().

Ngoài 3 thông tin bắt buộc ở trên, chúng ta còn có thể thêm vào các Action, đây là các nút bấm hiển thị cùng với tin nhắn, khi người dùng xem tin nhắn thì có thể bấm vào các nút này để thực hiện các công việc khác nhau.

Khi người dùng click vào tin nhắn thông báo, thường thì chúng ta nên mở một Activity nào đó và thực hiện công việc nào đó, tuy nhiên việc này là không bắt buộc. Chúng ta sử dụng lớp android.app.PendingIntent, lớp này chứa một đối tượng Intent dùng để mở một Activity nào đó. Để thiết lập cho tin nhắn mở Activity nào thì chúng ta dùng phương thức setContentIntent().

Ví dụ

Chúng ta tạo một project mới. Trong project này chúng ta định nghĩa 2 ActivityMainActivity được khởi động khi chạy ứng dụng, và ResultActivity được khởi động khi click vào tin nhắn.

Trong file AndroidManifest.xml chúng ta khai báo lớp ResultActivity.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" 
    package="com.phocode" 
    android:versionCode="1" 
    android:versionName="1.0">
    <application 
        android:label="@string/app_name" 
        android:icon="@drawable/ic_launcher">
    <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>
    <activity android:name=".ResultActivity"/>
    </application>
</manifest>

Đầu tiên là file layout chính của lớp MainActivity:

<?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">
    <Button 
        android:id="@+id/btnNotification" 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content" 
        android:text="Send notification" 
        android:onClick="sendNotification"/>
</LinearLayout>

Chúng ta hiển thị một Button, click vào Button này thì gửi tin nhắn thông báo.

Tiếp theo là lớp MainActivity:

package com.phocode;

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

public class MainActivity extends Activity
{ 
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main); 
    } 
 
    public void sendNotification(View view)
    {
        Intent intent = new Intent(this, ResultActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, (int)System.currentTimeMillis(), intent, 0);
 
        Notification noti = new Notification.Builder(this)
            .setContentTitle("New message")
            .setContentText("Subject")
            .setSmallIcon(R.drawable.ic_launcher)
            .setContentIntent(pendingIntent)
            .build();
 
        NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
 
        noti.flags |= Notification.FLAG_AUTO_CANCEL;
        notificationManager.notify(0, noti);
    }
}

Phương thức sendNotification() sẽ được gọi khi người dùng click vào Button trên màn hình.

Intent intent = new Intent(this, ResultActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, (int)System.currentTimeMillis(), intent, 0);

Ở đây chúng ta tạo một đối tượng Intent trở tới lớp ResultActivity và đối tượng PendingIntent chứa đối tượng Intent vừa tạo.

Notification noti = new Notification.Builder(this)
    .setContentTitle("New message")
    .setContentText("Subject")
    .setSmallIcon(R.drawable.ic_launcher)
    .setContentIntent(pendingIntent)
    .build();

Trong đoạn code trên chúng ta tạo đối tượng Notification từ lớp Notification.Builder. Lưu ý phương thức build() sẽ trả về đối tượng Notification, tuy nhiên phương thức này chỉ có từ phiên bản API 16 trở lên, ở các phiên bản trước đó thì phương thức này có tên khác là getNotification().

noti.flags |= Notification.FLAG_AUTO_CANCEL;

Dòng code trên có nghĩa là ẩn thông báo đi sau khi người dùng đã click vào, nếu không thì chỉ khi dùng tay kéo đi thì thông báo mới biến mất.

notificationManager.notify(0, noti);

Phương thức notify() sẽ gửi đối tượng Notification đến hệ điều hành để hiển thị, tham số đầu tiên là Id mà chúng ta tự gán cho thông báo đó, nếu trước đó đã có tin nhắn thông báo có Id bị trùng thì tin nhắn thông báo đó sẽ bị ghi đè.

Tiếp theo là file layout của lớp ResultActivity:

<?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">
    <TextView 
        android:id="@+id/textView1" 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content" 
        android:text="Message received" />
</LinearLayout>

Chúng ta chỉ hiển thị một câu thông báo đơn giản thôi.

Cuối cùng là định nghĩa lớp ResultActivity:

package com.phocode;

import android.app.Activity;
import android.os.Bundle;

public class ResultActivity extends Activity
{
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.result);
    }
}

Chạy chương trình chúng ta có kết quả:

Screenshot_2016-06-03-18-38-45