我正在学习 android,但我被困在这里:
我正在编写的应用程序会定期在后台扫描 Wifi 信号。我正在使用 android Intent 服务来实现同样的目的。问题是,应用程序永远不会执行 BroadCastReceiver 的 onReceive() 方法
Intent 代码:
public class BackgroundIntent extends IntentService {
// Default Constructor
public BackgroundIntent() {
super("BackgroundIntent");
// TODO Auto-generated constructor stub
}
WifiManager mainWifi;
BroadcastReceiver receiverWifi;
private final Handler handler = new Handler();
@TargetApi(Build.VERSION_CODES.GINGERBREAD)
@Override
protected void onHandleIntent(Intent intent) {
// TODO Auto-generated method stub
// Get mainWifi
mainWifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
if (mainWifi.isWifiEnabled() == false) {
mainWifi.setWifiEnabled(true);
}
receiverWifi = new WifiReceiver();
doInback();
}
// Basically a thread which calls itself after 5000milli sec
public void doInback() {
handler.postDelayed(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
mainWifi.startScan();
Log.i("Inside ", "doInBack");
// Call itself CODE GOES HERE :D
doInback();
}
}, 5000);
}
public class WifiReceiver extends BroadcastReceiver {
@TargetApi(Build.VERSION_CODES.GINGERBREAD)
public void onReceive(Context c, Intent intent) {
// CODE NEVER GOES HERE :(
List<ScanResult> wifiList;
wifiList = mainWifi.getScanResults();
Log.i("Inside receiver", "yes");
}
}
}
调用android Intent服务的MainActivity代码
public class MainActivity extends Activity {
TextView texty;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Intent is called here
Intent myIntent = new Intent(MainActivity.this, BackgroundIntent.class);
startService(myIntent);
texty = (TextView) findViewById(R.id.textView1);
}
public boolean onMenuItemSelected(int featureId, MenuItem item) {
return super.onMenuItemSelected(featureId, item);
}
}
知道可能是什么原因吗?这是实现后台wifi信号扫描的错误方法吗? 当我在 Main Activity 中实现时,运行良好,所以我猜测 AndroidManifest.xml 的编写正确..
最佳答案
编辑:我可能在这里误解了你的目标,如果你只是想知道为什么你的 onReceive() 没有触发,你的 Activity 必须注册接收器。类似于以下内容:
receiverWifi = new WifiReceiver();
registerReceiver(receiverWifi, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
doInback();
关于java - Android Intent 内的 Wifi 广播 Android,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24222937/