我已经创建了一个名为Autostart的BroadcastReceiver,在设备启动时将调用它:
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。当我重新启动手机时,自动启动会调用该服务,该服务会注册NetWatcher,也会立即调用该服务。但是如果我现在改变wifi状态,什么都不会发生。
发布于 2019-01-14 18:24:19
在服务的onCreate()中注册NetWatcher尝试将您的操作更改为android.net.conn.CONNECTIVITY_CHANGE而不是WifiManager.NETWORK_STATE_CHANGED_ACTION
https://stackoverflow.com/questions/54179413
复制相似问题