Android通过广播接收器和服务获取位置

时间:2019-04-26 07:38:35

标签: java android

我正在构建一个应用程序,该程序将跟踪他们是否在特定时间访问过某个地方,并且有两个实现了我正在遵循的目标

  • 使用alarm manager启动BroadcastReceiver
  • 在BroadcastReceiver中,我正在启动一项服务,该服务将获取用户的最后一个已知位置

我不知道这是完成此操作的最佳方法,它有时起作用,有时应用程序崩溃。下面是我的代码,如果有人告诉我我做错了,那将是很好的。

MainActivty

Calendar rightNow = Calendar.getInstance();
        int currentHourIn24Format = rightNow.get(Calendar.HOUR_OF_DAY);
        int currentMinuteIn24Format = rightNow.get(Calendar.MINUTE);

       // Toast.makeText(this, "Time is:"+currentMinuteIn24Format, Toast.LENGTH_SHORT).show();


        Calendar cal1 = Calendar.getInstance();
        cal1.set(Calendar.HOUR_OF_DAY, currentHourIn24Format);
        cal1.set(Calendar.MINUTE, currentMinuteIn24Format+1);
        cal1.set(Calendar.SECOND, 00);

        Calendar cal2 = Calendar.getInstance();
        cal2.set(Calendar.HOUR_OF_DAY, currentHourIn24Format);
        cal2.set(Calendar.MINUTE, currentMinuteIn24Format+2);
        cal2.set(Calendar.SECOND, 30);

         // Test if the times are in the past, if they are add one day
        Calendar now = Calendar.getInstance();
        if(now.after(cal1))
            cal1.add(Calendar.HOUR_OF_DAY, 24);
        if(now.after(cal2))
            cal2.add(Calendar.HOUR_OF_DAY, 24);

        // Create two different PendingIntents, they MUST have different requestCodes
        Intent intent = new Intent(this, YourBroadCastReceiver.class);
        PendingIntent morningAlarm = PendingIntent.getBroadcast(getApplicationContext(), 0, intent, 0);
        PendingIntent eveningAlarm = PendingIntent.getBroadcast(getApplicationContext(), 1, intent, 0);

        // Start both alarms, set to repeat once every day
        AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
        alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, cal1.getTimeInMillis(), DateUtils.DAY_IN_MILLIS, morningAlarm);
        alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, cal2.getTimeInMillis(), DateUtils.DAY_IN_MILLIS, eveningAlarm);  

BroadCastReceiver

  @Override
    public void onReceive(Context context, Intent intent) {

        Intent i = new Intent(context, LocationService.class);
        context.startService(i);

    }

LocationService

public class LocationService extends Service implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
    private GoogleApiClient mGoogleApiClient;
    public LocationService() {
    }
    @Override
    public void onCreate() {
       // Toast.makeText(this, "Service started....", Toast.LENGTH_SHORT).show();
        if (mGoogleApiClient == null) {
            mGoogleApiClient = new GoogleApiClient.Builder(this)
                    .addConnectionCallbacks(this)
                    .addOnConnectionFailedListener(this)
                    .addApi(LocationServices.API)
                    .build();
        }
        mGoogleApiClient.connect();
    }
    @Override
    public void onDestroy() {
       // mGoogleApiClient.disconnect();
    }
    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }
    @Override
    public void onConnected(@Nullable Bundle bundle) {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            //ActivityCompat.requestPermissions(LocationService.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
            return;
        }
        Location mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
        if (mLastLocation != null) {
            String location  = mLastLocation.getLatitude()+","+mLastLocation.getLongitude();
            Toast.makeText(this, location, Toast.LENGTH_LONG).show();
        }
    }
    @Override
    public void onConnectionSuspended(int i) {
    }
    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
    }
}

0 个答案:

没有答案