2014-01-24 86 views
0

我需要獲取位置更新形式onReceive方法。當onReceive()調用GPS開始2-3秒後,爲什麼?從BOOT_COMPLETED Receiver請求位置更新?

如何解決?我想獲取位置更新。請幫助。

注:的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> 
+1

,因爲廣播接收器是短暫的。改爲使用服務。 – njzk2

+0

thanx bro。這真的很有用:) – Yousif

回答

-1

當的的onReceive()調用GPS開始2-3秒後,爲什麼?

因爲您的過程已終止。

+0

好的。如何解決它? 請填寫您的答案 – Yousif

1

感謝名單球員的幫助,我只需要做出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>