我想拦截传入的消息,所以我创建了一个扩展 BroadcastReceiver 的类(如此处给出)它工作但我想控制接收器(在需要时停止它)我实现了这个但现在当我退出活动时接收器没有工作。
如何实现接收器,以便在活动不运行时可以控制和接收广播?
主要活动
public class MainActivity extends Activity {
Button StopB;
IntentFilter STARTER;
final BroadcastReceiver MSgR=new BR();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
StopB=(Button) findViewById(R.id.button1);
final BroadcastReceiver MSgR=new BR();
STARTER=new IntentFilter();
STARTER.addAction("android.provider.Telephony.SMS_RECEIVED");
registerReceiver(MSgR, STARTER);
StopB.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Log.i("Pressed", "UNRGSTR");
unregisterReceiver(MSgR);
}
} ) ;
}
BR.java
public class BR extends BroadcastReceiver{
String TAG="DELETE BLOCK";
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
// do something here
}
显现
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<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" >
<activity
android:name="com.example.delete_sms_2.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>
<receiver android:name="BR"></receiver>
</application>
</manifest>