1

我想捕获 Android 服务中的网络连接类型更改,并在事件触发时运行此服务的代码。如何在没有单独的类的情况下在服务类中做到这一点?我有这个代码,但它不起作用。

 BroadcastReceiver networkStateReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            playlist="NETWORK TYPE CHANGED";
        }
    };

 public void playSong(Context c, String url) {

        try
        {

IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);        
            registerReceiver(networkStateReceiver, filter);
4

1 回答 1

1

您的 BroadcastReceiver 需要从系统接收 Intent,因此您需要在 AndroidManifest 中注册您的 BroadcastReceiver

<receiver
    android:name=".ConnectivityReceiver
    android:exported="false" >
    <intent-filter>
        <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
    </intent-filter>
</receiver>

并且不要忘记许可

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
于 2013-07-26T18:31:05.967 回答