android监听短信发送和接收

文章目录

目录

一、MainActivity和activity_main

二、创建service和util类

三、配置manifest


一、MainActivity和activity_main




import androidx.appcompat.app.AppCompatActivity;

import android.content.ContentResolver;
import android.content.Intent;
import android.content.ServiceConnection;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;


public class MainActivity extends AppCompatActivity {

    private Button start;
    private Button stop;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        start = findViewById(R.id.start);
        stop = findViewById(R.id.stop);
        //收取
        Intent intent = new Intent(MainActivity.this, MessageService.class);

        start.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startService(intent);
                Toast.makeText(MainActivity.this, "开始监听", Toast.LENGTH_LONG).show();
            }
        });

        stop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                stopService(intent);
                Toast.makeText(MainActivity.this, "关闭监听", Toast.LENGTH_LONG).show();
            }
        });

        //TODO 下面这一行功能没用,可以删掉
        getApplicationContext().getContentResolver().registerContentObserver(Uri.parse("content://sms/"),
                true, new SmsObserver(this, new Handler()));

        //为content://sms 的数据改变注册监听器
//        ContentResolver contentResolver = getContentResolver();
//        Uri uri= Uri.parse("content://sms/");
//        contentResolver.registerContentObserver(uri,true,new SMSActivity.SmsObsever(new Handler()));
    }
}
<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_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="Hello World!" />

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <Button
            android:id="@+id/start"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="开启监听" />

        <Button
            android:id="@+id/stop"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:text="关闭监听" />

    </RelativeLayout>
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

    </RelativeLayout>

</RelativeLayout>

二、创建service和util类

MessageService类




import android.app.Service;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.IBinder;


import java.security.Provider;

public class MessageService extends Service {
    private MessageReciever mReceiver;

    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }
    @Override
    public void onCreate() {
        mReceiver = new MessageReciever();
        IntentFilter filter = new IntentFilter("android.provider.Telephony.SMS_RECEIVED");
        registerReceiver(mReceiver, filter);
    }
    @Override
    public void onDestroy() {
        if(null != mReceiver)
        {
            unregisterReceiver(mReceiver);
            mReceiver = null;
        }
    }
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return super.onStartCommand(intent, flags, startId);
    }
    @Override
    public boolean onUnbind(Intent intent) {
        return super.onUnbind(intent);
    }
}


 MessageReciever类




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

import static android.telephony.TelephonyManager.PHONE_TYPE_CDMA;

public class MessageReciever extends BroadcastReceiver {

    private static final String SMS_RECEIVER_ACTION = "android.provider.Telephony.SMS_RECEIVED";
    @Override
    public void onReceive(Context context, Intent intent) {
        StringBuilder sBuilder = new StringBuilder();
        String format = intent.getStringExtra("format");
        if(SMS_RECEIVER_ACTION.equals(intent.getAction()))
        {
            Bundle bundle = intent.getExtras();
            if(null != bundle)
            {
                Object[] pdus = (Object[])bundle.get("pdus");
                assert pdus != null;
                SmsMessage[] messages = new SmsMessage[pdus.length];
                for(int i = 0; i < messages.length; ++i)
                {
                    messages[i] = SmsMessage.createFromPdu((byte[])pdus[i],format);
                }
                for(SmsMessage msg : messages)
                {
                    sBuilder.append("来自:").append(msg.getDisplayOriginatingAddress()).append("\n").append("短信内容:");
                    sBuilder.append(msg.getDisplayMessageBody()).append("\n");
                }
            }
        }
        Toast.makeText(context, "您收到了一条短信!!\n" + sBuilder.toString(), Toast.LENGTH_LONG).show();
    }

}

三、配置manifest和开启权限

这一段内容必须加

    <!-- 接收消息 -->
    <uses-permission android:name="android.permission.RECEIVE_SMS"/>
    <!--  发送消息-->
    <uses-permission android:name="android.permission.SEND_SMS"/>
    <!--  阅读消息-->
    <uses-permission android:name="android.permission.READ_SMS"/>
    <!--  写入消息-->
    <uses-permission android:name="android.permission.WRITE_SMS" />

 这一段内容如果要使用广播就加service

        <!-- Service -->
        <service android:name=".service.MessageService"
            android:label="@string/app_name"
            android:exported="true">
            <intent-filter>
                <action android:name="org.anymobile.test.service.IMICHAT" />
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </service>

        <!-- Receiver -->
<!--        <receiver android:name=".util.MessageReciever"-->
<!--            android:exported="true">-->
<!--            <intent-filter>-->
<!--                <action android:name="android.provider.Telephony.SMS_RECEIVED" />-->
<!--            </intent-filter>-->
<!--        </receiver>-->

app运行后,要长按应用进入App Info修改权限

 

运行监听短信图片

 

猜你喜欢

转载自blog.csdn.net/i__saber/article/details/130541644