【发布时间】:2014-08-05 01:16:27
【问题描述】:
我正在学习android,我被困在这里:
我正在编写的应用程序会定期在后台扫描 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 是正确编写的..
【问题讨论】:
标签: java android android-intent android-wifi