register receiver in a service

前端 未结 3 1052
青春惊慌失措
青春惊慌失措 2020-12-01 05:01

I have a service that can be started and stopped from a button.

But within the service I want to register a reciever to listen

相关标签:
3条回答
  • 2020-12-01 05:42

    Remove the intent-filter from the xml and do only the dynamic registration of the Receiver. If you do not want it working when the service is off, then unregister it before stopping the service. Do not forget to add the permission to the xml though....

    0 讨论(0)
  • 2020-12-01 05:43

    If you want to only receive the broadcast while your service is running you will need to dynamically register your receiver in onCreate()

    Also it is important to not forget to unregister your receiver in the onDestroy() method!

    Example:

    import android.app.Service;
    import android.content.BroadcastReceiver;
    import android.content.Context;
    import android.content.Intent;
    import android.content.IntentFilter;
    import android.os.IBinder;
    import android.widget.Toast;
    
    public class YourClass extends Service {
    
        private static final String ACTION="android.provider.Telephony.SMS_RECEIVED";
        private BroadcastReceiver yourReceiver;
    
        @Override
        public IBinder onBind(Intent arg0) {
            return null;
        }
    
        @Override
        public void onCreate() {
            super.onCreate();
            final IntentFilter theFilter = new IntentFilter();
            theFilter.addAction(ACTION);
            this.yourReceiver = new BroadcastReceiver() {
    
                @Override
                public void onReceive(Context context, Intent intent) {
                    // Do whatever you need it to do when it receives the broadcast
                    // Example show a Toast message...
                    showSuccessfulBroadcast();
                }
            };
            // Registers the receiver so that your service will listen for
            // broadcasts
            this.registerReceiver(this.yourReceiver, theFilter);
        }
    
        @Override
        public void onDestroy() {
            super.onDestroy();
            // Do not forget to unregister the receiver!!!
            this.unregisterReceiver(this.yourReceiver);
        }
    
        private void showSuccessfulBroadcast() {
            Toast.makeText(this, "Broadcast Successful!!!", Toast.LENGTH_LONG)
                    .show();
        }
    }
    
    0 讨论(0)
  • 2020-12-01 05:47

    You must set permissions in the AndroidManifest file.

        <receiver android:name=".MySMSReciever"> 
            <intent-filter> 
                <action android:name=
                    "android.provider.Telephony.SMS_RECEIVED" /> 
            </intent-filter> 
        </receiver>
    
    <uses-permission android:name="android.permission.RECEIVE_SMS"/>
    
    0 讨论(0)
提交回复
热议问题