我想拦截传入的消息,所以我创建了一个扩展BroadcastReceiver的类(如给定的here),但是因为我想控制接收器(在需要时停止它)我实现了this但是现在,当我退出活动时,接收器不起作用。
如何实现接收器,以便在活动未运行时可以控制和接收广播?
Mainactivity
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>
答案 0 :(得分:4)
定义接收器何时启动,你定义什么时候活动开始然后重新开始工作,你需要改变menifest文件,就像在这个意图过滤器中收到sms一样,就像你改变它需要感谢
<receiver android:name=".HellowordActivity" >
<intent-filter >
<action android:name="android.provider.Telephony.SMS_RECEIVED"/>
</intent-filter>
</receiver>