Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
580 views
in Technique[技术] by (71.8m points)

android - Implement Broadcast receiver inside a Service

I want to check Internet connection throughout the run time of my Android application. I tried using services but seems like it is not the best option. Is there any possible way for me to implement a broadcast receiver with in a service? Or do I have to give up the service and use broadcast receivers alone?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I will show you how to create SMS receiver in a service:

public class MyService extends Service {

@Override
public void onCreate() {
    BwlLog.begin(TAG);
    super.onCreate();

    SMSreceiver mSmsReceiver = new SMSreceiver();
    IntentFilter filter = new IntentFilter();
    filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
    filter.addAction(SMS_RECEIVE_ACTION); // SMS
    filter.addAction(WAP_PUSH_RECEIVED_ACTION); // MMS
    this.registerReceiver(mSmsReceiver, filter);

}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    super.onStartCommand(intent, flags, startId);
    return START_STICKY;
}

   /**
 * This class used to monitor SMS
 */
class SMSreceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {

        if (TextUtils.equals(intent.getAction(), SMS_RECEIVE_ACTION)) {
             //handle sms receive
        }
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...