gpt4 book ai didi

java - Android自定义服务-类实现

转载 作者:行者123 更新时间:2023-12-03 13:11:39 25 4
gpt4 key购买 nike

在确定应该实现我的后台自定义服务类的方式时,我有些困惑。

我需要的 :

  • 位置更新和 Activity 识别。
  • REST API调用和Geofence API。

  • 我是Android后台处理的新手,我不确定如何实现此功能。

    是否可以制作ThreadPoolExecutor(任务管理器类,可运行对象等)并处理线程间通信?

    如果是,是否可以在Thread类中监听位置更新?

    现在,我正在使用此库( Smart-location-lib)来收听位置更新。

    有更好的解决方案吗?

    任何帮助是极大的赞赏 !

    最佳答案

    这是在后台服务中使用Google API的最佳方法
    您没有解释 Activity 识别的含义是什么?

    public class MyLocationService extends Service implements LocationListener,
    GoogleApiClient.ConnectionCallbacks,
    GoogleApiClient.OnConnectionFailedListener {

    private GoogleApiClient mGoogleApiClient;
    private LocationRequest mLocationRequest;

    public MyLocationService() {

    }

    @Override
    public void onCreate() {
    super.onCreate();

    mGoogleApiClient = new GoogleApiClient.Builder(this)
    .addApi(LocationServices.API).
    addConnectionCallbacks(this).
    addOnConnectionFailedListener(this)
    .build();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
    mGoogleApiClient.connect();
    Toast.makeText(this, "Location services started", Toast.LENGTH_SHORT).show();
    return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public IBinder onBind(Intent intent) {
    // TODO: Return the communication channel to the service.
    throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    public void onLocationChanged(Location location) {
    System.out.println("MyLocationService.onLocationChanged");
    // TODO with location updateshere
    }

    @Override
    public void onConnected(Bundle bundle) {

    mLocationRequest = LocationRequest.create();
    mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    mLocationRequest.setInterval(1000); // Update location every second

    LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
    Location loc = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
    sendMyLocUpdate(loc, UserProfile.DRIVER);
    }

    @Override
    public void onConnectionSuspended(int i) {

    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {

    }

    @Override
    public void onDestroy() {

    Toast.makeText(this, "Location services stopped", Toast.LENGTH_LONG).show();

    Location loc = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
    sendMyLocUpdate(loc, UserProfile.PASSENGER);

    mGoogleApiClient.disconnect();
    super.onDestroy();
    }

    }

    关于java - Android自定义服务-类实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30585373/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com