Android 利用广播实现短信的自动转发

由于初学(菜)的原因,没有考虑到在6.0版本以上需要权限的问题,等到期末考试后会及时进行更新

初学安卓,代码结构略显混乱,有任何问题欢迎提出!

界面

在这里插入图片描述

布局

布局中主要有四个元素,分别为设置号码,清除号码,显示当前自动转发号码以及输入号码的文本框,设置号码实现了从EditText中提取号码,并更新TextView的功能,清除号码实现了清除EditText以及TextView中号码的功能

<LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:gravity="center">
        <EditText
            android:id="@+id/number"
            android:layout_height="wrap_content"
            android:layout_width="wrap_content"
            android:hint="Phone Number"
            android:textSize="30dp"
            android:inputType="phone"
            android:singleLine="true"
            />
        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="horizontal">
            <TextView
                android:layout_height="wrap_content"
                android:layout_width="wrap_content"
                android:text="当前设置自动转发号码:"
                android:textSize="10dp"
                />
            <TextView
                android:id="@+id/cur_number"
                android:layout_height="wrap_content"
                android:layout_width="wrap_content"
                android:text=""
                android:textSize="10dp"
                />
        </LinearLayout>
        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="horizontal">
            <Button
                android:id="@+id/button1"
                android:layout_height="wrap_content"
                android:layout_width="wrap_content"
                android:text="设置号码"/>
            <Button
                android:id="@+id/button2"
                android:layout_height="wrap_content"
                android:layout_width="wrap_content"
                android:text="清除号码"/>
        </LinearLayout>
    </LinearLayout>

主活动

在活动里通过两次回调,分别实现了获取从广播中接收到的短信内容以及接收后自动转发的功能
在这里注意一点,即当调用sendMultipartTextMessage时,对于信息String和PendingIntent都应该使用ArrayList进行传递,反之sendTextMessage亦然

 public class MainActivity extends AppCompatActivity implements Callback{
    List<String> content;
    TextView textView,textView2;
    EditText editText;
    Button button,button1,button2;
    String num,sum;
    ArrayList<String> text;
    ArrayList<PendingIntent> pi;
    SmsReceiver smsReceiver;
    IntentFilter intentFilter;
    SmsManager smsMgr;
    PendingIntent PiSingle;
    Intent intent;


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

        initActi();

//        button.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                smsReceiver.doWork(MainActivity.this);
//                if(text!=null&&num!=null) {
//                    smsMgr.sendMultipartTextMessage(num, null, text, pi, null);
//                    Log.d(" Num:",num);
//                } else if(num==null){
//                    Toast.makeText(MainActivity.this,"Please Input the Phone Number",Toast.LENGTH_LONG).show();
//                } else if(text==null){
//                    Toast.makeText(MainActivity.this,"No message sent",Toast.LENGTH_LONG).show();
//                }
//            }
//        });

        button1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(editText.getText()==null||editText.getText().toString()==""){
                    Toast.makeText(MainActivity.this,"Please Input the Phone Number",Toast.LENGTH_LONG).show();
                }
                else{
                    num=editText.getText().toString();
                    if(num!=null||num=="") {
                        textView2.setText(num);
                        Log.d(" Num:", num);
                    }
                }
            }
        });

        button2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                num=null;
                text=null;
                editText.setText("");
                textView2.setText("无");
                Log.d(" Num:",""+(num==null));
            }
        });
    }

    public void initActi(){
        text=new ArrayList<>();
        pi=new ArrayList<>();
        textView=(TextView)findViewById(R.id.content);
        textView2=(TextView)findViewById(R.id.cur_number);
        //button=(Button)findViewById(R.id.button);
        button1=(Button)findViewById(R.id.button1);
        button2=(Button)findViewById(R.id.button2);
        editText=(EditText)findViewById(R.id.number);
        smsReceiver=new SmsReceiver(new Callback2() {
            @Override
            public void doSomething() {
                smsReceiver.doWork(MainActivity.this);
                if(text!=null&&num!=null) {
                    smsMgr.sendMultipartTextMessage(num, null, text, pi, null);
                    Log.d(" Num:",num);
                } else if(num==null){
                    Toast.makeText(MainActivity.this,"Please Input the Phone Number",Toast.LENGTH_LONG).show();
                } else if(text==null){
                    Toast.makeText(MainActivity.this,"No message sent",Toast.LENGTH_LONG).show();
                }
            }
        });
        intentFilter=new IntentFilter();
        intentFilter.addAction("android.provider.Telephony.SMS_RECEIVED");
        registerReceiver(smsReceiver,intentFilter);

        smsMgr = SmsManager.getDefault();
        PiSingle = PendingIntent.getBroadcast(this, 0, this.getIntent(), 0);
        //intent=new Intent();
    }

    public void doEvent(ArrayList res1,String res2){
        text=res1;
        //num=res2;
        pi=new ArrayList<>();
        sum="";

        if(text!=null) {
            for(String str:text){
                pi.add(PiSingle);
                sum+=str;
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(smsReceiver);
    }
}

两个回调接口

该接口实现了从broadcaster中获取文本信息,并使用ArrayList分割回传

public interface Callback {
    void doEvent(ArrayList res1, String res2);
}

该接口实现了当broadcaster接收到广播信息时,立即将消息回调至主活动,并进行发送消息的操作

public interface Callback2 {
    void doSomething();
}

广播

广播中的获取消息部分借鉴了其他大佬的思路。在类中定义了一个回调接口,并实现了当执行onReceive时,立刻返回至onCreate执行接下来的操作。

public class SmsReceiver extends BroadcastReceiver {
    String num;
    ArrayList<String> text;
    Callback2 callback;

    public SmsReceiver(Callback2 callback2){
        this.callback=callback2;
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        Bundle bundle = intent.getExtras();
        if (bundle!=null){
            Object pdusData[] = (Object[]) bundle.get("pdus");// pdus :protocol data unit
            SmsMessage[] msg = new SmsMessage[pdusData.length];
            for (int i = 0;i < msg.length;i++){
                byte pdus[] = (byte[]) pdusData[i];
                msg[i] = SmsMessage.createFromPdu(pdus);
            }

            StringBuffer phoneNumber = new StringBuffer();//获取地址
            text=new ArrayList<>();

            for (SmsMessage temp : msg){
                text.add(temp.getMessageBody());
                num=temp.getOriginatingAddress();
            }
        }
        callback.doSomething();
    }
    public void doWork(Callback callback){
        callback.doEvent(text,num);
    }
}
  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值