只要我的应用程序正在运行,我就想阻止传入的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); } }
体现:
<?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模拟器“使用Telnet发送SMS消息”上的android 2.2上测试了该应用程序
检查您的应用程序是否正在运行,然后仅中止广播接收器,否则不运行
//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" />
之后,当您的应用进入后台或运行时,此变量为true。