我实际上正在开发一个允许父母跟踪他的孩子的Android应用程序。我面临的问题是GPS位置需要每N秒执行一次,但每当我强行关闭应用程序,或重启移动设备时服务都不会重启。
这是我的LocationService:
public class LocationService extends Service
{
private LocationListener listener;
private LocationManager manager;
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate()
{
super.onCreate();
Toast.makeText(this, "Service.onCreate()", Toast.LENGTH_LONG).show();
}
@Override
public void onDestroy()
{
super.onDestroy();
Toast.makeText(this, "Service.destroy()", Toast.LENGTH_LONG).show();
if(this.manager != null)
//noinspection MissingPermission
this.manager.removeUpdates(this.listener);
}
@Override
public int onStartCommand(Intent intent, int flag, int startId)
{
super.onStartCommand(intent, flag, startId);
//Here end the code to execute
Toast.makeText(this, "Service.onStartCommand()",Toast.LENGTH_LONG).show();
this.listener = new LocationListener() {
@Override
public void onLocationChanged(Location location) {
Log.e("started", "service running");
play();
Toast.makeText(LocationService.this, location.getLongitude() + " " + location.getLatitude(), Toast.LENGTH_SHORT).show();
}
@Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
@Override
public void onProviderEnabled(String s) {
}
@Override
public void onProviderDisabled(String s) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
};
this.manager = (LocationManager)getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
//noinspection MissingPermission
this.manager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 3000,0, this.listener);
return START_NOT_STICKY;
}
@Override
public boolean onUnbind(Intent intent)
{
// TODO Auto-generated method stub
Toast.makeText(this, "Service.onUnbind()", Toast.LENGTH_LONG).show();
return super.onUnbind(intent);
}
}
我的广播接收器:
public class BootIntentReceiver extends BroadcastReceiver
{
@Override
public void onReceive(Context context, Intent intent)
{
Intent serviceIntent = new Intent(context, LocationService.class);
serviceIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startService(serviceIntent);
}
}
我的Manifest.xml:
<receiver android:name=".activity.service.BootIntentReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
<service
android:name=".activity.service.LocationService"
android:exported="false" />
启动权限:
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
每当我启动设备时都没有任何反应:/
感谢您的帮助!
答案 0 :(得分:1)
您是否尝试在清单中使用完全限定的服务名称?
e.g。如果服务在包com.package.activity.service
中,请使用<receiver android:name="com.package.activity.service.BootIntentReceiver">
而不是<receiver android:name=".activity.service.BootIntentReceiver">
在你的BootIntentReceiver
中添加日志或Toast,只是为了加倍确定