0% found this document useful (0 votes)
4 views

Receives Ms

The document contains an XML layout file for an Android application with a button to read the latest SMS and a TextView to display the message. The Java code in MainActivity handles the button click, requests SMS read permission, and retrieves the latest SMS from the inbox to display it. If no SMS is found, it shows a corresponding message in the TextView.

Uploaded by

komalsawant765
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Receives Ms

The document contains an XML layout file for an Android application with a button to read the latest SMS and a TextView to display the message. The Java code in MainActivity handles the button click, requests SMS read permission, and retrieves the latest SMS from the inbox to display it. If no SMS is found, it shows a corresponding message in the TextView.

Uploaded by

komalsawant765
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

Activity_main.

xml

<LinearLayout xmlns:android=http://schemas.android.com/apk/res/android

Android:layout_width=”match_parent” android:layout_height=”match_parent”

Android:orientation=”vertical” android:padding=”16dp”>

<Button

Android:id=”@+id/readBtn”

Android:text=”Read Latest SMS”

Android:layout_width=”wrap_content”

Android:layout_height=”wrap_content”/>

<TextView

Android:id=”@+id/smsText”

Android:layout_width=”match_parent”

Android:layout_height=”wrap_content”

Android:paddingTop=”20dp”

Android:text=”SMS will appear here”/>

</LinearLayout>

MainActivity.java

Public class MainActivity extends AppCompatActivity {

Button readBtn;

TextView smsText;
@Override

Protected void onCreate(Bundle savedInstanceState) {

Super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

readBtn = findViewById(R.id.readBtn);

smsText = findViewById(R.id.smsText);

// Request SMS read permission

ActivityCompat.requestPermissions(this,

New String[]{Manifest.permission.READ_SMS}, 1);

readBtn.setOnClickListener(v -> {

Uri inboxUri = Uri.parse(“content://sms/inbox”);

Cursor cursor = getContentResolver().query(inboxUri, null, null, null, “date DESC”);

If (cursor != null && cursor.moveToFirst()) {

String address = cursor.getString(cursor.getColumnIndex(“address”));

String body = cursor.getString(cursor.getColumnIndex(“body”));

smsText.setText(“From: “ + address + “\nMessage: “ + body);

cursor.close();

} else {

smsText.setText(“No SMS found.”);

});

}
}

You might also like