Hỏi/ Thắc mắc - Cấp quyền đọc tin nhắn trong Android 6.0 | VN-Zoom | Cộng đồng Chia Sẻ Kiến Thức Công Nghệ và Phần Mềm Máy Tính

Adblocker detected! Please consider reading this notice.

We've detected that you are using AdBlock Plus or some other adblocking software which is preventing the page from fully loading.

We need money to operate the site, and almost all of it comes from our online advertising.

If possible, please support us by clicking on the advertisements.

Please add vn-z.vn to your ad blocking whitelist or disable your adblocking software.

×

Hỏi/ Thắc mắc Cấp quyền đọc tin nhắn trong Android 6.0

congdongnet

Búa Đá Đôi
Mình có đoạn code thế này nhưng không hiểu tại sao mình cấp quyền đọc sms rồi thì phải mở ứng dụng 2 lần thì nó mới chạy được.
Lần đầu thì không. Từ các lần sau trở đi thì lại bình thường.

File .java của mình:
Mã:
package com.x.readsms; // Bác nào chạy lại code này thì thay lại package nhé. Bên dưới còn 3, 4 chỗ gì nữa. :D
import android.Manifest;
import android.content.ContentResolver;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

import com.x.readsms.model.ModelSMS;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

public class MainActivity extends AppCompatActivity {

    ListView lvDanhBa;
    ArrayList<ModelSMS> arrayList;
    ArrayAdapter<ModelSMS> arrayAdapter;

    private final static int REQUEST_SMS = 1;


    @Override
protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        addControls();

        requestReadSMS();


    }


    private void requestReadSMS() {


        if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.READ_SMS) == PackageManager.PERMISSION_GRANTED) {

            docTinNhan();

        } else {
            ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.READ_SMS}, REQUEST_SMS);
        }

    }


    public void docTinNhan() {

        try {
            ContentResolver contentResolver = getContentResolver();
            Uri uri = Uri.parse("content://sms/inbox");

            Cursor cursor = contentResolver.query(uri, null, null, null, null, null);
            while (cursor.moveToNext()) {
                int idPhoneNum = cursor.getColumnIndex("address");
                int iddate = cursor.getColumnIndex("date");
                int idbody = cursor.getColumnIndex("body");

                String sdt = cursor.getString(idPhoneNum);
                //String time = String.valueOf(cursor.getInt(iddate)/(24*60*60));
long time = cursor.getLong(iddate);

                SimpleDateFormat sdf = new SimpleDateFormat("MMM-dd-yyyy HH:mm");
                Date resultdate = new Date(time);
                System.out.println(sdf.format(resultdate));


                String noiDung = cursor.getString(idbody);
                ModelSMS tinNhan = new ModelSMS(sdt + "", sdf.format(resultdate) + "", noiDung + "");

                arrayList.add(tinNhan);
            }

            cursor.close();

        } catch (Exception ex) {
            Toast.makeText(this, ex.getMessage(), Toast.LENGTH_LONG).show();
        }
    }


    private void addControls() {
        lvDanhBa = (ListView) findViewById(R.id.lvDanhBa);
        arrayList = new ArrayList<>();
        arrayAdapter = new ArrayAdapter<>(MainActivity.this,
                android.R.layout.simple_list_item_1,
                arrayList);
        lvDanhBa.setAdapter(arrayAdapter);
    }

    @Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case REQUEST_SMS:
                docTinNhan();
                break;
        }
    }
}

file giao diện của em:

Mã:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    tools:context="com.x.readsms.MainActivity">


    <ListView
        android:id="@+id/lvDanhBa"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"></ListView>



</LinearLayout>


File model sms
Mã:
package com.x.readsms.model;

public class ModelSMS {

    String sdt;
    String thoiGian;
    String noiDung;

    public ModelSMS() {
    }

    public ModelSMS(String sdt, String thoiGian, String noiDung) {
        this.sdt = sdt;
        this.thoiGian = thoiGian;
        this.noiDung = noiDung;
    }

    public String getSdt() {
        return sdt;
    }

    public void setSdt(String sdt) {
        this.sdt = sdt;
    }

    public String getThoiGian() {
        return thoiGian;
    }

    public void setThoiGian(String thoiGian) {
        this.thoiGian = thoiGian;
    }

    public String getNoiDung() {
        return noiDung;
    }

    public void setNoiDung(String noiDung) {
        this.noiDung = noiDung;
    }

    @Override
    public String toString() {
        return "Số gửi đến "+this.sdt+"\nThời gian: "+this.thoiGian+"\nNội dung: "+this.noiDung;
    }
}

file manifest của em:

Mã:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.x.readsms">

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

    <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>
    </application>

</manifest>


Bác nào có thể trợ giúp em hiểu tại sao nó lại phải chạy 2 lần mới lấy được tin nhắn? Và có thể sửa code ra sao để khi xin cấp quyền từ người dùng nó lấy luôn SMS. Code chỉ phù hợp chạy trên Android 6 trở lên vì dưới 6 thì không cần xin quyền từ người dùng mà chỉ cần xin quyền hệ thống. :D
:D
 
Sửa lần cuối:


Top