不工作的后台服务

时间:2013-12-26 09:11:54

标签: android

    public class MyService extends BackgroundService implements LocationListener {

        private final static String TAG = MyService.class.getSimpleName();

        private String mHelloTo = "World";
        private LocationManager locationManager;
        private String provider;
        Context context;

        String username;
        CommentsDataSource datasource;

        @Override
        public void onCreate() {

            context = getApplicationContext();
            datasource = new CommentsDataSource(context);
            datasource.open();
            mHelloTo = datasource.getComment_1();

        }
        @Override
        public void onDestroy() {
    //datasource.close();

        }



        protected JSONObject doWork() {

            locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
            Criteria criteria = new Criteria();


             int level=0;

            provider = locationManager.getBestProvider(criteria, false);
            Location location = locationManager.getLastKnownLocation(provider);
            Double latitude = location.getLatitude();
            Double longitude = location.getLongitude();
            if (location != null) {
            Log.i("Provider", provider + " has been selected.");
            onLocationChanged(location);
            }
            JSONObject result = new JSONObject();

            try {

                String msg = "Kasun " + mHelloTo + " - its currently "
                        + "3.456789";
                result.put("Message", msg);

                Log.d(TAG, msg);

            } catch (JSONException e) {
            }

            return result;
        }
public void onLocationChanged(Location location) {
        Double latitude = location.getLatitude();
        Double longitude = location.getLongitude();


        }

    }

在这里,我创建了获取当前GPS位置并显示的后台服务。但是当我尝试上面的代码时,我得到以下错误。但是当我在Android选项卡上尝试它时,它工作正常但是我在Huwavi选项卡上尝试它给出了愚蠢的错误。

12-26 14:41:04.651: I/BackgroundService(5356): Exception occurred during doWork()
12-26 14:41:04.651: I/BackgroundService(5356): java.lang.NullPointerException
12-26 14:41:04.651: I/BackgroundService(5356):  at org.apache.cordova.example.MyService.doWork(MyService.java:84)
12-26 14:41:04.651: I/BackgroundService(5356):  at com.red_folder.phonegap.plugin.backgroundservice.BackgroundService.doWorkWrapper(BackgroundService.java:390)

1 个答案:

答案 0 :(得分:0)

请使用此服务:

  

Gradle

implementation 'com.google.android.gms:play-services:12.0.1'
  

启动服务

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
     ContextCompat.startForegroundService(MainActivity.this, new Intent(MainActivity.this, ServiceLocation.class));
 } else {
     startService(new Intent(MainActivity.this, ServiceLocation.class));
 }
  

服务等级

public class ServiceLocation extends Service implements
        GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener,
        LocationListener {

    private static final String NOTIFICATION_CHANNEL_ID = "my_notification_location";
    private static final long TIME_INTERVAL_GET_LOCATION = 1000 * 5; // 1 Minute
    private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 7; // meters

    private Handler handlerSendLocation;
    private Context mContext;

    private GoogleApiClient mGoogleApiClient;
    private LocationRequest mLocationRequest;

    private final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 5000;

    Location locationData;

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

        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();

        // Create the LocationRequest object
        mLocationRequest = LocationRequest.create()
                .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
                .setInterval(TIME_INTERVAL_GET_LOCATION)    // 3 seconds, in milliseconds
                .setFastestInterval(TIME_INTERVAL_GET_LOCATION); // 1 second, in milliseconds

        mContext = this;


        NotificationCompat.Builder builder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID)
                .setOngoing(false)
                .setSmallIcon(R.drawable.ic_notification)
                .setColor(getResources().getColor(R.color.fontColorDarkGray))
                .setPriority(Notification.PRIORITY_MIN);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
            NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID,
                    NOTIFICATION_CHANNEL_ID, NotificationManager.IMPORTANCE_LOW);
            notificationChannel.setDescription(NOTIFICATION_CHANNEL_ID);
            notificationChannel.setSound(null, null);
            notificationManager.createNotificationChannel(notificationChannel);
            startForeground(1, builder.build());
        }
    }

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

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

        Log.w("Service Update Location", "BGS > Started");

        if (handlerSendLocation == null) {
            handlerSendLocation = new Handler();
            handlerSendLocation.post(runnableSendLocation);
            Log.w("Service Send Location", "BGS > handlerSendLocation Initialized");
        } else {
            Log.w("Service Send Location", "BGS > handlerSendLocation Already Initialized");
        }

        return START_STICKY;
    }

    private Runnable runnableSendLocation = new Runnable() {

        @Override
        public void run() {


            // You can get Location
            //locationData

            Log.w("==>UpdateLocation<==", "" + String.format("%.6f", locationData.getLatitude()) + "," +
            String.format("%.6f", locationData.getLongitude()));

            Log.w("Service Send Location", "BGS >> Location Updated");

            if (handlerSendLocation != null && runnableSendLocation != null)
                handlerSendLocation.postDelayed(runnableSendLocation, TIME_INTERVAL_GET_LOCATION);
        }
    };



    @Override
    public void onConnected(@Nullable Bundle bundle) {
        if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
                ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

            return;
        }
        Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);

        LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
    }

    @Override
    public void onConnectionSuspended(int i) {

    }

    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
        if (connectionResult.hasResolution() && mContext instanceof Activity) {
            try {
                Activity activity = (Activity) mContext;
                connectionResult.startResolutionForResult(activity, CONNECTION_FAILURE_RESOLUTION_REQUEST);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            Log.i("", "Location services connection failed with code " + connectionResult.getErrorCode());
        }
    }

    @Override
    public void onLocationChanged(Location location) {
        Log.w("==>UpdateLocation<==", "" + String.format("%.6f", location.getLatitude()) + "," + String.format("%.6f", location.getLongitude()));
        locationData = location;

    }

    @Override
    public void onDestroy() {

        if (handlerSendLocation != null)
            handlerSendLocation.removeCallbacks(runnableSendLocation);


        Log.w("Service Update Info", "BGS > Stopped");

        stopSelf();
        super.onDestroy();
    }

}
  

AndroidManifest.XML

<service
            android:name=".ServiceLocation"
            android:enabled="true"
            android:exported="true" />