广播短信接收器

Posted

技术标签:

【中文标题】广播短信接收器【英文标题】:Broadcast sms Reciever 【发布时间】:2022-01-08 17:39:09 【问题描述】:

我是 android 开发的新手,我正在尝试创建一个 sms Reciever 应用程序,但它无法正常工作。我希望广播接收器捕获传入的消息并将它们传递给 Recycler 视图,以便它们可以显示。目前没有显示任何内容。

这是我的代码(清单文件)

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

    <uses-permission android:name="android.permission.RECEIVE_SMS" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.READ_SMS" />
    <uses-permission android:name="android.permission.READ_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/Theme.Test1">
        <receiver
            android:name=".SmsReceiver"
            android:enabled="true"
            android:exported="true"></receiver>

        <activity
            android:name=".MainActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>  

这里是 MainActivity 文件

 package com.example.test1;
    
    import android.content.ContentResolver;
    import android.content.pm.PackageManager;
    import android.database.Cursor;
    import android.net.Uri;
    import android.os.Bundle;
    
    import androidx.appcompat.app.AppCompatActivity;
    import androidx.core.app.ActivityCompat;
    import androidx.core.content.ContextCompat;
    import androidx.recyclerview.widget.LinearLayoutManager;
    import androidx.recyclerview.widget.RecyclerView;
    
    import java.util.ArrayList;
    
    public class MainActivity extends AppCompatActivity 
        //recycler view
        private RecyclerView recyclerView;
         private ArrayList<SmsModel>smsModel=new ArrayList<>();
        private static MainActivity inst;
        public static MainActivity instance() 
            return inst;
        
    @Override
    public void onStart() 
        super.onStart();
        inst = this;
    
    
    @Override
    protected void onCreate(Bundle savedInstanceState) 
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        recyclerView=findViewById(R.id.smsRecycler);
        ArrayAdapter adapter= new ArrayAdapter();
        adapter.setSmsModel(smsModel);
        recyclerView.setAdapter(adapter);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));

        if(ContextCompat.checkSelfPermission(getBaseContext(), "android.permission.READ_SMS") == PackageManager.PERMISSION_GRANTED) 
            refreshSmsInbox();
        else 
            // Todo : Then Set Permission
            final int REQUEST_CODE_ASK_PERMISSIONS = 123;
            ActivityCompat.requestPermissions(MainActivity.this, new String[]"android.permission.READ_SMS", REQUEST_CODE_ASK_PERMISSIONS);
        

        
    public void refreshSmsInbox() 
        ContentResolver contentResolver = getContentResolver();
        Cursor smsInboxCursor = contentResolver.query(Uri.parse("content://sms/inbox"), null, null, null, null);
        int indexBody = smsInboxCursor.getColumnIndex("body");
        int indexAddress = smsInboxCursor.getColumnIndex("address");
        if (indexBody < 0 || !smsInboxCursor.moveToFirst()) return;
        smsModel.clear();
        do 
            String str = "SMS From: " + smsInboxCursor.getString(indexAddress) +
                    "\n" + smsInboxCursor.getString(indexBody) + "\n";
            smsModel.add((SmsModel) smsInboxCursor);
         while (smsInboxCursor.moveToNext());
    

    public void updateList(final String smsMessage) 
       


    



这是我的 Recyclerview 适配器类

 package com.example.test1;
    
    import android.content.Context;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.TextView;
    
    import androidx.annotation.NonNull;
    import androidx.recyclerview.widget.RecyclerView;
    
    import java.util.ArrayList;
    import java.util.List;
    
    public class ArrayAdapter extends RecyclerView.Adapter<ArrayAdapter.viewHolder> 
    
    
        private ArrayList<SmsModel>smsModel=new ArrayList<>();
    
        public ArrayAdapter() 
    
        
    
        @NonNull
        @Override
        public viewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) 
            View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.smsview,parent,false);
            viewHolder viewHolder=new viewHolder(view);
            return viewHolder;
        
    
        @Override
        public void onBindViewHolder(@NonNull viewHolder holder, int position) 
            holder.ContactsNO.setText(smsModel.get(position).getContactNumber());
            holder.SmsText.setText(smsModel.get(position).getContactSms());
            holder.Time.setText(smsModel.get(position).getTime());
            holder.Number.setText(smsModel.get(position).getNumber());
    
    
        
    
        @Override
        public int getItemCount() 
            return smsModel.size();
        
    
        public void setSmsModel(ArrayList<SmsModel> smsModel) 
            this.smsModel = smsModel;
            notifyDataSetChanged();
        
    
        public class viewHolder extends RecyclerView.ViewHolder 
            private TextView ContactsNO;
            private TextView SmsText;
            private TextView Time;
            private TextView Number;
            public viewHolder(@NonNull View itemView) 
                super(itemView);
                ContactsNO=itemView.findViewById(R.id.contactsNo);
                SmsText=itemView.findViewById(R.id.smsText);
                Time=itemView.findViewById(R.id.time);
                Number=itemView.findViewById(R.id.Number);
            
        
    

这是我的短信接收类

package com.example.test1;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.widget.Toast;

import androidx.annotation.RequiresApi;

public class SmsReceiver extends BroadcastReceiver 
    public static final String SMS_BUNDLE = "pdus";
    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    public void onReceive(Context context, Intent intent) 
        Bundle intentExtras = intent.getExtras();
        if (intentExtras != null) 
            Object[] sms = (Object[]) intentExtras.get(SMS_BUNDLE);
            String smsMessageStr = "";
            for (int i = 0; i < sms.length; ++i) 
                SmsMessage smsMessage = SmsMessage.createFromPdu((byte[]) sms[i]);

                String smsBody = smsMessage.getMessageBody().toString();
                String address = smsMessage.getOriginatingAddress();

                smsMessageStr += "SMS From: " + address + "\n";
                smsMessageStr += smsBody + "\n";
            
            Toast.makeText(context, smsMessageStr, Toast.LENGTH_SHORT).show();

            //this will update the UI with message
            MainActivity inst = MainActivity.instance();
            inst.updateList(smsMessageStr);
            
        


    

这是我的短信模型类

package com.example.test1;

public class SmsModel 
    private  String Id;
    private String ContactNumber;
    private String ContactSms;
    private String Time;
    private String Number;

    public SmsModel(String id, String contactNumber, String contactSms, String time, String number) 
        Id = id;
        ContactNumber = contactNumber;
        ContactSms = contactSms;
        Time = time;
        Number = "Number";
    

    public String getId() 
        return Id;
    

    public void setId(String id) 
        Id = id;
    

    public String getContactNumber() 
        return ContactNumber;
    

    public void setContactNumber(String contactNumber) 
        ContactNumber = contactNumber;
    

    public String getContactSms() 
        return ContactSms;
    

    public void setContactSms(String contactSms) 
        ContactSms = contactSms;
    

    public String getTime() 
        return Time;
    

    public void setTime(String time) 
        Time = time;
    

    public void setNumber(String number) 
        Number = number;
    

    public String getNumber() 
        return Number;
    

    @Override
    public String toString() 
        return "SmsModel" +
                "Id='" + Id + '\'' +
                ", ContactNumber='" + ContactNumber + '\'' +
                ", ContactSms='" + ContactSms + '\'' +
                ", Time='" + Time + '\'' +
                ", Number='" + Number + '\'' +
                '';
    

这是我的主要活动代码

 <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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_
    android:layout_
    tools:context=".MainActivity">


<TextView
    android:layout_
    android:layout_
    android:id="@+id/sms"
    android:text="SMS APP"
    android:layout_centerHorizontal="true"
    android:textFontWeight="600"
    android:textStyle="bold"/>

    <androidx.recyclerview.widget.RecyclerView
        android:layout_
        android:layout_
        android:layout_below="@+id/sms"
        android:id="@+id/smsRecycler"
/>

</RelativeLayout>

和我的布局资源文件(smsview.xml)

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_
    android:layout_
    android:padding="10dp">

    <TextView
        android:id="@+id/Number"
        android:layout_
        android:layout_
        android:text="Number:" />

    <TextView
        android:id="@+id/contactsNo"
        android:layout_
        android:layout_
        android:layout_marginLeft="10dp"
        android:layout_toRightOf="@+id/Number"
        android:text="0700000000" />

    <TextView
        android:id="@+id/smsText"
        android:layout_
        android:layout_
        android:layout_below="@+id/Number"
        android:layout_marginTop="10dp"
        android:hint="sms text will apear here" />

    <TextView
        android:layout_
        android:layout_
        android:layout_marginLeft="200dp"
        android:layout_toRightOf="@+id/contactsNo"
        android:text="21:59"
        android:id="@+id/time"
        />

</RelativeLayout>

我已经尝试了我能做的任何事情,但无法让它发挥作用。

【问题讨论】:

在消息到达时接收它们,然后再阅读它们是两件不同的事情。您需要一次专注于一个问题。作为一般建议,必须在运行时请求使用的每个单独的 SMS 权限;目前,您只请求READ_SMS。此外,如果您的应用程序崩溃(如下所述),则需要在问题中说明这一点,并说明它发生的时间和方式,以及the complete stack trace from the crash。 【参考方案1】:

您应该在AndroidManifest.xml 中声明BroadcastReceiver

<receiver
  android:name="com.example.test1.SmsReceiver"
  android:priority="1000"
  android:permission="android.permission.BROADCAST_SMS">
  <intent-filter android:priority="1000">
    <action android:name="android.provider.Telephony.SMS_RECEIVED"/>
  </intent-filter>
</receiver>

【讨论】:

我已经声明了,但应用程序仍然无法运行......再次,应用程序在第一次点击时完美启动,当我再次尝试启动它时崩溃......我必须清除数据它工作......你有什么想法吗? 应用程序崩溃的事实可能是您如何使 Service 与 Activity 通信的结果。不推荐使用像private static MainActivity inst 这样的静态变量。开始阅读以下主题以了解更多信息:***.com/questions/2463175/…

以上是关于广播短信接收器的主要内容,如果未能解决你的问题,请参考以下文章

安卓学习之接收发送短信

从Intent服务发送短信 - 无法接收广播以检查是否发送了短信

如何将联系人信息放入短信广播接收器类?

如何在 Android Studio 中使用广播接收器接收短信?

android 6.0为啥接收不到短信广播

Android studio之广播监听接收短信