无法在后台线程上执行工作

时间:2020-05-21 01:11:02

标签: java android multithreading

因此,我正在关注this tutorial,以在我的应用中实现服务。我成功实现了服务。服务已激活,并且通知正常显示。一切都很好,除了我无法在后台线程上工作。请参见下面。

我的目标是设置模拟位置。

这是我为我的服务onStartCommand

@Override
public int onStartCommand(Intent intent, int flags, int startId) {



    Intent notificationIntent = new Intent(this, MainActivity.class);
    PendingIntent pendingIntent = PendingIntent.getActivity(this,
            0, notificationIntent, 0);

    Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
            .setContentTitle("Example Service")
            .setContentText("hi")
            .setSmallIcon(R.drawable.icon)
            .setContentIntent(pendingIntent)
            .build();


    startForeground(1, notification);

    //do work on a background thread
    new Thread(new Runnable() {
        @Override
        public void run() {

            startMockLocation(); // doesn't actually mock device's location!
        }
    }).start();

    return START_NOT_STICKY;
}

但是,当我这样做时,它可以正常工作,但是效率不高:

@Override
public int onStartCommand(Intent intent, int flags, int startId) {



    Intent notificationIntent = new Intent(this, MainActivity.class);
    PendingIntent pendingIntent = PendingIntent.getActivity(this,
            0, notificationIntent, 0);

    Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
            .setContentTitle("Example Service")
            .setContentText("hi")
            .setSmallIcon(R.drawable.icon)
            .setContentIntent(pendingIntent)
            .build();


    startForeground(1, notification);

// works great
timer.schedule(new TimerTask() {
    @Override
    public void run() {

        startMockLocation();
        //other stuff
    }
}, 0, 1000);

    return START_NOT_STICKY;
}

模拟定位方法:

public void startMockLocation(){ // this code is fine, nothing to fix here, something is wrong with the thread though :(

    FusedLocationProviderClient locationProvider =  new FusedLocationProviderClient(getApplicationContext());
    locationProvider.setMockMode(true);

    Location loc = new Location("gps");

    Location mockLocation = new Location("gps"); // a string
    mockLocation.setLatitude(48.8566);
    mockLocation.setLongitude(2.3522);
    mockLocation.setAltitude(loc.getAltitude());
    mockLocation.setTime(System.currentTimeMillis());

    mockLocation.setAccuracy(1f);
    mockLocation.setElapsedRealtimeNanos(SystemClock.elapsedRealtimeNanos());
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        mockLocation.setBearingAccuracyDegrees(0.1f);
        mockLocation.setVerticalAccuracyMeters(0.1f);
        mockLocation.setSpeedAccuracyMetersPerSecond(0.01f);
    }
    locationProvider.setMockLocation(mockLocation);

}

1 个答案:

答案 0 :(得分:3)

如果无法在后台线程中工作,则意味着您看不到startMockLocation()的效果,这取决于是否有任何计算依赖于startMockLocation()。如果您不加入线程或在某处阻塞,而是等待后台线程完成,则主线程可能会运行良好直到终止,直到后台线程完成其工作为止。看起来您的后台线程没有执行任何操作。

相关问题