Android使用BroadCastReceiver阻止传入短信

时间:2015-01-07 12:24:28

标签: java android sms

只要我的应用程序正在运行,我想阻止传入的SMS消息。我可以实现这一点,但问题是我关闭应用程序甚至重新启动甚至卸载后,用户将无法再接收短信。那么如何让应用程序仅在运行时以及关闭或卸载等时阻止传入的SMS才能阻止SMS。这是我的代码:

BroadCastReceiver.Java

package com.example.sms;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.widget.Toast;

public class BroadCastReceiver extends BroadcastReceiver 
{

    public void onReceive(Context context, Intent intent)
    {
     abortBroadcast();
     }
    }

MainActivity.java

package com.example.sms;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;

public class MainActivity extends Activity {

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

Manifiest:

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

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="19" />
<uses-permission android:name="android.permission.RECEIVE_SMS"/>

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <receiver android:name=".BroadCastReceiver">
    <intent-filter android:priority="2147483647">
        <action android:name="android.provider.Telephony.SMS_RECEIVED" />
    </intent-filter>
</receiver>

        <activity
            android:name="com.example.sms.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

</manifest>

注意:我在Android模拟器上测试了Android 2.2上的应用程序“使用Telnet发送短信”

1 个答案:

答案 0 :(得分:1)

检查您的应用是否正在运行,然后仅中止广播接收器

//define this variable above onReceive() with default value as false;
boolean appRunningInBack=false;

ActivityManager am = (ActivityManager) mContext.getSystemService(Activity.ACTIVITY_SERVICE);
String packageName = am.getRunningTasks(1).get(0).topActivity.getPackageName();

if(packageName.equalIgnoreCase("your app package name") || appRunningInBack)
{    
    appRunningInBack=true;
    abortBroadCast();
} else {

}

还在 AndroidManifest.xml

中添加权限
<uses-permission android:name="android.permission.GET_TASKS" />

在此之后,当你的应用程序在运行时进入background.or。这个变量将是真的。