BroadcastReceiver不是从服务开始的

时间:2013-12-09 08:02:51

标签: android service broadcastreceiver

我需要从一个服务启动一个广播接收器并且它不能正常工作,我遵循了一些教程,一切似乎都是正确的但不是。

这是我的代码:

    public class ServiceNotif extends Service{


        smsReceiver receiver;  
            private static final IntentFilter intentFilter = 
                    new IntentFilter("android.provider.Telephony.SMS_RECEIVED");

        @Override
        public void onCreate() {
            // TODO Auto-generated method stub
            super.onCreate();
            Log.w("A intrat in service"," ");
            Toast.makeText(getBaseContext(), 
                    "A intrat in service", 
                    Toast.LENGTH_SHORT).show();
             //daca primesc un mesaj se intra in functia asta
receiver = new smsReceiver();
            registerReceiver(receiver, intentFilter);
        }

        @Override
        public void onDestroy() {
            // TODO Auto-generated method stub
            super.onDestroy();
            unregisterReceiver(receiver);
        }

        @Override
        public IBinder onBind(Intent intent) {
            return mBinder;
        }

        // This is the object that receives interactions from clients.  See
        // RemoteService for a more complete example.
        private final IBinder mBinder = new LocalBinder();

         /**
         * Class for clients to access.  Because we know this service always
         * runs in the same process as its clients, we don't need to deal with
         * IPC.
         */
        public class LocalBinder extends Binder {
            ServiceNotif getService() {
                return ServiceNotif.this;
            }
        }
        @Override
        public int onStartCommand(Intent intent, int flags, int startId) {
            Log.i("LocalService", "Received start id " + startId + ": " + intent);
            // We want this service to continue running until it is explicitly
            // stopped, so return sticky.
            return START_STICKY;
        }

    }

为什么收到消息时接收器不会被触发?

编辑: 我也在日志中得到这个:

12-09 08:16:05.708: W/GAV3(1183): Thread[GAThread,5,main]: Service unavailable (code=1), will retry.
12-09 08:16:05.718: I/GAV3(1183): Thread[GAThread,5,main]: No campaign data found.
12-09 08:16:10.779: W/GAV3(1183): Thread[Service Reconnect,5,main]: Service unavailable (code=1), using local store.

1 个答案:

答案 0 :(得分:1)

  

为什么收到消息时接收器不会被触发?

因为您没有初始化Receiver。注册前在onCreate()初始化。

@Override
public void onCreate() {
    super.onCreate();
    Log.w("A intrat in service"," ");
    Toast.makeText(getBaseContext(), 
            "A intrat in service", 
            Toast.LENGTH_SHORT).show();
     //daca primesc un mesaj se intra in functia asta
    receiver = new BroadcastReceiver(); // init the Receiver
    registerReceiver(receiver, intentFilter);
}

编辑:

确保您在清单中拥有正确的权限。

<manifest
    ...
    <uses-permission android:name="android.permission.RECEIVE_SMS" />
    ...
</manifest>