2

我正在编写一个监听传入短信的应用程序。因此,我为此编写了一个服务来启动 BroadcastReceiver。该服务由我的应用程序启动,但是当后者被销毁时,我的服务似乎没有听任何东西。由于此服务的目的是收听传入的 SMS,因此它必须“永远”运行(或由于内存管理而重新启动)。

这是一些代码:

public class SmsService extends Service {

    private final static String TAG = SmsService.class.getSimpleName();
    public static boolean SMS_SERVICE_STARTED = false;
    private boolean mRegistered = false;
    public final static String SMS_PORT = "port";

    private SMSReceiver mSmsReceiver = null; // this is the BroadcastReceiver listening to SMS

    public SmsService() {
        super();
        Log.d(TAG, "SmsService");
    }

    @Override
    public void onCreate() {
        Log.d(TAG, "onCreate");
        SMS_SERVICE_STARTED = true;
    }

    @Override
    public void onDestroy() {
        Log.d(TAG, "onDestroy");
        stopListenSms();
        SMS_SERVICE_STARTED = false;
    }

    @Override
    public IBinder onBind(Intent intent) {
        Log.d(TAG, "onBind");
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d(TAG, "onStartCommand");

        if (intent != null && intent.hasExtra(SMS_PORT)) {
            Log.d(TAG, "we got extra!");
            short port = intent.getShortExtra(SMS_PORT, (short) 0);
            startListenSms(port);
        } else {
            Log.d(TAG, "no extra :(");
        }

        return START_STICKY;
    }

    private void startListenSms(short port) {
        Log.d(TAG, "startListenSms on port " + port);

        mSmsReceiver = new SMSReceiver();
        IntentFilter filter = new IntentFilter(
                "android.intent.action.DATA_SMS_RECEIVED");
        filter.addDataScheme("sms");
        String strPort = String.valueOf(port);
        filter.addDataAuthority("localhost", strPort);
        registerReceiver(mSmsReceiver, filter);
        mRegistered = true;
    }

    private void stopListenSms() {
        Log.d(TAG, "stopListenSms");
        if (mSmsReceiver != null) {
            if (mRegistered)
                unregisterReceiver(mSmsReceiver);
            mSmsReceiver = null;
        }
    }
}

我观察到,当它的活动被破坏时,onStartCommand 会以空 Intent 调用。你知道为什么我的服务在活动被破坏时停止运行吗?我该怎么做才能让它“永远”运行?

在此先感谢,干杯。

4

2 回答 2

5

Why do you need to run a service to listen to incoming SMS. Broadcast receiver itself serves the purpose, it will keep listening to the incoming message once you configured in the intent filter while registering the receivers. There are tons of examples Broadcast Receiver and SMS listening. Please go through those example and build your code efficiently

于 2013-01-28T21:54:14.860 回答
0

服务也有生命周期,可以被系统终止。您无法阻止这种情况,尽管您可以将服务置于前台,这使得系统更难终止它。尽管如此,它仍然是可能的;服务不能永远运行。查看服务的生命周期:http: //developer.android.com/reference/android/app/Service.html#ServiceLifecycle

您需要的是一个侦听 SMS 意图的 BroadcastReceiver(我不知道它到底是哪一个)。BroadcastReceiver 可以注册某些意图(例如,传入的 SMS),并在系统发送此类意图时启动。请参阅http://developer.android.com/reference/android/content/BroadcastReceiver.html

于 2013-01-28T21:50:34.397 回答