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

Làm cách nào để tạo một dịch vụ android mà dalvik sẽ không giết?

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ị phá hủy.

Ví dụ này minh họa về Cách tôi có thể tạo một dịch vụ android mà dalvik sẽ không giết.

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 dịch vụ và dừng dịch vụ. 

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.SuppressLint; 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.os.PowerManager; nhập android.support.annotation.RequiresApi; nhập android.support.v4.app.NotificationCompat; nhập android.util.Log; nhập android.widget.Toast; dịch vụ lớp công khai mở rộng Dịch vụ { Chiều PowerManager; @SuppressLint ("InvalidWakeLockTag") PowerManager.WakeLock wl; @Override public IBinder onBind (Ý định có ý định) {return null; } @SuppressLint ("InvalidWakeLockTag") @Override public void onCreate () {super.onCreate (); pm =(PowerManager) getSystemService (Context.POWER_SERVICE); wl =pm.newWakeLock (PowerManager.SCREEN_DIM_WAKE_LOCK, "Thẻ của tôi"); } @TargetApi (Build.VERSION_CODES.O) @RequiresApi (api =Build.VERSION_CODES.JELLY_BEAN) @Override public int onStartCommand (Intent Ý định, int flags, int startId) {wl.acquire (); // Thực hiện một số tác vụ Toast.makeText (đây, "Dịch vụ thông báo do người dùng bắt đầu.", Toast.LENGTH_LONG) .show (); trả lại START_STICKY; } @RequiresApi (api =Build.VERSION_CODES.N) @Override public void onDestroy () {super.onDestroy (); wl.release (); 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 đã gọi trình quản lý nguồn để dừng khóa màn hình để luồng android sẽ không dừng chuỗi dịch vụ như hình dưới đây -

 @SuppressLint ("InvalidWakeLockTag") @ Overridepublic void onCreate () {super.onCreate (); pm =(PowerManager) getSystemService (Context.POWER_SERVICE); wl =pm.newWakeLock (PowerManager.SCREEN_DIM_WAKE_LOCK, "Thẻ của tôi");} @ TargetApi (Build.VERSION_CODES.O) @RequiresApi (api =Build.VERSION_CODES.JELLY_BEAN) @Overridepublic int onStartCommand (Intent Ý định, ) {wl.acquire (); // Thực hiện một số tác vụ Toast.makeText (đây, "Dịch vụ thông báo do người dùng bắt đầu.", Toast.LENGTH_LONG) .show (); return START_STICKY;} @ RequestApi (api =Build.VERSION_CODES.N) @Overridepublic void onDestroy () {super.onDestroy (); wl.release (); Toast.makeText (đây, "Dịch vụ thông báo bị người dùng phá hủy.", Toast.LENGTH_LONG) .show ();} 

Bước 4 - Thêm mã sau vào tệp kê khai.xml

              

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 cách nào để tạo một dịch vụ android mà dalvik sẽ không giết?

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 cách nào để tạo một dịch vụ android mà dalvik sẽ không giết?

Trong kết quả trên, dịch vụ là startd bây giờ bấm vào xem văn bản, nó sẽ dừng dịch vụ thông báo như hình bên dưới -

Làm cách nào để tạo một dịch vụ android mà dalvik sẽ không giết?