【问题标题】:How to communicate with continuously running background service in Activity?如何与Activity中持续运行的后台服务进行通信?
【发布时间】:2015-02-16 20:12:26
【问题描述】:

在我的项目中,有一个检索用户位置的服务。它在后台连续运行。我想在我的文本视图上设置位置。 所以,我有ManinActivity如下:

import android.app.Activity;
import android.app.Fragment;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

public class MainActivity extends Activity {
    GPSTracker gps;
    double mylatitude, mylongitude;
    TextView txt_location;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        txt_location = (TextView)findViewById(R.id.current_location);

        if (savedInstanceState == null) {
            getFragmentManager().beginTransaction().add(R.id.container, new PlaceholderFragment()).commit();
        }              
    }

    public void btn_remember_Clicked(View v)
    {
        Intent i = new Intent(MainActivity.this,RememberActivity.class);
        startActivity(i);
    }

    public void btn_show_places_Clicked(View v)
    {
        Intent i = new Intent(MainActivity.this,ShowPlacesActivity.class);
        startActivity(i);
    }

    public static class PlaceholderFragment extends Fragment {
        public PlaceholderFragment() {
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
            return inflater.inflate(R.layout.fragment_main, container, false);    
        }
    }
}

而我的LocationService类如下:

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;

public class LocationService extends Service
{
    public static final String BROADCAST_ACTION = "Hello World";
    private static final int TWO_MINUTES = 1000 * 60 * 2;
    public LocationManager locationManager;
    public MyLocationListener listener;
    public Location previousBestLocation = null;
    
    Intent intent;    
    
    @Override
    public void onCreate()
    {
        super.onCreate();
        intent = new Intent(BROADCAST_ACTION);
    }
    
    @Override
    public int onStartCommand(Intent intent,int flags, int startId)
    {
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        listener = new MyLocationListener();
        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 4000, 0, listener);
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 4000, 0, listener);
        return super.onStartCommand(intent, flags, startId);
    }
    
    @Override
    public IBinder onBind(Intent intent)
    {
        return null;
    }
    
    protected boolean isBetterLocation(Location location, Location currentBestLocation) {
        if (currentBestLocation == null) {
            // A new location is always better than no location
            return true;
        }
    
        // Check whether the new location fix is newer or older
        long timeDelta = location.getTime() - currentBestLocation.getTime();
        boolean isSignificantlyNewer = timeDelta > TWO_MINUTES;
        boolean isSignificantlyOlder = timeDelta < -TWO_MINUTES;
        boolean isNewer = timeDelta > 0;
    
        // If it's been more than two minutes since the current location, use the new location
        // because the user has likely moved
        if (isSignificantlyNewer) {
            return true;
            // If the new location is more than two minutes older, it must be worse
        } else if (isSignificantlyOlder) {
            return false;
        }
    
        // Check whether the new location fix is more or less accurate
        int accuracyDelta = (int) (location.getAccuracy() - currentBestLocation.getAccuracy());
        boolean isLessAccurate = accuracyDelta > 0;
        boolean isMoreAccurate = accuracyDelta < 0;
        boolean isSignificantlyLessAccurate = accuracyDelta > 200;
    
        // Check if the old and new location are from the same provider
        boolean isFromSameProvider = isSameProvider(location.getProvider(),
                    currentBestLocation.getProvider());
    
        // Determine location quality using a combination of timeliness and accuracy
        if (isMoreAccurate) {
            return true;
        } else if (isNewer && !isLessAccurate) {
            return true;
        } else if (isNewer && !isSignificantlyLessAccurate && isFromSameProvider) {
            return true;
        }
        return false;
    }
    
    /** Checks whether two providers are the same */
    private boolean isSameProvider(String provider1, String provider2) {
        if (provider1 == null) {
            return provider2 == null;
        }
        return provider1.equals(provider2);
    }
            
    @Override
    public void onDestroy() {
        // handler.removeCallbacks(sendUpdatesToUI);
        super.onDestroy();
        Log.v("STOP_SERVICE", "DONE");
        locationManager.removeUpdates(listener);
    }
    
    public static Thread performOnBackgroundThread(final Runnable runnable) {
        final Thread t = new Thread() {
            @Override
            public void run() {
                try {
                    runnable.run();
                } catch(Exception e) {
                    System.out.print(e);
                }
            }
        };
        t.start();
        return t;
    }
    
    public class MyLocationListener implements LocationListener {
        public void onLocationChanged(final Location loc) {
            Log.i("**************************************", "Location changed");
            if(isBetterLocation(loc, previousBestLocation)) {
                loc.getLatitude();
                loc.getLongitude();
                intent.putExtra("Latitude", loc.getLatitude());
                intent.putExtra("Longitude", loc.getLongitude());
                intent.putExtra("Provider", loc.getProvider());
                sendBroadcast(intent);        
            }
        }
    
        public void onProviderDisabled(String provider) {
            Toast.makeText( getApplicationContext(), "Gps Disabled", Toast.LENGTH_SHORT ).show();
        }
            
        public void onProviderEnabled(String provider) {
            Toast.makeText(getApplicationContext(), "Gps Enabled", Toast.LENGTH_SHORT).show();
        }
            
        public void onStatusChanged(String provider, int status, Bundle extras) {
        }
    }
}

我有LocationBroadcast 类如下:

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

public class LocationBroadcast extends BroadcastReceiver{
    @Override
    public void onReceive(Context ctx, Intent intent) {
        ctx.startService(new Intent(ctx, LocationService.class));
    }
}

我想在 MainActivity 中的 textview txt_location 上设置位置。我不太了解服务以及我们如何在 Activity 中进行通信。如何在 MainActivity 中获取纬度和经度?请帮忙。

更新:

我刚刚根据答案更新了我的代码:

public class LocationService extends Service
{
    private static final int TWO_MINUTES = 1000 * 60 * 2;
    public LocationManager locationManager;
    public MyLocationListener listener;
    public Location previousBestLocation = null;

    Intent i;

    @Override
    public void onCreate()
    {
        super.onCreate();
        i = new Intent("LOCATION_CHANGED");
    }

    @Override
    public int onStartCommand(Intent intent,int flags, int startId)
    {
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        listener = new MyLocationListener();
        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 4000, 0, listener);
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 4000, 0, listener);
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public IBinder onBind(Intent intent)
    {
        return null;
    }

    protected boolean isBetterLocation(Location location, Location currentBestLocation) {
        if (currentBestLocation == null) {
            // A new location is always better than no location
            return true;
        }

        // Check whether the new location fix is newer or older
        long timeDelta = location.getTime() - currentBestLocation.getTime();
        boolean isSignificantlyNewer = timeDelta > TWO_MINUTES;
        boolean isSignificantlyOlder = timeDelta < -TWO_MINUTES;
        boolean isNewer = timeDelta > 0;

        // If it's been more than two minutes since the current location, use the new location
        // because the user has likely moved
        if (isSignificantlyNewer) {
            return true;
            // If the new location is more than two minutes older, it must be worse
        } else if (isSignificantlyOlder) {
            return false;
        }

        // Check whether the new location fix is more or less accurate
        int accuracyDelta = (int) (location.getAccuracy() - currentBestLocation.getAccuracy());
        boolean isLessAccurate = accuracyDelta > 0;
        boolean isMoreAccurate = accuracyDelta < 0;
        boolean isSignificantlyLessAccurate = accuracyDelta > 200;

        // Check if the old and new location are from the same provider
        boolean isFromSameProvider = isSameProvider(location.getProvider(),
                currentBestLocation.getProvider());

        // Determine location quality using a combination of timeliness and accuracy
        if (isMoreAccurate) {
            return true;
        } else if (isNewer && !isLessAccurate) {
            return true;
        } else if (isNewer && !isSignificantlyLessAccurate && isFromSameProvider) {
            return true;
        }
        return false;
    }

    /** Checks whether two providers are the same */
    private boolean isSameProvider(String provider1, String provider2) {
        if (provider1 == null) {
            return provider2 == null;
        }
        return provider1.equals(provider2);
    }

    @Override
    public void onDestroy() {
        // handler.removeCallbacks(sendUpdatesToUI);
        super.onDestroy();
        Log.v("STOP_SERVICE", "DONE");
        locationManager.removeUpdates(listener);
    }

    public static Thread performOnBackgroundThread(final Runnable runnable) {
        final Thread t = new Thread() {
            @Override
            public void run() {
                try {
                    runnable.run();
                } catch(Exception e) {
System.out.print(e);
                }
            }
        };
        t.start();
        return t;
    }

    public class MyLocationListener implements LocationListener
    {
        public void onLocationChanged(final Location loc)
        {
            Log.i("**************************************", "Location changed");
            if(isBetterLocation(loc, previousBestLocation)) {
                String newLocation = "Lat: " + loc.getLatitude() + " and Long: " + loc.getLongitude();
               i = new Intent("LOCATION_CHANGED");
                i.putExtra("location", newLocation);
                sendBroadcast(i);
            }
        }

        public void onProviderDisabled(String provider)
        {
            Toast.makeText( getApplicationContext(), "Gps Disabled", Toast.LENGTH_SHORT ).show();
        }


        public void onProviderEnabled(String provider)
        {
            Toast.makeText(getApplicationContext(), "Gps Enabled", Toast.LENGTH_SHORT).show();
        }

        public void onStatusChanged(String provider, int status, Bundle extras)
        {
        }
    }
}

我在MainActivity 收到了广播意图,如下:

public class MainActivity extends Activity {
    TextView txt_location;    

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        txt_location = (TextView)findViewById(R.id.current_location);

        if (savedInstanceState == null) {
            getFragmentManager().beginTransaction()
                    .add(R.id.container, new PlaceholderFragment()).commit();
        }
    }    

    public class LocationBroadcast extends BroadcastReceiver {
        @Override
        public void onReceive(Context ctx, Intent intent) {
            txt_location.setText(intent.getExtras().getString("location"));
        }
    }

    public static class PlaceholderFragment extends Fragment {
        public PlaceholderFragment() {
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {    
            return inflater.inflate(R.layout.fragment_main, container, false);
        }
    }
}

如您所见,它没有显示任何位置更新。 Logcat 没有显示任何错误。谁能指导我是什么错误?

【问题讨论】:

  • @Leo 嘿,它不是重复的...我看到过...我的问题不同。
  • 哎呀,你是对的。我不知道为什么我完全无视你说“持续”的部分
  • @Leo 好的..没问题:-)

标签: android android-intent android-service android-broadcast android-location


【解决方案1】:

MainActivity 中创建BroadcastReceiver

BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {

    @Override
    public void onReceive(Context appContext, Intent intent) {
        .......
        //get location from Service and create Method for set location on textview txt_location

    }
};

registerReceiver 中的onResume MainActivity

registerReceiver(broadcastReceiver, new IntentFilter(GET_LOCATION));

并在开始MainActivity时声明这一点

private static final String GET_LOCATION = "com.pkg.location";

并在您的服务中将您的位置作为广播传递

Intent intent = new Intent(GET_LOCATION);
intent.putExtra("location", "your_location_got_from_service");
sendBroadcast(intent);

别忘了unregisterReceiverMainActivity

@Override
protected void onPause() {
    super.onPause();
    unregisterReceiver(broadcastReceiver);
}

【讨论】:

  • 我应该删除扩展 BroadcastReciever 的 LocationBroadcast 类吗?
  • 私有静态最终字符串 GET_LOCATION = "com.pkg.location";看不懂这条线?你为什么把包命名为这个?
  • 只是一个例子,你可以改变它
  • 嗨..我刚刚更新了问题...它不起作用..请帮助我。
  • registerReceiver(broadcastReceiver, new IntentFilter(GET_LOCATION));
【解决方案2】:

您可以使用 BroadcastReceiver 接收您的 LOCATION_CHANGED 事件,并从其 onReceive 方法更新 TextView

在你的活动中:

TextView textView = (TextView) findViewById(R.id.location_text);  //global variable

registerReceiver(locationChangedReceiver, new IntentFilter("LOCATION_CHANGED"));

//your receiver class as inner class of activity.
private BroadcastReceiver locationChangedReceiver= new BroadcastReceiver() {

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

        textView.setText(intent.getExtras().getString("location"));

    }
};

在您的服务中,您可以简单地广播“LOCATION_CHANGED”,并将字符串位置作为意图的额外参数传递。

String newLocation = "Lat: " + loc.getLatitude() + " and Long: " + loc.getLongitude();
Intent i = new Intent("LOCATION_CHANGED");
i.putExtra("location", newLocation);
sendBroadcast(i);

如果您想保留一个单独的接收器类(不在活动中),您可以使用您的上下文来更新视图,如下所示:

public class LocationBroadcast extends BroadcastReceiver{
    @Override
    public void onReceive(Context ctx, Intent intent) {
        TextView textView = (TextView) ctx.findViewById(R.id.location_text);
        textView.setText(intent.getExtras().getString("location"));
    }

}

希望对你有帮助。

【讨论】:

  • 我在你的代码的最后一行出错了..at ctx.findViewById(R.id.location_text);显示 findViewById 无法解析
  • 嗨..先生你在吗?我刚刚更新了问题...它不起作用..请帮助我。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-06-26
  • 2017-09-19
相关资源
最近更新 更多