0

我想拦截传入的消息,所以我创建了一个扩展 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>
4

1 回答 1

4

定义接收器何时开始,您定义活动何时开始然后接收工作,您需要更改清单文件,就像收到短信时在这个意图过滤器中一样,就像您根据您的需要更改它一样谢谢

 <receiver android:name=".HellowordActivity" >
            <intent-filter > 
            <action android:name="android.provider.Telephony.SMS_RECEIVED"/> 
            </intent-filter> 
    </receiver> 
于 2013-04-24T06:23:33.497 回答