เริ่มต้นใช้งาน Android Notification
![เริ่มต้นใช้งาน Android Notification](/_vercel/image?url=%2Fimages%2F2015%2F08%2Fandroid-notification.png&w=828&q=80)
Image Credit : http://developer.android.com/
บทความว่าด้วยเรื่องการทำ Notification บน Android ในบทความนี้จะพูดถึงว่า Notification คืออะไร และการใช้งานเบื้องต้นเท่านั้น ไม่รวมถึง Push Notification ต่างๆ เช่น ใช้ Parse , GCM หรือ implement Server เอง (จะไว้เขียนในบทความถัดๆไป)
Notification
Notification คืออะไร ? จริงๆ Notification มันก็คือข้อความแจ้งเตือนรูปแบบหนึ่งเท่านั้น ซึ่งจะแตกต่างจากพวก Toast หรือ Snackbar ตรงที่ ไม่จำเป็นที่แอพพลิเคชันของเราทำงานอยู่ มันก็สามารถแสดงการแจ้งเตือนข้อความ Notification ได้ นอกจากข้อความแจ้งเตือนแล้ว Notification ยังสั่น หรือมีเสียงได้อีกด้วย
อ่านเพิ่มเติมเกี่ยวกับ Notification ได้ที่ Android Notifications
มาลองสร้าง Notification จริงๆกันเลยดีกว่า
Step 1 : Create Project
ทำการสร้างโปรเจ็ค Android ขึ้นมา โดยผมกำหนด API เวอร์ชั่น ดังภาพ
ควรทำการดาวน์โหลด Support Library มาซะก่อน เนื่องจากบทความนี้ใช้
NotificationCompat
ซึ่งมีใน Support Library เท่านั้น
ไฟล์หลักจะเป็น MainActivity.java
และเลเอาท์หลักจะเป็น activity_main.xml
Step 2 : Create Button
ต่อมาทำการเพิ่มปุ่ม Button ปุ่มนี้จะเอาไว้สำหรับกด เพื่อให้โชว์ Notification ฉะนั้นก็ไม่มีอะไรมาก ใช้ xml syntax onClick:""
ลงไปเลย เนื่องจากขี้เกียจ binding View ในโปรแกรม :) ฉะนั้นไฟล์ activity_main.xml
จะได้ดังนี้
1<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"2 xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"3 android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"4 android:paddingRight="@dimen/activity_horizontal_margin"5 android:paddingTop="@dimen/activity_vertical_margin"6 android:paddingBottom="@dimen/activity_vertical_margin"7 tools:context=".MainActivity">8
9 <Button10 android:id="@+id/btn_notification"11 android:layout_width="wrap_content"12 android:layout_height="wrap_content"13 android:layout_centerInParent="true"14 android:text="Show Notification"15 android:padding="32dp"16 android:onClick="showNotification"/>17
18</RelativeLayout>
ที่ไฟล์ MainActivity.java
ก็เพิ่มเมธอดสำหรับ onClick
event ดังนี้
1package com.devahoy.simplenotification;2
3import android.support.v7.app.AppCompatActivity;4import android.os.Bundle;5import android.view.View;6
7public class MainActivity extends AppCompatActivity {8
9 @Override10 protected void onCreate(Bundle savedInstanceState) {11 super.onCreate(savedInstanceState);12 setContentView(R.layout.activity_main);13 }14
15 public void showNotification(View view) {16 // your code goes here.17 }18
19}
Note : สำหรับวิธีการทำ Button OnClick สามารถอ่านเพิ่มเติมได้ที่นี่
Step 3 : Create Notification
ส่วนประกอบในการสร้าง Notification จะประกอบไปด้วย
- setContentTitle() : แสดงหัวข้อของ Notification
- setContentText() : เอาไว้แสดงข้อความของ Notification
- setSmallIcon() : เอาไว้แสดงไอคอนของ Notification
ส่วนประกอบอื่นๆ เป็น Optional เสริม เช่น
- setAutoCancel() : เอาไว้กำหนด ให้ลบ Notification เมื่อกดหรือไม่
- setGroup() : แบ่งกลุ่มให้กับ Notification
- setStyle() : ปรับแต่งรูปแบบ Notification
- setContentIntent() : เอาไว้ส่ง PendingIntent เมื่อกด Notification
การสร้าง Notification จะทำการสร้างจาก NotificationCompat.Builder
กัน โดยเพิ่มโค๊ดภายในเมธอด showNotification()
ดังนี้
1Notification notification =2 new NotificationCompat.Builder(this) // this is context3 .setSmallIcon(R.mipmap.ic_launcher)4 .setContentTitle("DevAhoy News")5 .setContentText("สวัสดีครับ ยินดีต้อนรับเข้าสู่บทความ Android Notification :)")6 .setAutoCancel(true)7 .build();
ตอนนี้เราก็ได้ Notification ขึ้นมาแล้ว โดยมีไอคอน หัวข้อ และข้อความตามที่เรากำหนด แต่ว่ามันจะไม่โชว์บน ActionBar จนกว่าเราจะสั่ง และคำสั่งที่จะใช้โชว์ก็คือ notify()
ซึ่งต้องใช้คลาส NotificationManager
เข้ามาช่วย ดังนี้
1NotificationManager notificationManager =2 (NotificationManager) getSystemService(NOTIFICATION_SERVICE);3notificationManager.notify(1000, notification);
โดยเมธอด notify(int id, Notification notification)
จะรับ parameter เป็น id และ ออปเจ็ค Notification ที่เราทำการสร้างขึ้นก่อนหน้านี้
ทดสอบรันโปรแกรม เมื่อคลิก Button จะเห็น Notification ปรากฎ แสดงว่าถูกต้อง
แต่ว่าเดี๋ยวก่อน เมื่อกดแล้วไม่มีอะไรเกิดขึ้นใช่หรือไม่? ต่อมาเราลองเขียนเพิ่ม ว่า เมื่อมีการกด Notification จะให้มันไปทำงานอะไรต่อดี
Step 4 : Notification Actions
ต่อมา ทำการเพิ่ม Action เมื่อกด Notification ในตัวอย่าง จะทำการเปิดเว็บไซต์ devahoy.com โดยใช้ PendingIntent ดังนี้ เพิ่มโค๊ดไว้ก่อนการสร้าง Notification
1Intent intent = new Intent(Intent.ACTION_VIEW,2 Uri.parse("https://devahoy.com"));3PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
จากนั้นตรงส่วน NotificationCompat.Builder()
ที่เอาไว้สร้าง Notification ก็ทำการเพิ่ม setContentIntent()
ดังนี้
1Notification notification =2 new NotificationCompat.Builder(this) // this is context3 .setSmallIcon(R.mipmap.ic_launcher)4 .setContentTitle("DevAhoy News")5 .setContentText("สวัสดีครับ ยินดีต้อนรับเข้าสู่บทความ Android Notification :)")6 .setAutoCancel(true7 .setContentIntent(pendingIntent)8 .build();
สุดท้ายเมธอด showNotification()
จะได้ดังนี้
1public void showNotification(View view) {2
3 Intent intent = new Intent(Intent.ACTION_VIEW,4 Uri.parse("https://devahoy.com/blog/2015/08/android-notification/"));5 PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);6
7 Notification notification =8 new NotificationCompat.Builder(this)9 .setSmallIcon(R.mipmap.ic_launcher)10 .setContentTitle("DevAhoy News")11 .setContentText("สวัสดีครับ ยินดีต้อนรับเข้าสู่บทความ Android Notification :)")12 .setAutoCancel(true)13 .setContentIntent(pendingIntent)14 .build();15
16 NotificationManager notificationManager =17 (NotificationManager) getSystemService(NOTIFICATION_SERVICE);18 notificationManager.notify(1000, notification);19}
เอ๊ะถ้าเรา อยากจะทำการเปิดอีก Activity แทนที่จะเปิดหน้าเว็บด้วย PendingIntent จะทำได้ไหม ? คำตอบคือได้ครับ
Step 5 : Start new Activity
ทำการสร้าง Activity ขึ้นมาใหม่อีกหนึ่งตัวชื่อว่า PushActivity.java
1package com.devahoy.simplenotification;2
3import android.os.Bundle;4import android.support.v7.app.AppCompatActivity;5
6public class PushActivity extends AppCompatActivity {7
8 @Override9 protected void onCreate(Bundle savedInstanceState) {10 super.onCreate(savedInstanceState);11 setContentView(R.layout.activity_push);12 }13}
และไฟล์ activity_push.xml
ดังนี้
1<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"2 xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"3 android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"4 android:paddingRight="@dimen/activity_horizontal_margin"5 android:paddingTop="@dimen/activity_vertical_margin"6 android:paddingBottom="@dimen/activity_vertical_margin"7 tools:context=".MainActivity">8
9 <TextView10 android:id="@+id/txt_message"11 android:layout_width="wrap_content"12 android:layout_height="wrap_content"13 android:layout_centerInParent="true"/>14
15</RelativeLayout>
จากนั้นเพิ่ม PushActivity
ลงไปใน AndroidManifest.xml
ดังนี้
1<application2 android:allowBackup="true"3 android:icon="@mipmap/ic_launcher"4 android:label="@string/app_name"5 android:theme="@style/AppTheme" >6 <activity7 android:name=".MainActivity"8 android:label="@string/app_name" >9 <intent-filter>10 <action android:name="android.intent.action.MAIN" />11 <category android:name="android.intent.category.LAUNCHER" />12 </intent-filter>13 </activity>14
15 <activity16 android:name=".PushActivity"17 android:parentActivityName=".MainActivity">18 <meta-data19 android:name="android.support.PARENT_ACTIVITY"20 android:value=".MainActivity"/>21 </activity>22 </application>
จากนั้นที่คลาส MainActivity.java
ทำการสร้าง Intent
ขึ้นมาใหม่แทนอันเก่า ดังนี้
1// Uri.parse("https://devahoy.com/posts/android-notification/"));2// PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);3
4Intent intent = new Intent(this, PushActivity.class);5intent.putExtra("message", MESSAGE);6TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);7stackBuilder.addParentStack(PushActivity.class);8stackBuilder.addNextIntent(intent);9PendingIntent pendingIntent =10 stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
ส่วนข้อความและ title ก็ประกาศเป็น static final ไป
1private static final String TITLE = "Devahoy News";2private static final String MESSAGE = "สวัสดีครับ ยินดีต้อนรับเข้าสู่บทความ Android Notification :)";
เมื่อแตะ Notification จะ putExtra()
ส่งข้อความไปยัง PushActivity
ด้วย ฉะนั้นที่คลาส PushActivity.java
ก็ทำการรับ Intent และแสดงข้อความใส่ TextView ดังนี้
1package com.devahoy.simplenotification;2
3import android.os.Bundle;4import android.support.v7.app.AppCompatActivity;5import android.widget.TextView;6
7public class PushActivity extends AppCompatActivity {8
9 @Override10 protected void onCreate(Bundle savedInstanceState) {11 super.onCreate(savedInstanceState);12 setContentView(R.layout.activity_push);13
14 Bundle bundle = getIntent().getExtras();15
16 String message = bundle.getString("message");17
18 TextView textView = (TextView) findViewById(R.id.txt_message);19 textView.setText(message);20 }21}
ทดสอบรันโปรแกรมอีกครั้ง ลองกดปุ่ม Button เพื่อแสดง Notification และเมื่อแตะ Notification แอพก็จะไปเปิดหน้า PushActivity ซึ่งมีข้อความแสดงอยู่ เป็นอันเรียบร้อย :D
สรุปขั้นตอนการสร้าง Notification
- ใช้
Notification.Builder()
เพื่อทำกำหนดค่าต่างๆ จากนั้นbuild()
เพื่อให้ได้ออปเจ็คNotification
ขึ้นมา - ใช้
NotificationManager
เพื่อทำการแสดง Notification ด้วยnotify()
- หากต้องการเพิ่ม Action ให้ Notification ก็ต้องทำการกำหนด ก่อนที่จะทำการ
build()
สุดท้าย Notification ก็ยังมีอะไรให้เล่นอีกเยอะ custom อะไรได้มากมาย ทั้งการใส่ Progress ลงบน Notification การกำหนดความสำคัญ (Priority) ใส่การสั่น เพิ่มเสียง เพ่ิม/ลบ Stack Notification หรืออื่นๆอีกเยอะแยะ ลองไปเล่นกันดูครับ สำหรับบทความนี้ก็ขอฝากไว้เพียงเท่านี้ :)
- Authors
-
Chai Phonbopit
เป็น Web Dev ในบริษัทแห่งหนึ่ง ทำงานมา 10 ปีกว่าๆ ด้วยภาษาและเทคโนโลยี เช่น JavaScript, Node.js, React, Vue และปัจจุบันกำลังสนใจในเรื่องของ Blockchain และ Crypto กำลังหัดเรียนภาษา Rust