2014-11-20 45 views
0

我想创建一个应用程序,当拍摄照片时给我GPS坐标。由于GPS需要准确,我将其作为服务运行以获得最佳锁定。但是,当主要活动打开时,startservice()onCreate()不会访问GPSClass中的onStartCommand。使用Android服务,在奇怪的时间访问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> 

回答

0

小号你不可以在清单中声明你的服务吗?

<application 

    . 
    . 
    . 

    <service 
     android:name=".MyService" 
     android:label="My Service" > 
    </service> 
</application> 
+0

对不起备份,我所做的仅仅是它没有打印部分,当我张贴的问题,我可以得到的服务工作,它只是工作在onCreate和onStart的所有调用都发生后 – emmistar 2014-11-20 23:24:20

+0

@emmistar为什么你在onCreate和onStart中都使用? – 2014-11-21 01:27:52

+0

如果活动重新启动以便它再次打开GPS,我正在使用onStart()。我可能会在赛道后面改变它。 – emmistar 2014-11-21 02:03:25