android - 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状态,什么都不会发生
解决方案
在您的服务中注册 NetWatcheronCreate()
尝试将您的操作更改为android.net.conn.CONNECTIVITY_CHANGE
WifiManager.NETWORK_STATE_CHANGED_ACTION
推荐阅读
- javascript - 如何解决 Windows 中的“npm ERR!code ELIFECYCLE”错误
- php - 基于php codeigniter中条件的数据表颜色变化
- c++ - 是否使用 if (0) 跳过应该工作的开关中的一个案例?
- vue.js - 如何通过 API 调用的响应对 Vue 列表组的特定列表项做出反应?
- c++ - 如何在 Boost.asio 中设置写入超时
- java - 如何拆分这个 Xpath?
- sql - ORA-01821:Oracle 日期时间转换
- javascript - mysq-events 多个观察者不好的做法?
- c++ - 在 C++ 模板中将类型传递给 Lambda 函数
- angular - Angular:如何在 innerHTML 中加载安全图像