سلام دوستان امیدوارم حالتان خوب باشد در این سری از آموزش برنامه نویسی اندروید به آموزش Notification به زبان کوتلین در برنامه نویسی اندروید می پردازیم قبلا آموزش Notification Builder را به زبان جاوا برای شما قرار داده بودیم در امروز Notification را به زبان کوتلین برای شما توضیح خواهیم داد در ادامه می توانید پیش نمایشی از آن را مشاهده کنید با ما همراه باشید.
ابتدا شما باید زبان کوتلین را به اندروید استودیو اضافه کنید برای اینکار باید از آموزش زیر استفاده کنید.
حالا وارد layout شده (در اینجا activity_main.xml است ) و یک دکمه (button) همانند زیر در آن قرار دهید.
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:paddingLeft="16dp"
android:paddingRight="16dp" >
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Show Notification"
android:id="@+id/button" />
</LinearLayout>
</RelativeLayout>
سپس وارد اکتیویتی مربوط به آن شده در اینجا نام آن برابر با MainActivity.kt است و کدهای زیر را در آن قرار دهید.
package ir.programchi
import android.app.Notification
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.support.v7.app.NotificationCompat
import android.widget.Button
import android.widget.ProgressBar
class Main2Activity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val Btn_Notification = findViewById(R.id.btn_notification) as Button
Btn_Notification.setOnClickListener{
val intent = Intent()
val pendingIntent = PendingIntent.getActivity(this@MainActivity,0,intent,0)
val notification= Notification.Builder(this@MainActivity)
.setTicker("")
.setContentTitle("Notification Title")
.setContentText("Programchi.ir")
.setSmallIcon(R.mipmap.ic_launcher)
.setContentIntent(pendingIntent).notification
notification.flags = Notification.FLAG_AUTO_CANCEL
val notificaionmanager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificaionmanager.notify(0,notification)
}
}
}
در بالا ابتدا view مربوط به دکمه را find کردیم سپس یک رویداد کلیک برای آن ایجاد کرده و کدمان را داخل آن نوشته ایم.
setTicker : مقدار Ticker را تنظیم می کند (در بعضی از گوشی ها پشتیبانی می شود)
setContentTitle : متنی که در عنوان قرار می گیرد را تنظیم می کند.
setContentText: متنی که زیر عنوان قرار می گیرد را تنظیم می کند.
setSmallIcon : آیکونی که در سمت چپ نمایش داده می شود را تنظیم می کند.
setContentIntent : این ویژگی Intent را آماده می کند تا Notification را نمایش دهد.
FLAG_AUTO_CANCEL : یعنی اینکه کاربر بتواند آن Notification را خودش حذف کند (Cancel کند).
این آموزش هم به پایان رسید.
موفق و موید باشید.
مطالعه بیشتر