Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 56

CHƯƠNG VI

INTENT – INTENT FILTER


(LƯU HÀNH NỘI BỘ)

XÂY DỰNG VÀ THIẾT KẾ


Võ Minh Thông
1. Intent
- Ba trong số những thành phần ứng dụng cốt lõi trong một
dự án Android là: Activity, Service và Broadcast Receiver,
được kích hoạt thông qua các thông điệp bất đồng bộ,
được gọi là Intent. Thông điệp này dùng để kết nối các
thành phần trong một dự án với nhau, hoặc giữa các dự
án với nhau.
- Intent rất quan trọng nó là linh hồn của Android, là hạt
nhân để Android tồn tại.
1. Intent
- Intent có 5 công dụng chính:

1) Dùng Intent để mở một Activity khác nhưng không kiểm soát kết


quả trả về.

2) Dùng Intent để mở một Activity khác và truyền dữ liệu

3) Mở Activity, có kiểm soát kết quả trả về.

4) Liên kết Application Components: Activity, Service, Broadcast


Receiver trong 1 ứng dụng.

5) Kết nối các thành phần trong các ứng dụng khác nhau và giữa HĐH
với ứng dụng
2. Phân loại Intent
a. Explicit Intent:
Hay còn gọi là Intent công khai. Với loại Intent này tên của
Application Componnet đích phải được chỉ định và nêu rõ tên,
Ví dụ:
Intent myIntent=new Intent(MainActivity.this, ChildActivity.class);

b. Implicit Intent: hay còn gọi là Intent ẩn, Với loại Intent này
tên của Application Componnet đích không được chỉ định,
chúng ta cần thiết lập thông tin về hành động (Action), Dữ liệu
(Data) hay phân loại (category)
Ví dụ:
Intent myIntent=new Intent(Intent.ACTION_CALL, Uri.parse(“tel:55
5-2368”));
2. Phân loại Intent
3. Intent và Activity
 Explicit Intent
- Dùng Intent để mở Activity khác
 Explicit Intent
 Explicit Intent
Button btnOpen=(Button) findViewById(R.id.btnOpenChildActivity);
 btnOpen.setOnClickListener(new View.OnClickListener() {
 public void onClick(View arg0) {
 doOpenChildActivity();
 }
 });
 }
 public void doOpenChildActivity()
 {
 Intent myIntent=new Intent(this, ChildActivity.class);
 startActivity(myIntent);
 }
Intent myIntent=new Intent(this, ChildActivity.class);
Đối số 1 là context hiện tại, nếu bạn muốn chắc ăn ở đâu nó cũng
hiểu thì bạn gán tên class Activity như thế này:
Intent myIntent=new Intent(MainActivity.this, ChildActivity.class);
 Explicit Intent

 Button btnBack= (Button)


 findViewById(R.id.btnBacktoMainActivity);
 btnBack.setOnClickListener(new
 View.OnClickListener() {
 public void onClick(View v) {
 finish();
 }
 });
 
 Explicit Intent

• Lưu ý là phải khai báo ChildActivity trong


AndroidMainifest
 Explicit Intent
- Mở một Activity khác đồng thời truyền dữ liệu
 Explicit Intent
Dùng đối tượng Bundle để đóng gói dữ liệu, gán vào Intent để
truyền

myIntent.putExtra("MyPackage", bundle);
yourintent.getBundleExtra("MyPackage");
 Explicit Intent
Đưa dữ liệu trực tiếp vào Intent để truyền

myintent.putExtra("soa",a);
myintent.putExtra("sob",b);

int a = myintent.getIntExtra("soa",1);
int b = myintent.getIntExtra("sob",1);
 Explicit Intent
 
 Explicit Intent
Intent myIntent=new Intent(MainActivity.this, ResultActivity.class);
 //Khai báo Bundle
 Bundle mybundle=new Bundle();
 int a=Integer.parseInt(txta.getText().toString());
 int b=Integer.parseInt(txtb.getText().toString());
 //đưa dữ liệu riêng lẻ vào Bundle
 mybundle.putInt("soa", a);
 mybundle.putInt("sob", b);
 //Đưa Bundle vào Intent
 myIntent.putExtra("MyPackage", mybundle);
 //Mở Activity ResultActivity
 startActivity(myIntent);
 Explicit Intent
//lấy intent gọi Activity này
 Intent yourintent = getIntent();
 //có intent rồi thì lấy Bundle dựa vào MyPackage
 Bundle yourbundle =
yourintent.getBundleExtra("MyPackage");
 //Có Bundle rồi thì lấy các thông số dựa vào key “soa”, “sob”
 int a= yourbundle.getInt("soa");
 int b= yourbundle.getInt("sob");
 Explicit Intent
- Truyền dữ liệu và tự động lắng nghe kết quả trả về giữa các Activity
Màn hình A Màn hình B

Nhập a:

113
113 và 100
Nhập b: qua màn hình
B
100
Gửi và nhận Nhận 113 và 100, tính
kết quả Tổng của 113 và 100
Nhận lại Tổng
Kết quả ở đây
 Explicit Intent
- Truyền dữ liệu và tự động lắng nghe kết quả trả về giữa các Activity`
Màn hình MainActivity Màn hình ManHinhXuLyActivity
Bước 1: Bước 2:
startActivityForResult(intent,99); intent=getIntent();

Bước 3
//Thay đổi thông tin và gán vào cho intent
//nên sử dụng lại intent (ko cần tạo mới)
intent.putExtra(“ketqua",sum);
Bước 4:
Đánh dấu kết quả trả về:
setResult(33,intent);
Bước 6 Bước 5
Nhận kết quả trong onActivityResult phải đóng màn hình này lại:
//để màn hình MainActivity trở thành
Foreground lifetime
(Chỉ nhận trong vòng đời foregroundlifetime)
//vì nó chỉ tự động nhận được kết quả trả về ở
trong Foreground lifetime
finish();
 Implicit Intent
• Implicit Intent hay còn gọi là Intent ẩn, Với loại Intent này
tên của Application Componnet đích không được chỉ định,
chúng ta cần thiết lập thông tin về hành động (Action), Dữ
liệu (Data) hay phân loại (category)
 Implicit Intent
• Ví dụ 1:
Intent myIntent=new Intent(Intent.ACTION_CALL, Uri.parse(“tel:5
55-2368”));
• Trong ví dụ trên, Intent chứa Action là ACTION_CALL và
Data tương ứng là số điện thoại 555-2368, hệ thống Android
sẽ tìm một ứng dụng có sẵn trong thư viện SDK để thực hiện
yêu cầu.
• Hoặc:
Intent myintent =new Intent(Intent.ACTION_CALL);
myintent.setData(Uri.parse(“tel:555-2368”));
• Ví dụ 2:
Intent myIntent=new Intent(Intent.ACTION_VIEW, Uri.parse
(“www.google.com”)
 Implicit Intent
Một số ACTION thường sử dụng trong Intent:
ACTION_CALL - mở 1 Phone Dialer và ngay lập tức thực hiện cuộc gọi dựa
vào thông tin trong data URI
ACTION_DIAL - mở 1 Phone Dialer (mặc định là PD của Android) và điền
thông tin lấy từ địa chỉ chứa trong data URI
ACTION_SEND - mở 1 Activity cho phép gửi dữ liệu lấy từ data URI, kiểu của
dữ liệu xác định trong thuộc tính type
ACTION_SENDTO - mở 1 Activity cho phép gửi thông điệp (Message) tới địa
chỉ lấy từ data URI
ACTION_VIEW - action thông dụng nhất, khởi chạy activity thích hợp để hiển
thị dữ liệu trong data URI (hình ảnh, web, map...)
ACTION_IMAGE_CAPTURE/ACTION_VIDEO_CAPTURE – Mở ứng dụng cho
phép chụp ảnh/ quay video
ACTION_MAIN - sử dụng để khởi chạy 1 Activity
Demo: Action_Call & Action Sendto
Demo Implicit Intent
Bước 1: Tạo một Project mới có tên My_Contact
Bước 2: Xây dựng 3 cửa sổ giao diện
– activity_main.xml
– call_phone.xml
– send_sms.xml
Bước 3: Xây dựng Class MainActivity.java
Button Call Phone:
btnCall.setOnClickListener(new View.OnClickListener() {
 @Override
public void onClick(View v) {
Intent intent1 =new
Intent(MainActivity.this,CallPhoneActivity.class);
startActivity(intent1); }});
Demo Implicit Intent
Button Send_SMS:
btnSend.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent2 =new
Intent(MainActivity.this,SendSMSActivity.class);
startActivity(intent2); }});
Demo Implicit Intent
Bước 4: Tạo thêm Activity CallPhoneActivity
Thiết lập sự kiện cho Button Call Phone:
btnCallPhone.setOnClickListener(new
View.OnClickListener() {
@Override
public void onClick(View v) {
Intent callintent =new Intent(Intent.ACTION_CALL);
callintent.setData(Uri.parse("tel:"+txtNumber.getText().toStr
ing()));
startActivity(callintent); } });
Demo Implicit Intent
Bước 5: Tạo Activity SendSMSActivity:
Thiết lập sự kiện cho Button Send SMS
btnsendsms.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent smsintent = new Intent(Intent.ACTION_SENDTO,
Uri.parse("smsto:"+edtsms.getText().toString()));
startActivity(smsintent);
}
});
btnback2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
finish();
}
});
Demo Implicit Intent
• Khai báo các Activity và các quyền trong tập tin
AndroidManifest.xml
Demo Implicit Intent
• Action Image_Capture
Demo Implicit Intent
Action Image_Capture
Demo Implicit Intent
Action Image_Capture
Demo Action_View
4. Intent Filter
• Với Explicit Intent: chúng ta chỉ cần cung cấp đối
tượng nguồn và đối tượng đích cụ thể
• Còn với Implicit Intent: Android phải tìm Application
Component phù hợp để thực hiện Action chuyển phát
thông điệp (Broadcast).
• Để làm được điều này, Android sử dụng Intent Filter
như những bộ lọc để cho biết một Application
Component có thể thực hiện được những Action nào
4. Intent Filter
 Review Implicit Intent

• Ví dụ 1:
Intent myIntent=new Intent(Intent.ACTION_CALL, Uri.parse(“tel:555-
2368”));
• Trong ví dụ trên, Intent chứa Action là ACTION_CALL và Data
tương ứng là số điện thoại 555-2368, hệ thống Android sẽ tìm
một ứng dụng có sẵn trong thư viện SDK để thực hiện yêu cầu.
• Hoặc:
Intent myintent =new Intent(Intent.ACTION_CALL);
myintent.setData(Uri.parse(“tel:555-2368”));
• Ví dụ 2:
Intent myIntent=new Intent(Intent.ACTION_VIEW, Uri.parse
(“www.google.com”)
4. Intent Filter
• Ví dụ: khi bạn mở một file Image hệ thống android sẽ đưa
ra một thông báo với tên các ứng dụng có thể mở file này
như là Gallery, Photos, QuikPic,….Vậy các ứng dụng đó
đã được cài đặt Intent Filter để báo cho Android rằng “tôi
có thể thực hiện công việc này”
4. Intent Filter
• Mấu chốt của vấn đề làm sao cài đặt nó? Ta chỉ cần khai
báo trong AndroidMaintifest.xml là xong!
• Ví dụ : SMS
Demo Intent Filter
Demo Intent Filter

Bước 1: Tạo Activity có gia diện như hình


Viết sự kiê ̣n cho Button
btnopen.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_VIEW,
Uri.parse("https://"+edtlink.getText().toString()));
startActivity(intent); } });
Demo Intent Filter

Bước 2: Activity chứa WebView, code trong Class:


protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = getIntent();
Uri data = intent.getData();
WebView webView = (WebView) findViewById(R.id.webView1);
webView.loadUrl(data.toString());
}
Demo Intent Filter
• Bước 3: Khai báo trong AndroidManifest
5. Intent và Service
• Service là một dạng Application Component, dùng
để thực hiện những công việc chạy nền, mang tính
chất lâu dài và không cần cung cấp giao diện cho
người dùng tương tác, có thể làm việc ngay cả khi
ứng dụng bị hủy.
• Cần phải có 1 Component khác để khởi động và
ngừng service
• Sử dụng các thông điệp bất đồng bộ Intent để
start và stop một service
Demo Service
• Xây dựng ứng dụng nghe nhạc đơn
giản với giao diện như trên. Mô tả
chức năng:
• Khi click vào Button play, một bài
nhạc được cài đặt sẵn được bật lên,
nếu ta bấm vào nút Back trên thiết
bị thì thoát Activity, nhưng bài nhạc
vẫn tiếp tục phát. Một Notification
sẽ xuất hiện
• Khi click vào Notification thì quay trở
lại ứng dụng, nếu ta click vào Button
Stop thì dừng bài hát đồng thời
thoát ứng dụng.
Demo Service
• Bước 1: Tạo mới Project
Intent_service
• Bước 2: Tạo thư mục drawable
nằm trong thư mục res, copy các
file ảnh nhac.png, play.png và
stop.png vào thư mục này. Tạo
thư mục raw trong thư mục res,
copy file tinhme.mp3 vào.
• Bước 3: Xây dựng MainActivity
có giao diện như sau
Bước 4: Tạo lớp MediaPlayerService kế thừa từ lớp Service của Android
public class MediaPlayerService extends Service{
MediaPlayer myMediaPlayer;
@Override
public void onCreate() { Demo Service
myMediaPlayer = MediaPlayer.create(this,R.raw.tinhme);
myMediaPlayer.setLooping(true); }
@Override
public void onDestroy() {
myMediaPlayer.stop();
}
@Override
public void onStart(Intent intent, int startId) {
myMediaPlayer.start();
}
Bước 5: Mở lại tệp tin MainActivity.java, cập nhật sự kiện onCreate() như sau
ImageButton startButton = findViewById(R.id.imagstart);
ImageButton stopButton = findViewById(R.id.imgstop);
startButton.setOnClickListener(new View.OnClickListener() {
  @Override
public void onClick(View v) {
Intent intent1 = new Intent(MainActivity.this, MediaPlayerService.class)
startService(intent1);
stopButton.setOnClickListener(new View.OnClickListener() { 
@Override
public void onClick(View v) {
Intent intent2 = new Intent(MainActivity.this, MediaPlayerService.class)
stopService(intent2);
finish(); } });
Intent intent = new Intent(getApplicationContext(),
MainActivity.class);
PendingIntent pIntent =
PendingIntent.getActivity(getApplicationContext(),
(int)System.currentTimeMillis(), intent, 0);
Notification myNotification = new
Notification.Builder(getApplicationContext())
.setContentTitle("MUSIC")
.setContentText("Tình Mẹ - Mỹ Tâm")
.setSmallIcon(R.drawable.nghenhac)
.setContentIntent(pIntent).build();
NotificationManager notificationManager =
(NotificationManager)
getSystemService(NOTIFICATION_SERVICE);
notificationManager.notify(0, myNotification);
}
Demo Service

• Bước 7. Khai báo Service trong


AndroidMainifest
<service
android:name="com.example.intent_servic
e.MediaPlayerService" >
</service>
6. Intent và BroadcastReceiver
• BroadcastReceiver là bộ tiếp nhận và xử lý các Intent
dựa trên các chỉ định của chúng ta hoặc hệ thống.
• Thành phần này sẽ có phép mở các ứng dụng để xử lý
các Intent tương ứng được gởi lên từ hệ thống

• Trong các ứng dụng, đôi


khi bạn cần phải nhận
được tín hiệu nếu như
một sự kiện nào đó trong
thiết bị được kích hoạt để
xử lý cho các ứng dụng tốt
hơn.
6. Intent và BroadcastReceiver
• Các sự kiện ví dự như: ĐT sắp hết Pin, nguồn được cắm sạc,
rút sạc, máy vừa được khởi động, một ứng dụng nào đó vừa
cài đặt lên máy, Internet thay đổi, tin nhắn đến, cuộc gọi
đến, cảm biến thay đổi…khi đó, sử dụng BroadcastReceiver
sẽ giúp chúng ta bắt được các sự kiện này khi chúng bị kích
hoạt
Tạo BroadcastReceiver
• Để tạo 1 BroadcastReceiver, ta sẽ tạo một lớp
kế thừa từ lớp BroadcastReceiver
public class MySmsReceive extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent)
{
//To do thing
}

• Context: Là context của ứng dụng hoặc hệ thống


mà Broadcast này được kích hoạt
• Intent: Toàn bộ dữ liệu nhận được đều nằm
trong đối số này. Tùy thuộc vào bộ lọc khi đăng
ký mà cách lấy đối số này sẽ khác nhau
Đăng ký BroadcastReceiver
• Đăng ký trong onResume của Activity: Khi tắt Activity thì Receiver không còn hoạt động nữa

• Đăng ký trong AndroidManifest: Trở thành 1 dịch vụ chạy ngầm, cho dù tắt phần mềm nó vẫn luôn lắng nghe bộ
lọc
IntentFilter filter = new IntentFilter(“Tên bộ lọc khai báo ở đây"
MySmsReceive receiver = new MySmsReceive();
registerReceiver(receiver,filter);

<receiver
android:name=".MySmsReceive">
<intent-filter>
<action android:name=“Tên bộ lọc khai báo tại đây"/>
</intent-filter>
</receiver>
Hủy BroadcastReceiver
• Muốn hủy BroadcastReceiver ta dùng lệnh
unregisterReceiver trong onPause
@Override
protected void onPause() {
super.onPause();
unregisterReceiver(MySmsReceive);
}

• Chú ý: lệnh hủy chỉ áp dụng cho Broadcast


Receiver được đăng ký trong Activity. Nếu đăng
ký trong AndroidManifest thì khi tháo ứng dụng
khỏi thiết bị thì Receiver mới bị hủy
Tên một số bộ lọc Receiver
• android.provider.Telephony.SMS_RECEIVED
• android.intent.action.PHONE_STATE
• android.net.conn.CONNECTIVITY_CHANGE
• android.intent.action.ACTION_POWER_CONNECTED
• android.intent.action.ACTION_POWER_DISCONNECTED
• android.intent.action.BATTERY_CHANGED
• android.intent.action.BATTERY_LOW
• android.intent.action.DEVICE_STORAGE_LOW
• android.intent.action.CAMERA_BUTTON
• android.intent.action.DATE_CHANGED
• android.intent.action.SCREEN_ON/OFF
Demo BroadcastReceiver
• Viết chương trình nghe lén tin nhắn từ 1 hoặc nhiều số
điện thoại nào đó và tự động chuyển tiếp đến số cài đặt
sẵn.
Tạo mới 1 lớp kế thừa từ lớp
BroadcastReceiver
Khai báo AndroidMainifest

You might also like