首页 > 解决方案 > android:重启后注册接收器

问题描述

当设备启动时,我创建了一个被BroadcastReceiver调用的调用:Autostart

public class Autostart extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent arg1)
    {
        Log.i("mydebug","autostart");
        Intent intent = new Intent(context, RegisterService.class);
        context.startService(intent);

    }
}

这是应该被调用的服务:

public class RegisterService extends Service {


    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.i("mydebug","service");
        BroadcastReceiver receiver = new NetWatcher();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
        registerReceiver(receiver, intentFilter);
        return super.onStartCommand(intent, flags, startId);
    }
}

这里是我的清单:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.ginso.podcasts">
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <receiver android:name=".NetWatcher">
            <intent-filter>
                <action android:name="android.net.conn.CONNECTIVITY_CHANGE"/>
            </intent-filter>
        </receiver>
        <receiver android:name=".Autostart">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
            </intent-filter>
        </receiver>
        <service android:name=".RegisterService"/>
    </application>

</manifest>

我也以同样的方式在我的 MainActivity 中注册 NetWatcher。现在,当我启动应用程序时,Netwatcher 会立即被调用,而且每次我更改我的 wifi 状态时。当我重新启动手机时,自动启动会调用该服务,该服务会注册 NetWatcher,该服务也会立即被调用。但是如果我现在改变wifi状态,什么都不会发生

标签: android

解决方案


在您的服务中注册 NetWatcheronCreate()尝试将您的操作更改为android.net.conn.CONNECTIVITY_CHANGEWifiManager.NETWORK_STATE_CHANGED_ACTION


推荐阅读