应用程序被杀后如何重新启动服务

时间:2018-03-15 06:56:32

标签: android service location broadcastreceiver

我必须从位置管理器获取位置更新。如果app被杀,我希望服务仍然继续。 我有以下服务类。我正在使用广播接收器。在onTaskRemove()方法中,我发送广播。在接收器类我重新启动服务,但没有重新启动。请帮忙。谢谢。

 public class GoogleService extends Service implements LocationListener{

            boolean isGPSEnable = false;
            boolean isNetworkEnable = false;
            double latitude,longitude;
            LocationManager locationManager;
            Location location;
            private Handler mHandler = new Handler();
            private Timer mTimer = null;
            long notify_interval = 1000;
            public static String str_receiver = "servicetutorial.service.receiver";
            Intent intent;




            public GoogleService() {

            }

            @Override
            public IBinder onBind(Intent intent) {
                return null;
            }

            @Override
            public void onCreate() {
                super.onCreate();

                mTimer = new Timer();
                mTimer.schedule(new TimerTaskToGetLocation(),5,notify_interval);
                intent = new Intent(str_receiver);
                fn_getlocation();

            }

            @Override
            public void onLocationChanged(Location location) {

            }

            @Override
            public void onStatusChanged(String provider, int status, Bundle extras) {

            }

            @Override
            public void onProviderEnabled(String provider) {

            }

            @Override
            public void onProviderDisabled(String provider) {

            }

            @Override
            public void onDestroy() {
                super.onDestroy();
                sendBroadcast(new Intent("ChangeStatus"));
            }

            @Override
            public void onTaskRemoved(Intent rootIntent) {
                /*rootIntent = new Intent("ChangeStatus");
                rootIntent.putExtra("action", "statusChange");
                sendBroadcast(rootIntent);*/
                super.onTaskRemoved(rootIntent);
                sendBroadcast(new Intent("ChangeStatus"));

            }



            @SuppressLint("MissingPermission")
            private void fn_getlocation(){
                locationManager = (LocationManager)getApplicationContext().getSystemService(LOCATION_SERVICE);
                isGPSEnable = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
                isNetworkEnable = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

                if (!isGPSEnable && !isNetworkEnable){

                }else {

                    if (isNetworkEnable){
                        location = null;
                        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,1000,0,this);
                        if (locationManager!=null){
                            location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                            if (location!=null){

                                Log.e("latitude",location.getLatitude()+"");
                                Log.e("longitude",location.getLongitude()+"");

                                latitude = location.getLatitude();
                                longitude = location.getLongitude();
                                fn_update(location);
                            }
                        }

                    }


                    if (isGPSEnable){
                        location = null;
                        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,1000,0,this);
                        if (locationManager!=null){
                            location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                            if (location!=null){
                                Log.e("latitude",location.getLatitude()+"");
                                Log.e("longitude",location.getLongitude()+"");
                                latitude = location.getLatitude();
                                longitude = location.getLongitude();
                                fn_update(location);
                            }
                        }
                    }


                }

            }
            @Override
            public int onStartCommand(Intent intent, int flags, int startId) {
                Log.i("LocalService", "Received start id " + startId + ": " + intent);
                // We want this service to continue running until it is explicitly
                // stopped, so return sticky.
                return START_STICKY;
            }
            private class TimerTaskToGetLocation extends TimerTask{
                @Override
                public void run() {

                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            fn_getlocation();
                        }
                    });

                }
            }

            private void fn_update(Location location){

                intent.putExtra("latutide",location.getLatitude()+"");
                intent.putExtra("longitude",location.getLongitude()+"");
                sendBroadcast(intent);
            }


        }

**my Reciver class is**

    public class RestartServiceReceiver extends BroadcastReceiver
    {

        @Override
        public void onReceive(Context context, Intent intent) {
            context.startService(new Intent(context.getApplicationContext(), GoogleService.class));
        }

    }

我的清单

<service android:name=".GoogleService"
            android:enabled="true"
            android:exported="true"
            android:stopWithTask="false"
            ></service>
        <receiver android:name=".RestartServiceReceiver" >
            <intent-filter>
                <action android:name="ChangeStatus" >
                </action>
            </intent-filter>
        </receiver>

我做错了什么。

1 个答案:

答案 0 :(得分:0)

使用Pending Intent使用上面的android 7.0服务获取LocationUpdates使用你必须使用广播接收器:

@Override
public int onStartCommand(Intent intent, int flags, int startId) {

    if (intent != null) {
        final String action = intent.getAction();
        if (ACTION_PROCESS_UPDATES.equals(action)) {
            LocationResult result = LocationResult.extractResult(intent);
            if (result != null) {
                List<Location> locations = result.getLocations();

                Log.d("servicelocation","*******lastupdate     "+result.getLastLocation());
                Log.d("servicelocation","*******     "+locations.size()+
                "\n"+locations.get(locations.size()-1).getLatitude() +"    " +
                        "lng    "+locations.get(locations.size()-1).getLongitude());
                Toast.makeText(getApplicationContext(),"Service Stared  "+locations.size(),Toast.LENGTH_SHORT).show();

            }
        }
    }else {
        Log.d("serviceintentvalues","********");
    }

    return START_STICKY;
}

这里给出的完整参考是谷歌样本:https://github.com/googlesamples/android-play-location

它对我来说效果很好...