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

Làm thế nào để triển khai start Foreground cho một dịch vụ?

Trước khi đi vào ví dụ, chúng ta nên biết dịch vụ nào trong android. Dịch vụ sẽ hoạt động trở lại mà không cần tương tác với giao diện người dùng và nó hoạt động ngay cả sau khi hoạt động bị hủy

Ví dụ này minh họa về Cách triển khai start Foreground cho một dịch vụ.

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

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

    
 Trong đoạn mã trên, chúng ta đã sử dụng chế độ xem văn bản, khi người dùng nhấp vào chế độ xem văn bản, nó sẽ bắt đầu startForeground (). 

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

 package com.example.andy.myapplication; nhập android.app.ActivityManager; nhập android.content.Context; nhập android.content.Intent; nhập android.support.v7.app.AppCompatActivity; nhập android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.TextView; public class MainActivity mở rộng AppCompatActivity {@Override được bảo vệ void onCreate (Gói đã lưuInstanceState) {super.onCreate (saveInstanceState); setContentView (R.layout.activity_main); cuối cùng TextView text =findViewById (R.id.text); text.setOnClickListener (new View.OnClickListener () {@Override public void onClick (View v) {if (isMyServiceRunning (service.class)) {text.setText ("Đã dừng"); stopService (Ý định mới (MainActivity.this, dịch vụ .class));} else {text.setText ("Đã bắt đầu"); startService (new Intent (MainActivity.this, service.class));}}}); } private boolean isMyServiceRunning (Class  serviceClass) {ActivityManager manager =(ActivityManager) getSystemService (Context.ACTIVITY_SERVICE); for (Dịch vụ ActivityManager.RunningServiceInfo:manager.getRunningServices (Integer.MAX_VALUE)) {if (serviceClass.getName (). equals (service.service.getClassName ())) {return true; }} trả về false; }} 

Trong đoạn mã trên để bắt đầu và dừng dịch vụ. Chúng tôi đã sử dụng ý định và chuyển ngữ cảnh và lớp dịch vụ. Bây giờ, hãy tạo một lớp dịch vụ trong thư mục gói dưới dạng service.class và thêm mã sau -

 package com.example.andy.myapplication; nhập android.annotation.TargetApi; nhập android.app.Notification; nhập android.app.NotificationChannel; nhập android.app.NotificationManager; nhập android.app.PendingIntent; nhập android. app.Service; nhập android.content.Context; nhập android.content.Intent; nhập android.graphics.Color; nhập android.media.MediaPlayer; nhập android.os.Build; nhập android.os.IBinder; nhập android.support .annotation.RequiresApi; nhập android.support.v4.app.NotificationCompat; nhập android.widget.Toast; dịch vụ lớp công khai mở rộng Dịch vụ {@Override public IBinder onBind (Ý định có ý định) {return null; } @Override public void onCreate () {super.onCreate (); } @TargetApi (Build.VERSION_CODES.O) @RequiresApi (api =Build.VERSION_CODES.JELLY_BEAN) @Override public int onStartCommand (Ý định, int cờ, int startId) {Toast.makeText (cái này, "Dịch vụ thông báo do người dùng bắt đầu. ", Bánh mì nướng.LENGTH_LONG) .show (); Chuỗi NOTIFICATION_CHANNEL_ID ="com.example.andy.myapplication"; String channelName ="Dịch vụ nền của tôi"; NotificationChannel chan =new NotificationChannel (NOTIFICATION_CHANNEL_ID, channelName, NotificationManager.IMPORTANCE_NONE); chan.setLightColor (Màu.BLUE); chan.setLockscreenVisibility (Notification.VISIBILITY_PRIVATE); NotificationManager manager =(NotificationManager) getSystemService (Context.NOTIFICATION_SERVICE); khẳng định người quản lý! =null; manager.createNotificationChannel (chan); Intent notificationIntent =new Intent (this, MainActivity.class); PendingIntent pendingIntent =PendingIntent.getActivity (this, 0, notificationIntent, 0); Notification notification =new Notification.Builder (this, NOTIFICATION_CHANNEL_ID) .setSmallIcon (R.mipmap.ic_launcher) .setContentTitle ("Ứng dụng tuyệt vời của tôi") .setContentIntent (pendingIntent) .build (); startForeground (1337, thông báo); trả lại START_STICKY; } @RequiresApi (api =Build.VERSION_CODES.N) @Override public void onDestroy () {super.onDestroy (); stopForeground (true); Toast.makeText (this, "Dịch vụ thông báo bị người dùng phá hủy.", Toast.LENGTH_LONG) .show (); }} 

Trong đoạn mã trên, chúng tôi đã sử dụng kênh thông báo và trình tạo thông báo như hình dưới đây -

 String NOTIFICATION_CHANNEL_ID ="com.example.andy.myapplication"; String channelName ="My Background Service"; NotificationChannel chan =new NotificationChannel (NOTIFICATION_CHANNEL_ID, channelName, NotificationManager.IMPORTANCE_NONE); chan.setLightColor (Màu sắc .setLockscreenVisibility (Notification.VISIBILITY_PRIVATE); NotificationManager manager =(NotificationManager) getSystemService (Context.NOTIFICATION_SERVICE); khẳng định người quản lý! =null; manager.createNotificationChannel (chan); Đang chờ thông báoIntent =new Intent (this, MainActivity.ctivity) PendingIntent.getActivity (this, 0, notificationIntent, 0); Notification notification =new Notification.Builder (this, NOTIFICATION_CHANNEL_ID) .setSmallIcon (R.mipmap.ic_launcher) .setContentbuildTitle ("Ứng dụng tuyệt vời của tôi"). SetContentIntent (pendingIntent). (); startForeground (1337, thông báo); 

Để bắt đầu và dừng nền trước, hãy sử dụng mã sau -

 startForeground (1337, thông báo); stopForeground (true); 

Bước 4 - Thêm mã sau vào tệp kê khai.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 Chạy 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 thế nào để triển khai start Foreground cho một dịch vụ?

Kết quả trên là màn hình ban đầu, Click vào Text view, nó sẽ bắt đầu dịch vụ Thông báo như hình bên dưới -
Làm thế nào để triển khai start Foreground cho một dịch vụ? Trong kết quả trên, dịch vụ startd bây giờ nhấp vào xem văn bản, nó sẽ dừng dịch vụ thông báo như hình dưới đây -

Làm thế nào để triển khai start Foreground cho một dịch vụ?