アンドロイドには若干の新サービスが必要です。インターバルXで現在の場所をポーリングするサービスがあります。そのサービスにバインドして、サービスからgetLastKnownLocationをアクティビティAに渡したいと思います。情報がバインドされたサービスからアクティビティにどのように渡されているか正確にはわかりませんそのバインダーまたは何を介して。とにかく、私はこれまでのところ私のコードです。サービスからの所在地の取得方法
サービス:
public class LocationService extends Service implements LocationListener {
LocationManager myLocationManager;
public Location myLocation;
LocationListener myLocationListener;
public static final String TAG = LocationService.class.getSimpleName();
MyDB db;
double latitude,longitude;
Cursor c;
@Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
Log.d(TAG, "service started (onCreate)");
db = new MyDB(getApplicationContext());
myLocationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
criteria.setPowerRequirement(Criteria.POWER_LOW);
criteria.setAccuracy(Criteria.ACCURACY_LOW);
String locationProvider = myLocationManager.getBestProvider(criteria, true);
myLocationManager.requestLocationUpdates(locationProvider, 1000*60*2, 100, this);
myLocation = myLocationManager.getLastKnownLocation(locationProvider);
}
public class MyBinder extends Binder {
LocationService getService() {
return LocationService.this;
}
}
活動A:
public class myActivity extends Activity {
LocationManager myLocationManager;
Location myLocation;
boolean isBound = false;
private LocationService mBoundService;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
bindLocationService();
}
private void bindLocationService() {
try {
isBound = getApplicationContext().bindService(new Intent(getApplicationContext(), LocationService.class), mConnection, BIND_AUTO_CREATE);
bindService(new Intent(this, LocationService.class), mConnection, BIND_AUTO_CREATE);
} catch (SecurityException e) {
// TODO: handle exception
}
}
private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
mBoundService = ((LocationService.MyBinder)service).getService();
Log.d(LocationService.TAG, "activity bound to service");
}
public void onServiceDisconnected(ComponentName className) {
mBoundService = null;
Log.d(LocationService.TAG, "activity unbound to service");
}
};
}
ロケーションを取得するにはLocationListenerを実装してリスニングを開始するだけです。これは別のスレッドで実行されます。 yway。ここでサービスを使用する特別な理由はありますか? –