【发布时间】:2014-11-20 23:13:25
【问题描述】:
我正在尝试创建一个应用程序,该应用程序可以在拍摄照片时为我提供 GPS 坐标。因为 GPS 需要准确,所以我将其作为服务运行以获得最佳锁定。但是,当打开主要活动时,onCreate() 中的startservice() 不会访问 GPSClass 中的 onStartCommand。
它运行onStart(),然后由于某种原因在完成两个启动过程后触发访问该类。
为什么会这样?这似乎太不合逻辑了。顺便说一句,我一直在尝试使用调试。
主要活动启动代码
public class MainActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent GPSstart = new Intent(this, GPSClass.class);
this.startService(GPSstart);
}
private void GPSrunner() {
Intent GPSstart = new Intent(this, GPSClass.class);
this.startService(GPSstart);
// check GPS is onstart
if (!GPSClass.isGPSon()) {
buildAlertMessageNoGps();
}
}
@Override
protected void onStart() {
super.onStart();
GPSrunner();
}
服务代码
public class GPSClass extends Service implements LocationListener {
private static final int TWO_MINUTES = 1000 * 60 * 2;
private static LocationManager locationManager;
private static boolean GPSOn;
private static Location location;
@Override
public int onStartCommand(final Intent intent, final int flags, final int startId) {
locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
GPSOn = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
Toast.makeText(getApplicationContext(),"Service started",Toast.LENGTH_SHORT).show();
return START_STICKY;
}
@ Override
public void onDestroy() {
locationManager.removeUpdates(this);
public static boolean isGPSon() {
return GPSOn;
}
清单
<service android:name=".GPSClass"
android:exported="false"
/>
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
【问题讨论】: