Computer >> Máy Tính >  >> Lập trình >> Android

Làm cách nào để chạy dịch vụ Android luôn ở chế độ nền bằng Kotlin?

Ví dụ này trình bày cách chạy dịch vụ Android luôn ở chế độ nền bằng Kotlin.

Bước 1 - Tạo một dự án mới trong Android Studio, vào Tệp? Dự án mới và điền tất cả các chi tiết bắt buộc để tạo một dự án mới.

Bước 2 - Thêm mã sau vào res / layout / activity_main.xml.

Ví dụ

      

Bước 3 - Tạo một lớp Kotlin mới MyService.kt và thêm mã sau

 import android.app.Serviceimport android.content.Intentimport android.os.IBinderimport android.widget.Toastclass MyService:Service () {ghi đè fun onStartCommand (ý định:Intent, flags:Int, startId:Int):Int {onTaskRemoved (ý định) Toast.makeText (applicationContext, "Đây là một Dịch vụ chạy trong Nền", Toast.LENGTH_SHORT) .show () return START_STICKY} ghi đè onBind vui nhộn (ý định:Intent):IBinder? {// VIỆC CẦN LÀM:Trả lại kênh liên lạc cho dịch vụ. ném UnsupportedOperationException ("Chưa được triển khai")} ghi đè fun onTaskRemoved (rootIntent:Intent) {val restartServiceIntent =Intent (applicationContext, this.javaClass) restartServiceIntent.setPackage (packageName) startService (restartServiceIntent) super.on trước> 

Bước 4 - Thêm mã sau vào src / MainActivity.kt

 import android.content.Intentimport android.os.Bundleimport android.widget.Buttonimport androidx.appcompat.app.AppCompatActivityclass MainActivity:AppCompatActivity () {ghi đè fun onCreate (saveInstanceState:Bundle?) {super.onCreate (SaveInstanceState) R.layout.activity_main) title ="KotlinApp" val button:Button =findViewById (R.id.button) button.setOnClickListener {startService (Intent (applicationContext, MyService ::class.java))}}} 

Bước 5 - Thêm mã sau vào androidManifest.xml

   <ứng dụng android:allowBackup =" true "android:icon =" @ mipmap / ic_launcher "android:label =" @ string / app_name "android:roundIcon =" @ mipmap / ic_launcher_round "android:supportsRtl =" true "android :theme ="@ style / AppTheme">          

Hãy thử chạy ứng dụng của bạn. Tôi giả sử bạn đã kết nối thiết bị Di động Android thực tế với máy tính của mình. Để chạy ứng dụng từ android studio, hãy mở một trong các tệp hoạt động của dự án của bạn và nhấp vào biểu tượng Run Làm cách nào để chạy dịch vụ Android luôn ở chế độ nền bằng Kotlin? từ thanh công cụ. Chọn thiết bị di động của bạn làm tùy chọn, sau đó kiểm tra thiết bị di động sẽ hiển thị màn hình mặc định của bạn

Làm cách nào để chạy dịch vụ Android luôn ở chế độ nền bằng Kotlin?

Làm cách nào để chạy dịch vụ Android luôn ở chế độ nền bằng Kotlin?