我正在学习android,并且被困在这里:
我正在编写的应用程序会定期在后台扫描Wifi信号。我正在使用android intent服务。问题是,应用程序永远不会执行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 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的编写正确。
所以问题出在我正在使用的功能上。
我使用的是onHandleIntent(intent),这是错误的函数。右一个是用于服务的onStartCommand(intent,flags,startId)。
不好意思..
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句