从BOOT_COMPLETED Receiver请求位置更新?

时间:2014-01-24 16:55:45

标签: android gps broadcastreceiver bootcompleted

我需要从onReceive方法获取位置更新。当onReceive()调用GPS开始2-3秒后就消失了,为什么??

如何解决?我想获得位置更新。求助。

注意:重新启动手机时会调用onReceive方法

java代码:

public class BootReceiver extends BroadcastReceiver implements LocationListener {

@Override
public void onReceive(Context context, Intent intent) {
    // TODO Auto-generated method stub


    if (Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction()))
 {
    LocationManager LM2=(LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
    LM2.requestLocationUpdates("gps",5000, 0, this);
 }

}

@Override
public void onLocationChanged(Location location) {
    // TODO Auto-generated method stub

}

@Override
public void onProviderDisabled(String provider) {
    // TODO Auto-generated method stub

}

@Override
public void onProviderEnabled(String provider) {
    // TODO Auto-generated method stub

}

@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
    // TODO Auto-generated method stub

}

}

的Manifest.xml

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>

<receiver android:name="com.my.package.BootReceiver">
       <intent-filter>
    <action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>

2 个答案:

答案 0 :(得分:2)

Thanx伙伴们为您提供了帮助,我只需要制作一个Service

onReceive方法将是

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

   if (Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction()))
  {
     Intent i= new Intent(context, MyService.class);            
     context.startService(i);
  }

}

MyService类

public class MyService extends Service implements LocationListener {


     @Override
public IBinder onBind(Intent intent) {
    // TODO Auto-generated method stub
    return null;
}

      @Override
  public int onStartCommand(Intent intent, int flags, int startId) {
    //TODO do something useful
    LocationManager LM2=(LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
    LM2.requestLocationUpdates("gps",5000, 0, this);
    return Service.START_STICKY;
  }


    @Override
 public void onLocationChanged(Location location) {
// TODO Auto-generated method stub

}

@Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub

}

 @Override
 public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub

 }

 @Override
  public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub

}

}

我需要在manifest.xml中注册我的服务

<service
 android:name="com.my.package.MyService"
 android:icon="@drawable/icon"
 android:label="Service name"
 >
 </service>

答案 1 :(得分:-1)

  

当onReceive()调用GPS开始2-3秒后,为什么?

因为您的流程已终止。