我正在学习机器人,我被困在这里:
我正在编写的应用程序定期扫描背景中的Wifi信号。我正在使用android意图服务。问题是,应用程序永远不会执行BroadCastReceiver的 onReceive()方法
意图代码:
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意图服务的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写得正确..
答案 0 :(得分:0)
编辑:我可能在这里误解了你的目标,如果你只是想知道为什么你的onReceive()没有被解雇,你的活动必须注册接收者。如下所示:
receiverWifi = new WifiReceiver();
registerReceiver(receiverWifi, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
doInback();
答案 1 :(得分:0)
所以问题在于我正在使用的功能。
我正在使用 onHandleIntent(intent)这是错误的功能。正确的是 onStartCommand(intent,flags,startId)用于服务。
我很抱歉......