开发者

Broadcast receiver for internet connection from a Service

I am implementing a Broadcast receiver inside a serv开发者_Go百科ice which is supposed to be listening for internet connection availability. The service is started from the main activity of the application. The problem is that the broadcast listener does not actually listen to anything. My code is :

public class MyService extends Service {

public final static String SEND_DATA_BROADCAST = "com.myapp.SEND_DATA"; 
private final static String LOG_TAG="-Service-";
private BroadcastReceiver   updateListener;

@Override
public void onCreate()
{
    super.onCreate();

    //create listener

     final IntentFilter theFilter = new IntentFilter();
        theFilter.addAction(SEND_DATA_BROADCAST);
        this.updateListener = 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...
                Log.d(LOG_TAG,"Listening..");
            }
        };

    // register listener
    Log.d(LOG_TAG,"Registering Listener");
    this.registerReceiver(this.updateListener, theFilter);
    listenerRegistered = true;
    Log.d(LOG_TAG,"Listener Registered");
}


I did a quick search of all the intents available and it seems what you are trying to do cannot be identified as an intent (and hence detected by a BroadcastReceiver)

try using the class PhoneStateListener.

there should be plenty of examples of using that class out there, and you should be looking out for this onDataConnectionStateChanged() callback method, together with this LISTEN_DATA_CONNECTION_STATE flag... or something similar.


You should break your BroadcastReceiver out into its own class, and register it in your manifest. Otherwise, it won't get registered until after your Service is started. More details on doing that can be found here: http://developer.android.com/reference/android/content/BroadcastReceiver.html

Its hard to help further without a detailed explanation of what you mean by "the broadcast listener does not work properly".

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜