1. Trang chủ
  2. » Công Nghệ Thông Tin

Lập trình android chapter22 services

31 223 1

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

22 Android Services Notes are based on: Android Developers http://developer.android.com/index.html 22 Android Services Services Android Services Một Service component ứng dụng chạy background, không tương tác với người dùng, chạy khoảng thời gian không xác định Service, đối tượng ứng dụng khác (activitties, broadcast listeners…), chạy thread tiến trình chủ Nghĩa là, service định làm chiếm CPU (chẳng hạn MP3 playback) đợi lâu (networking), nên tạo thread riêng để làm việc Mỗi service phải có khai báo  tại AndroidManifest.xml package Service gọi bằng Context.startService() và Context.bindService()   2 22 Android Services Services Android Services • Đối với service, nhiều lời gọi Context.startService() dẫn đến việc phương thức onStartCommand() Service class gọi nhiều lần) Tuy nhiên, cần lần Context.stopService() hay stopSelf() gọi đủ để kết thúc service • Một service khởi động chạy dừng nó tự dừng 3 22 Android Services Services Service Life Cycle CŨng activity, service có phương thức lifecycle mà ta cài để giám sát thay đổi trạng thái Nhưng service có phương thức life cycle hơn, chúng dạng public protected: void onCreate ()  void onStartCommand (Intent intent,…) void onDestroy () 4 22 Android Services Services Service Life Cycle The entire lifetime of a service happens between the time  onCreate() is called and the time onDestroy() returns Toàn đời service bắt đầu onCreate() được gọi kết thúc khi onDestroy() trả Like an activity, a service does its initial setup in onCreate(), and releases all remaining resources in onDestroy() Cũng activity, service thực công việc khởi tạo onCreate() trả tất tài nguyên lại OnDestroy() For example, a music playback service could create the thread where the music will be played in onCreate(), and then stop the thread in onDestroy() Ví dụ, service chơi nhạc tạo thread phụ chơi nhạc phương thức onCreate(), dừng thread onDestroy() 5 22 Android Services Services Broadcast Receiver Lifecycle A Broadcast Receiver lớp ứng dụng nghe global Intent gửi cho tất muốn nghe (thay gửi cho ứng dụng/activity định trước) Hệ thống gửi broadcast Intent cho tất broadcast receiver quan tâm, chúng xử lý Intent 6 22 Android Services Services Registering a Broadcast Receiver • Ta đăng ký động (tại mã chương trình) thực thể BroadcastReceiver lời gọi Context.registerReceiver() • đăng kí tĩnh cách khai báo thẻ AndroidManifest.xml 7 22 Android Services Services Broadcast Receiver Lifecycle onReceive Mỗi broadcast receiver có callback method: void onReceive (Context  context, Intent broadcastMsg) Khi broadcast message gửi đến receiver, Android gọi phương thức onReceive() của receiver truyền cho đối tượng Intent chứa message Một broadcast receiver coi active (đang chạy) thực thi phương onReceive() Khi onReceive() kết thúc, receiver quay lại trạng thái inactive * callback method phương thức dành riêng để hệ thống gọi có kiện xảy ra, không gọi trực tiếp mã chương trình 8 22 Android Services Services Services, BroadcastReceivers and the AndroidManifest Manifest ứng dụng dùng Android Services phải có chứa: Một entry (mục) cho service dùng ứng dụng Nếu ứng dụng định nghĩa BroadcastReceiver hình thức lớp độc lập, manifest phải có clause (mệnh đề) xác định component Ngoài ra, cần entry để khai báo filter mà service receiver sử dụng See example 9 22 Android Services Services Services, BroadcastReceivers and the AdroidManifest 10 10 22 Android Services Example cont //non CPU intensive service running the main task in its main thread package es.demo; import public class MyService1 extends Service { @Override public IBinder onBind(Intent arg0) { return null; } @Override public void onCreate() { super.onCreate(); Log.i ("", "I am alive-1!"); } @Override public int onStartCommand(Intent intent, int flags, int startId) { super.onStartCommand(intent, flags, startId); Log.i ("", "I did something very quickly"); return START_STICKY; } @Override public void onDestroy() { super.onDestroy(); Log.i ("", "I am dead-1"); } } 17 17 22 Android Services Services Example cont According to the Log Main Activity is started (no displayed yet) Service is started (onCreate, onStart) Main Activity UI is displayed User stops Service 18 18 22 Android Services Services Example cont Manifest 19 19 22 Android Services Services Example cont Layout >>", e.getMessage() ); } Log.e ("MAIN3-DESTROY>>>" , "Adios" ); } //onDestroy 26 26 22 Android Services Services Example Main Activity ////////////////////////////////////////////////////////////////////// // local (embedded) RECEIVER public class MyMainLocalReceiver extends BroadcastReceiver { @Override public void onReceive(Context localContext, Intent callerIntent) { Get data String serviceData = callerIntent.getStringExtra("serviceData"); Log.e ("MAIN>>>", serviceData + " -receiving data " + SystemClock.elapsedRealtime() ); String now = "\n" + serviceData + " - " + new Date().toLocaleString(); txtMsg.append(now); } }//MyMainLocalReceiver }//MyServiceDriver3 27 27 22 Android Services Example The Service // Service3 uses a thread to run slow operation package es.demos; import android.app.Service; import android.content.Intent; import android.os.IBinder; import android.util.Log; public class MyService3 extends Service { boolean isRunning = true; @Override public IBinder onBind(Intent arg0) { return null; } @Override public void onCreate() { super.onCreate(); } 28 28 22 Android Services Example The Service @Override public int onStartCommand(Intent intent, int flags, int startId) { super.onStartCommand(intent, flags, startId); Log.e ("", "I am alive-3!"); // we place the slow work of the service in its own thread // so the caller is not up waiting for us Thread triggerService = new Thread ( new Runnable(){ long startingTime = System.currentTimeMillis(); long tics = 0; public void run() { for(int i=0; (i< 120) & isRunning; i++) { //at most 10 minutes try { //fake that you are very busy here tics = System.currentTimeMillis() - startingTime; Intent myFilteredResponse = Set filter new Intent("es.action.GOSERVICE3"); String msg = i + " value: " + tics; myFilteredResponse.putExtra("serviceData", msg); broadcasting sendBroadcast(myFilteredResponse); Thread.sleep(1000); //five seconds } catch (Exception e) { e.printStackTrace(); } }//for }//run }); triggerService.start(); return START_STICKY; }//onStartCommand 29 29 22 Android Services Services Example The Service @Override public void onDestroy() { super.onDestroy(); Log.e ("", "I am dead-3"); isRunning = false; Thread is now stopped }//onDestroy }//MyService3 30 30 22 Android Services Services Questions 31 31 ... xác định Service, đối tượng ứng dụng khác (activitties, broadcast listeners…), chạy thread tiến trình chủ Nghĩa là, service định làm chiếm CPU (chẳng hạn MP3 playback) đợi lâu (networking), nên... 22 Android Services Services Registering a Broadcast Receiver • Ta đăng ký động (tại mã chương trình) thực thể BroadcastReceiver lời gọi Context.registerReceiver() • đăng kí tĩnh cách khai báo... callback method phương thức dành riêng để hệ thống gọi có kiện xảy ra, không gọi trực tiếp mã chương trình 8 22 Android Services Services Services, BroadcastReceivers and the AndroidManifest Manifest

Ngày đăng: 07/09/2017, 23:16

Xem thêm: Lập trình android chapter22 services

TỪ KHÓA LIÊN QUAN

w