Lập trình Android tiếng Việt - Chapter 22: Android Services

Android Services

 

Một Service là một component ứng dụng chạy tại background, không tương tác với người dùng, chạy trong khoảng thời gian không xác định.

 

Service, cũng như các đối tượng ứng dụng khác (activitties, broadcast listeners ), chạy tại thread chính của tiến trình chủ.

 

Nghĩa là, nếu một service định làm gì đó chiếm CPU (chẳng hạn MP3 playback) hoặc đợi lâu (networking), nó nên tạo một thread riêng để làm việc đó.

 

Mỗi service phải có một khai báo <service> tại AndroidManifest.xml của package.

 

Service được gọi bằng Context.startService() và Context.bindService().

 

 

pptx30 trang | Chuyên mục: Android | Chia sẻ: dkS00TYs | Lượt xem: 1991 | Lượt tải: 4download
Tóm tắt nội dung Lập trình Android tiếng Việt - Chapter 22: Android Services, để xem tài liệu hoàn chỉnh bạn click vào nút "TẢI VỀ" ở trên
ai lớp broadcast chính: Normal broadcast (được gửi bằng Context.sendBroadcast) hoàn toàn không đồng bộ (asynchronous). Tất cả các receiver của broadcast được chạy theo thứ tự không xác định, thường là chạy cùng lúc. Ordered broadcast (được gửi bằng Context.sendOrderedBroadcast) được gửi lần lượt đến cho từng receiver một. Khi đến lượt một receiver thực thi, nó có thể chuyển tiếp kết quả cho receiver tiếp theo, hoặc nó có thể hủy toàn bộ broadcast (abortBroadcast()) để broadcast đó sẽ không được gửi đến cho các receiver khác. Thứ tự thực thi của các receiver được kiểm soát bởi thuộc tính android:priority của intent-filter tương ứng; các receiver có cùng priority (độ ưu tiên) sẽ được chạy theo thứ tự bất kì. 12 12 12 22. Android Services Services 12 Useful Methods – The Driver Giả sử main activity MyService3Driver muốn tương tác với một service có tên MyService3. Activity chính có trách nhiệm thực hiện các việc sau: 1. Start the service called MyService3. Bật service 	Intent intentMyService = new Intent(this, MyService3.class); 	Service myService = startService(intentMyService); 2. Define corresponding receiver’s filter and register local receiver. Định nghĩa filter của receiver tương ứng và đăng ký receiver nội bộ. 	IntentFilter mainFilter = new IntentFilter("matos.action.GOSERVICE3"); 	BroadcastReceiver receiver = new MyMainLocalReceiver(); 	registerReceiver(receiver, mainFilter); 3. Implement local receiver and override its main method 	public void onReceive(Context localContext, Intent callerIntent) 13 13 13 22. Android Services Services 13 Useful Methods – The Service Giả sử main activity MyService3Driver muốn tương tác với một service có tên MyService3. Activity đó dùng phương thức onStart của nó để làm việc sau: 1. Tạo một Intent với broadcast filter phù hợp (bao nhiêu receiver khớp với nó cũng được). Intent myFilteredResponse = new Intent("matos.action.GOSERVICE3"); 	 2. Chuẩn bị dữ liệu extra (‘myServiceData’) để gửi theo intent tới (các) receiver Object msg = some user data goes here; myFilteredResponse.putExtra("myServiceData", msg); 3. Gửi intent tới tất cả các receiver khớp với filter đã tạo sendBroadcast(myFilteredResponse); 14 14 14 22. Android Services Services 14 Useful Methods – The Driver (again) Giả sử main activity MyService3Driver muốn tương tác với một service có tên MyService3. Activity chính có trách nhiệm kết thúc service một cách sạch sẽ. Thực hiện như sau 1. Giả sử intentMyService là Intent đã được dùng để gọi service. Việc kết thúc service được làm bằng cách gọi phương thức stopService(new Intent(intentMyService) ); 2. Tại phương thức onDestroy của activity, đảm bảo rằng tất cả các thread đang chạy của nó được chấm dứt và receiver được hủy đăng ký. unregisterReceiver(receiver); 15 15 15 22. Android Services Example 1. A very Simple Service 15 Main activity bật một service. Service đó in vài dòng tại DDMS LogCat cho đến khi main activity dừng service. Không có liên lạc giữa các tiến trình khác nhau (IPC). // a simple service is started & stopped package es.demo; import android.app.Activity; import android.os.Bundle; import android.content.ComponentName; import android.content.Intent; import android.view.View; import android.view.View.OnClickListener; import android.widget.*; public class ServiceDriver1 extends Activity { TextView txtMsg; Button btnStopService; Intent intentMyService; ComponentName service; 16 16 16 22. Android Services Services 16 Example 1. cont. @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); txtMsg = (TextView) findViewById(R.id.txtMsg); intentMyService = new Intent(this, MyService1.class); service = startService(intentMyService); btnStopService = (Button) findViewById(R.id.btnStopService); btnStopService.setOnClickListener(new OnClickListener() { public void onClick(View v) { try { stopService((intentMyService) ); txtMsg.setText("After stoping Service: \n" + service.getClassName()); } catch (Exception e) { Toast.makeText(getApplicationContext(), e.getMessage(), 1).show(); } }//onClick }); } } 17 17 17 22. Android Services Example 1. cont. 17 //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"); 	} } 18 18 18 22. Android Services Services 18 Example 1. 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 19 19 19 22. Android Services Services 19 Example 1. cont. Manifest 20 20 20 22. Android Services Services 20 Example 1. cont. Layout 21 21 21 22. Android Services Example 2 21 Example 2. A More Realistic Activity-Service Interaction The main activity starts the service and registers a receiver. Activity chính bật service và đăng kí một receiver. The service is slow, therefore it runs in a parallel thread its time consuming task. Service chạy chậm, nên nó chạy công việc của nó trong một thread song song. When done with a computing cycle, the service adds a message to an intent. Sau mỗi chu kì tính toán, service gắn một message vào một intent The intent is broadcasted using the filter: matos.action.GOSERVICE3. Intent được broadcast bằng filter matos.action.GOSERVICE3 A BroadcastReceiver (defined inside the main Activity) uses the previous filter and catches the message (displays the contents on the main UI ). Receiver (đã được đăng kí từ trong activity chính) dùng filter để bắt message mà service gửi rồi hiển thị tại UI. At some point the main activity stops the service and finishes executing. Tại một thời điểm nào đó, activity chính dừng service và kết thúc. 22 22 22 22. Android Services Services 22 Example 2. Layout 23 23 23 22. Android Services Services 23 Example 2. Manifest 24 24 24 22. Android Services Services 24 // Application logic and its BroadcastReceiver in the same class package es.demos; import java.util.Date; import android.app.Activity; import android.content.BroadcastReceiver; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; import android.os.SystemClock; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.*; public class MyServiceDriver3 extends Activity { TextView txtMsg; Button btnStopService; ComponentName service; Intent intentMyService; BroadcastReceiver receiver; Example 2. Main Activity @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); txtMsg = (TextView) findViewById(R.id.txtMsg); intentMyService = new Intent(this, MyService3.class); service = startService(intentMyService); txtMsg.setText("MyService3 started - (see DDMS Log)"); btnStopService = (Button) findViewById(R.id.btnStopService); btnStopService.setOnClickListener(new OnClickListener() { public void onClick(View v) { try { stopService(new Intent(intentMyService) ); txtMsg.setText("After stoping Service: \n" + 	service.getClassName()); } catch (Exception e) { 	e.printStackTrace(); } } }); 25 25 25 22. Android Services Services 25 Example 2. Main Activity stop start 26 26 26 22. Android Services Services 26 	// register & define filter for local listener IntentFilter mainFilter = new IntentFilter("es.action.GOSERVICE3"); 	receiver = new MyMainLocalReceiver(); 	registerReceiver(receiver, mainFilter); }//onCreate //////////////////////////////////////////////////////////////////////// @Override protected void onDestroy() { super.onDestroy(); try { stopService(intentMyService); unregisterReceiver(receiver); } catch (Exception e) { 	Log.e ("MAIN3-DESTROY>>>", e.getMessage() ); } Log.e ("MAIN3-DESTROY>>>" , "Adios" ); } //onDestroy Example 2. Main Activity register unregister 27 27 27 22. Android Services Services 27 ////////////////////////////////////////////////////////////////////// // local (embedded) RECEIVER public class MyMainLocalReceiver extends BroadcastReceiver { @Override public void onReceive(Context localContext, Intent callerIntent) { 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 Example 2. Main Activity Get data 28 28 28 22. Android Services Example 2. The Service 28 // 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(); } 29 29 29 22. Android Services Example 2. The Service 29 @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 hung 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>", "I am dead-3"); isRunning = false; }//onDestroy }//MyService3 Example 2. The Service Thread is now stopped 31 31 	22. Android Services Services 31 	 	 Questions 

File đính kèm:

  • pptxLập trình Android tiếng Việt - Chapter 22 Android Services.pptx
Tài liệu liên quan