Android DeveloperDeveloperFeatured

เขียนแอพ Android การใช้งาน SMS เบื้องต้น

บทเรียนง่ายๆ สำหรับการใช้งาน SMS ร่วมกับแอพพลิเคชัน Android ให้ส่งข้อความไปยังหมายเลขที่ต้องการได้ หรือเอาไปประยุกต์ใช้กับสถานการณ์อื่นๆ ในการส่งข้อความ SMSแนวทางการใช้งานนั้นก็เพียงแค่เราต้องปรับใช้ SMSManager ให้สามารถส่งข้อความได้

ให้สร้าง Project ขึ้นมาครับ เลือก Blank Activity ซะ

Screen Shot 2558-04-26 at 1.14.13 PM

เปิดไฟล์ AndroidManifest.xml ขึ้นมาขอ Permission ในการเรียกใช้ SMS ให้เรียบร้อย

<uses-permission android:name="android.permission.SEND_SMS" />

ตัวอย่างนี้จะมีการเรียกใช้งาน 2 แบบ คือแบบ Intent ส่ง Parameter เบอร์โทร และข้อความไปเปิด และส่งผ่าน SMS ปรกติของระบบปฏิบัติการ Android และอีกแบบคือส่ง SMS ผ่านหน้าจอแอพพลิเคชันของเราโดยตรง

ออกแบบหน้าจอ Layout ใน activity_main.xml ครับ

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/linearLayout1"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    android:padding="5dp" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Phone Number : "
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <EditText
        android:id="@+id/mobileNumber"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:hint="Enter phone number"
        android:phoneNumber="true" >
    </EditText>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Message Body: "
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <EditText
        android:id="@+id/smsBody"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="top"
        android:hint="Enter message body"
        android:inputType="textMultiLine"
        android:lines="5" />

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:weightSum="10" >

        <Button
            android:id="@+id/sendViaIntent"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_weight="5"
            android:text="SMS Intent" />

        <Button
            android:id="@+id/send"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_weight="5"
            android:text="Send" />
    </LinearLayout>

</LinearLayout>

Screen Shot 2558-04-26 at 1.15.07 PM

เปิดไฟล์ MainActivity.java ขึ้นมาเขียนคำสั่งต่อไปนี้ ให้ Import ส่วน Header เปิดการใช้ Intent, Toast และ SMS ครับ

import android.view.View;
import android.widget.Toast;
import android.telephony.gsm.SmsManager;


import android.content.Intent;

ประกาศ Global Variable ใต้ Class ของ MainActivity()

private Button shareIntent;
private Button send;
private EditText phoneNo;
private EditText messageBody;

เรียกใช้คำสั่งในเมธอด OnCreate() ในการ Final ตัว Widget ให้เรียบร้อย

phoneNo = (EditText) findViewById(R.id.mobileNumber);
messageBody = (EditText) findViewById(R.id.smsBody);
send = (Button) findViewById(R.id.send);

ให้ปุ่ม send เป็นปุ่มดำเนินการส่ง SMS แล้วบอกผลลัพธ์ผ่าน Toast

send.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String number = phoneNo.getText().toString();
                String sms = messageBody.getText().toString();

                try {
                    SmsManager smsManager = SmsManager.getDefault();
                    smsManager.sendTextMessage(number, null, sms, null, null);
                    Toast.makeText(getApplicationContext(), "SMS Sent!",
                            Toast.LENGTH_LONG).show();
                } catch (Exception e) {
                    Toast.makeText(getApplicationContext(),
                            "SMS faild, please try again later!",
                            Toast.LENGTH_LONG).show();
                    e.printStackTrace();
                }
            }
        });

อีกปุ่มคือ shareIntent ให้เรียก Intent Activity ออกมา พร้อม PutExtra ผ่าน Intent ไป

shareIntent = (Button) findViewById(R.id.sendViaIntent);
        
        shareIntent.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    Intent sendIntent = new Intent(Intent.ACTION_VIEW);
                    sendIntent.putExtra("sms_body", messageBody.getText().toString());
                    sendIntent.setType("vnd.android-dir/mms-sms");
                    startActivity(sendIntent);
                } catch (Exception e) {
                    Toast.makeText(getApplicationContext(),
                            "SMS faild, please try again later!",
                            Toast.LENGTH_LONG).show();
                    e.printStackTrace();
                }
            }
        });

ภาพรวมของ MainActivity.java จะเป็นดังนี้

package th.ac.dpu.sms;


import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.EditText;

import android.view.View;
import android.widget.Toast;
import android.telephony.gsm.SmsManager;


import android.content.Intent;


public class MainActivity extends Activity {

    private Button shareIntent;
    private Button send;
    private EditText phoneNo;
    private EditText messageBody;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        phoneNo = (EditText) findViewById(R.id.mobileNumber);
        messageBody = (EditText) findViewById(R.id.smsBody);

        send = (Button) findViewById(R.id.send);
        send.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String number = phoneNo.getText().toString();
                String sms = messageBody.getText().toString();

                try {
                    SmsManager smsManager = SmsManager.getDefault();
                    smsManager.sendTextMessage(number, null, sms, null, null);
                    Toast.makeText(getApplicationContext(), "SMS Sent!",
                            Toast.LENGTH_LONG).show();
                } catch (Exception e) {
                    Toast.makeText(getApplicationContext(),
                            "SMS faild, please try again later!",
                            Toast.LENGTH_LONG).show();
                    e.printStackTrace();
                }
            }
        });


        shareIntent = (Button) findViewById(R.id.sendViaIntent);

        shareIntent.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    Intent sendIntent = new Intent(Intent.ACTION_VIEW);
                    sendIntent.putExtra("sms_body", messageBody.getText().toString());
                    sendIntent.setType("vnd.android-dir/mms-sms");
                    startActivity(sendIntent);
                } catch (Exception e) {
                    Toast.makeText(getApplicationContext(),
                            "SMS faild, please try again later!",
                            Toast.LENGTH_LONG).show();
                    e.printStackTrace();
                }
            }
        });

    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

ทดสอบ แอพพลิเคชันของเรา

Screen Shot 2558-04-26 at 1.22.50 PM

Asst. Prof. Banyapon Poolsawas

อาจารย์ประจำสาขาวิชาการออกแบบเชิงโต้ตอบ และการพัฒนาเกม วิทยาลัยครีเอทีฟดีไซน์ & เอ็นเตอร์เทนเมนต์เทคโนโลยี มหาวิทยาลัยธุรกิจบัณฑิตย์ ผู้ก่อตั้ง บริษัท Daydev Co., Ltd, (เดย์เดฟ จำกัด)

Related Articles

Back to top button
Game & Mobile Development AR VR XR
Privacy Overview

This website uses cookies so that we can provide you with the best user experience possible. Cookie information is stored in your browser and performs functions such as recognising you when you return to our website and helping our team to understand which sections of the website you find most interesting and useful.

Adblock Detected

เราตรวจพบว่าคุณใช้ Adblock บนบราวเซอร์ของคุณ,กรุณาปิดระบบ Adblock ก่อนเข้าอ่าน Content ของเรานะครับ, ถือว่าช่วยเหลือกัน