Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Android

วิธี Update UI จาก Intent Service ใน Android


ก่อนเข้าตัวอย่าง เราควรรู้ว่า Intent Service ใน Android คืออะไร Intent Service จะทำ Background Operation แบบ Asynchronous เมื่อ User เรียก startService() จาก Activity มันไม่สร้าง Instance ใหม่สำหรับแต่ละ Request มันจะหยุด Service หลังจากทำ Action ใน Service Class เสร็จ หรือเราต้องหยุดด้วย stopSelf()

ตัวอย่างนี้สาธิตวิธี Update UI จาก Intent Service

Step 1 - สร้าง Project ใหม่ใน Android Studio ไปที่ File → New Project และกรอกรายละเอียดทั้งหมดเพื่อสร้าง Project ใหม่

Step 2 - เพิ่มโค้ดต่อไปนี้ใน res/layout/activity_main.xml

<?xml version = "1.0" encoding = "utf-8"?> <android.support.constraint.ConstraintLayout xmlns:android = "https://schemas.android.com/apk/res/android" xmlns:app = "https://schemas.android.com/apk/res-auto" xmlns:tools = "https://schemas.android.com/tools" android:layout_width = "match_parent" android:layout_height = "match_parent" tools:context = ".MainActivity"> <TextView android:id = "@+id/text" android:layout_width = "wrap_content" android:layout_height = "wrap_content" android:text = "Start Service" android:textSize = "25sp" app:layout_constraintBottom_toBottomOf = "parent" app:layout_constraintLeft_toLeftOf = "parent" app:layout_constraintRight_toRightOf = "parent" app:layout_constraintTop_toTopOf = "parent" /> </android.support.constraint.ConstraintLayout>

ในโค้ดข้างต้นเราใช้ TextView เมื่อ User ได้ข้อมูลจาก Intent Service จะอัปเดต TextView

Step 3 - เพิ่มโค้ดต่อไปนี้ใน src/MainActivity.java

package com.example.andy.myapplication; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.TextView; public class MainActivity extends AppCompatActivity {    TextView text;    BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {       @Override       public void onReceive(Context context, Intent intent) {          String s1 = intent.getStringExtra("DATAPASSED");          text.setText(s1);       }    };    @Override    protected void onStart() {       super.onStart();       IntentFilter intentFilter = new IntentFilter();       intentFilter.addAction("com.example.andy.myapplication");       registerReceiver(broadcastReceiver, intentFilter);    }    @Override    protected void onCreate(Bundle savedInstanceState) {       super.onCreate(savedInstanceState);       setContentView(R.layout.activity_main);       text = findViewById(R.id.text);       text.setOnClickListener(new View.OnClickListener() {          @Override          public void onClick(View v) {             startService(new Intent(MainActivity.this, service.class));          }       });    } @Override protected void onStop() { super.onStop(); unregisterReceiver(broadcastReceiver); } }

ในโค้ดข้างต้นเราสร้าง Service Class และ Dynamic Broadcast Receiver ดังนี้

@Override protected void onStart() { super.onStart(); IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction("com.example.andy.myapplication"); registerReceiver(broadcastReceiver, intentFilter); } ................ BroadcastReceiver broadcastReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String s1 = intent.getStringExtra("DATAPASSED"); text.setText(s1); } }; ................ @Override protected void onStop() { super.onStop(); unregisterReceiver(broadcastReceiver); }

สร้าง Class ชื่อ service.class และเพิ่มโค้ดต่อไปนี้

package com.example.andy.myapplication; import android.app.IntentService; import android.content.Intent; import android.os.IBinder; public class service extends IntentService { public service() { super(service.class.getSimpleName()); } @Override public IBinder onBind(Intent intent) { return null; } @Override protected void onHandleIntent(Intent intent) { Intent intent1 = new Intent(); intent1.setAction("com.example.andy.myapplication"); intent1.putExtra("DATAPASSED", "Tutorialspoint.com"); sendBroadcast(intent1); } }

Step 4 - เพิ่มโค้ดต่อไปนี้ใน manifest.xml

<?xml version = "1.0" encoding = "utf-8"?> <manifest xmlns:android = "https://schemas.android.com/apk/res/android"    package = "com.example.andy.myapplication">    <uses-permission android:name = "android.permission.WAKE_LOCK"/>    <application       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">       <activity android:name = ".MainActivity">          <intent-filter>             <action android:name = "android.intent.action.MAIN" />             <category android:name = "android.intent.category.LAUNCHER" />          </intent-filter>       </activity> <service android:name = ".service"/> </application> </manifest>

ลองรันแอปพลิเคชันของคุณ สมมติว่าคุณเชื่อม Android Device จริงกับคอมพิวเตอร์แล้ว เพื่อรันแอปจาก Android Studio ให้เปิดไฟล์ Activity ของโปรเจกต์และคลิกไอคอน Run จาก Toolbar เลือก Mobile Device ของคุณเป็นตัวเลือก และตรวจสอบ Mobile Device ซึ่งจะแสดงหน้าจอ Default

วิธี Update UI จาก Intent Service ใน Android

ในผลลัพธ์ข้างต้น แสดงหน้าจอ Default ของแอปพลิเคชัน เมื่อ User คลิก "Start Service" จะเริ่ม Service และอัปเดต TextView ดังนี้

วิธี Update UI จาก Intent Service ใน Android