在服务中注册接收器

我有一个service ,可以启动和停止从一个button

但在service范围内,我想注册一个接收器来收听短信广播。 我只想让service在运行时收听短信。 我尝试registerReceiver(receiver, intentfilter)但这是行不通的。 我究竟做错了什么?

Solutions Collecting From Web of "在服务中注册接收器"

您必须在AndroidManifest文件中设置权限。

  <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"/> 

如果您只想在服务运行时接收广播,则需要在onCreate()中dynamic注册接收器

另外重要的是不要忘记在onDestroy()方法中注销你的接收器!

例:

 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(); } } 

从xml中删除意图filter,只做接收器的dynamic注册。 如果在服务closures时不希望它工作,则在停止服务之前取消注册。 不要忘了将权限添加到xml,虽然….