我有一个位置监听器在服务类内部的一个单独的线程上运行,如下所示:
public void onCreate() {
locationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
final Criteria locCriteria = new Criteria();
locCriteria.setPowerRequirement(Criteria.POWER_LOW);
locCriteria.setAccuracy(Criteria.ACCURACY_FINE);
locCriteria.setSpeedRequired(true);
locThread = new Thread(new Runnable() {
@Override
public void run() {
provider = locationManager.getBestProvider(locCriteria, true);
listener = new LocationListener() {
@Override
public void onLocationChanged(Location location) {
longitude = location.getLongitude();
latitude = location.getLatitude();
Log.i("Lat changed", String.valueOf(latitude));
Log.i("Lon changed", String.valueOf(longitude));
}
如何将cordinates发送回主活动类以使其显示在文本视图中?除了使用广播。
答案 0 :(得分:1)
尝试使用我的代码
创建类似
的界面public interface Message {
void latitudeandlongitude(double lat,double log);
}
然后在您的服务类
public void oncreate()
{
Message ms=new Activity();
new Thread(new Runnable() {
@Override
public void run() {
for(int i=0;i<=10;i++)
{
//pass the latitude and longitude value
ms.latitudeandlongitude(50.264,96.856);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
}
然后在您的活动中
public class Activity implements Message {
String textview; //use findviewbyId in oncreate method
@Override
public void latitudeandlongitude(double lat, double log) {
textview.setText("Your latitude "+lat+" Your longitude "+log);
//System.out.println("Your latitude "+lat+" Your longitude "+log);
}
}
答案 1 :(得分:0)
您可以将LocationListener
的实例传递给您的服务,而不是在那里实现侦听器。例如:
public class MyService extends Service {
private LocationListener locationListener;
public MyService(LocationListener locationListener) {
this.locationListener = locationListener;
}
@Override
public void onCreate() {
// Do your stuff
// add this location listener where it needs to be
}
}
然后,在您的活动或片段中,您实施LocationListener
并根据需要处理结果。