我是android开发的新手。我需要在gps激活时启动服务。
这就是我到目前为止所做的:
服务:
public class MainService extends Service implements LocationListener {
private LocationManager locationManager;
Intent i;
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 30000, 1, this);
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onLocationChanged(Location location) {
String msg = "New Latitude: " + location.getLatitude()
+ "New Longitude: " + location.getLongitude();
Log.d("",msg);
}
@Override
public void onProviderDisabled(String provider) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
Log.i("", "------------------->GPS is off");
}
@Override
public void onProviderEnabled(String provider) {
Log.i("", "------------------->Gps is turned on!! ");
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
}
广播接收器:
public class GPSReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Log.d("", "Receiver is on");
if (intent.getAction().matches("android.location.PROVIDERS_CHANGED")) {
// react on GPS provider change action
Intent serviceIntent = new Intent(context, MainService.class);
context.startService(serviceIntent);
}
}
}
清单:
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<receiver
android:name="gr.dit.hua.it21370.gpsreciever.GPSReceiver"
android:enabled="true"
android:exported="false">
<intent-filter>
<action android:name="android.location.PROVIDERS_CHANGED" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</receiver>
<service
android:name="gr.dit.hua.it21370.gpsreciever.MainService"
android:process=":gps_service">
</service>
</application>
我已经尝试了,但我搜索了很多,但我没有设法解决它。 请帮帮我。
提前致谢:)