在服务中实现广播接收器

时间:2013-05-06 08:39:57

标签: android service broadcastreceiver internet-connection

我想在Android应用程序的整个运行时检查Internet连接。我尝试过使用服务,但似乎不是最好的选择。我有可能在服务中实现广播接收器吗?或者我是否必须放弃服务并单独使用广播接收器?

4 个答案:

答案 0 :(得分:7)

我现在展示如何在服务中创建SMS接收器:

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
        }
    }
}

答案 1 :(得分:2)

每秒检查一次连接是不明智的。或者,您可以收听操作( ConnectivityManager.CONNECTIVITY_ACTION ),并确定您是否已连接到活动网络。

IntentFilter filter = new IntentFilter();
filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);

此外,您可以检查当前活动的网络类型(Type_WIFI,Type_MOBILE)

这样,您不需要每秒都检查连接的服务。

答案 2 :(得分:2)

我希望这link会有所帮助。只是通过它。

答案 3 :(得分:1)

您无需为此目的使用ServiceBroadCastReceiver。只需检查ping服务器所需的每个时间的连接状态。

您可以编写一个检查此方法的方法,并根据连接状态返回boolean(true / false)。 以下方法也是如此。

public static boolean isNetworkAvailable(Context mContext) {

        try {
            final ConnectivityManager conn_manager = (ConnectivityManager) mContext
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            final NetworkInfo network_info = conn_manager
                    .getActiveNetworkInfo();

            if (network_info != null && network_info.isConnected()) {
                if (network_info.getType() == ConnectivityManager.TYPE_WIFI)
                    return true;
                else if (network_info.getType() == ConnectivityManager.TYPE_MOBILE)
                    return true;
            }

        } catch (Exception e) {
            // TODO: handle exception
        }
        return false;

    }
相关问题