Skip to content Skip to sidebar Skip to footer

Cant Run Background Service

I am trying to use LocationListener class in a background service to receive the current location of user every time and then comparing it with some data stored in my database. but

Solution 1:

The LogCat states:

Caused by: java.lang.NullPointerException
    at android.content.ContextWrapper.getSystemService(ContextWrapper.java:416)
    at com.example.alert.service.<init>(service.java:15)

Simply wait for the Context to be initialized by moving this code into onCreate():

publicclassserviceextendsService {
    LocationManager lm;

    @OverridepublicvoidonCreate() {
        // This line needs an existing context
        lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        Toast.makeText(this, "Background Service Created", Toast.LENGTH_LONG).show();
    }

    // etc

Solution 2:

Make sure that you have added service to the AndroidManifest file

A Service is an application component representing either an application's desire to perform a longer-running operation while not interacting with the user or to supply functionality for other applications to use. Each service class must have a corresponding declaration in its package's AndroidManifest.xml. Services can be started with Context.startService() and Context.bindService().

Solution 3:

Use this code my friend and make changes according to your need

publicclassMainActivityextendsActivity {
    Button btnStart, btnStop;
    publicstaticContext mContext;
    Intent it;
    publicLocationManager manager;
    publicboolean isGPSEnabled = false;
    boolean isNetworkEnabled = false;

    @OverrideprotectedvoidonCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mContext = this;
        manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        isGPSEnabled = manager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        // getting network status
        isNetworkEnabled = manager
                .isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        btnStart = (Button) findViewById(R.id.btnStart);
        btnStop = (Button) findViewById(R.id.btnStop);
        btnStart.setOnClickListener(newView.OnClickListener() {

            @OverridepublicvoidonClick(View v) {
                // TODO Auto-generated method stub/*if (isGPSEnabled) {
                    startService(getIntent());
                }
                else
                {
                    Toast.makeText(MainActivity.this, "Please oN Gps ",
                            Toast.LENGTH_LONG).show();
                }*/startService(getIntent());
            }
        });
        btnStop.setOnClickListener(newView.OnClickListener() {

            @OverridepublicvoidonClick(View v) {
                // TODO Auto-generated method stubstopService(getIntent());
            }
        });
    } // on create ends@OverridepublicbooleanonCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.getMenuInflater().inflate(R.menu.main, menu);
        returntrue;
    }

    publicIntentgetIntent() {
        it = newIntent(mContext, MyService.class);
        return it;
    } // method endspublicstaticContextgetContextForService() {
        return mContext;
    } // methods ends
} // final class ends

Here is Your service for Location

publicclassMyServiceextendsService {
    // flag for GPS statuspublicstatic LocationManager manager;
    publicstaticbooleanisGPSEnabled=false;
    publicstaticdoublelattitude=0;
    publicstaticdoublelongitude=0;
    intcount=0;
    // flag for network statusbooleanisNetworkEnabled=false;

    // flag for GPS statusbooleancanGetLocation=false;
    MyFile myFile;

    @Overridepublic IBinder onBind(Intent intent) {
        // TODO Auto-generated method stubreturnnull;
    } // method ends@OverridepublicintonStartCommand(Intent intent, int flags, int startId) {

        super.onStartCommand(intent, flags, startId);
        System.out.println("On Start Command is called ");
        return START_STICKY;
    } // method ends@OverridepublicvoidonCreate() {
        // TODO Auto-generated method stubsuper.onCreate();
        System.out.println("Service is created//////////// ");
        // start asyntask to get locationsnewGetLocations().execute();
    }// on create ends@OverridepublicvoidonDestroy() {
        // TODO Auto-generated method stubsuper.onDestroy();
        System.out.println("Service is  Destroyed  //////////// ");
        if (manager != null && isGPSEnabled == true) {
            manager.removeUpdates(mylistener);
            System.out.println("Service is  Destroyed under if //////////// ");
        }

    } // method endspublicclassGetLocationsextendsAsyncTask<Void, Void, Void> {

        @OverrideprotectedvoidonPreExecute() {
            // TODO Auto-generated method stubsuper.onPreExecute();
            manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
            // getting GPS status
            isGPSEnabled = manager
                    .isProviderEnabled(LocationManager.GPS_PROVIDER);
            // getting network status
            isNetworkEnabled = manager
                    .isProviderEnabled(LocationManager.NETWORK_PROVIDER);
            if (isGPSEnabled) {
                /*
                 * Criteria criteria = new Criteria(); String bestProvider =
                 * manager.getBestProvider(criteria, false); Location location =
                 * manager.getLastKnownLocation(bestProvider); double lat
                 * =location.getLatitude(); double longi
                 * =location.getLongitude();
                 * System.out.println("getting location continous ////// Lattti "
                 * +location.getLatitude() );
                 * System.out.println("getting location continous ////// LONGITU "
                 * + location.getLongitude());
                 */
                manager.requestLocationUpdates(
                        LocationManager.NETWORK_PROVIDER, 3000, 0, mylistener);

            } else {
                Toast.makeText(MyService.this, "Please oN Gps ",
                        Toast.LENGTH_LONG).show();
            }
        }

        @Overrideprotected Void doInBackground(Void... params) {
            // TODO Auto-generated method stub// getting current lattitude and longitudereturnnull;
        }// method ends
    }// asyntask class endsvoidhandleLocationChanged(Location loc) {
        lattitude = loc.getLatitude();
        longitude = loc.getLongitude();
        /*Toast.makeText(MyService.this,
                "lat is " + lattitude + " long is  " + longitude,
                Toast.LENGTH_LONG).show();*/
        System.out.println("getting location continous ////// Lattti "
                + lattitude);
        System.out.println("getting location continous ////// LONGITU "
                + longitude);

        generateNoteOnSD("GpsTesting.txt", "lattitude is" + lattitude + "\n"
                + " longitude" + longitude);

    } // method endspublicLocationListenermylistener=newLocationListener() {

        @OverridepublicvoidonLocationChanged(Location loc) {
            handleLocationChanged(loc);
        }

        publicvoidonProviderDisabled(String arg0) {
            // TODO Auto-generated method stub// Toast.makeText(mContext, "Gps is disable",// Toast.LENGTH_SHORT).show();
        }

        publicvoidonProviderEnabled(String arg0) {
            // TODO Auto-generated method stub// Toast.makeText(mContext, "Gps is on", Toast.LENGTH_SHORT).show();
        }

        publicvoidonStatusChanged(String arg0, int arg1, Bundle arg2) {
            // TODO Auto-generated method stub// Toast.makeText(appcontext, "Gps  status is chnged ",// Toast.LENGTH_SHORT).show();
        }
    };

    publicvoidshowSettingsAlert() {
        AlertDialog.BuilderalertDialog=newAlertDialog.Builder(
                MainActivity.getContextForService());

        // Setting Dialog Title
        alertDialog.setTitle("Alert");

        // Setting Dialog Message
        alertDialog
                .setMessage("GPS is not enabled. Do you want to go to settings menu?");

        // On pressing Settings button
        alertDialog.setPositiveButton("Settings",
                newDialogInterface.OnClickListener() {
                    publicvoidonClick(DialogInterface dialog, int which) {
                        Intentintent=newIntent(
                                Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                        getApplicationContext().startActivity(intent);
                    }
                });

        // on pressing cancel button
        alertDialog.setNegativeButton("Cancel",
                newDialogInterface.OnClickListener() {
                    publicvoidonClick(DialogInterface dialog, int which) {
                        dialog.cancel();
                    }
                });

        // Showing Alert Message
        alertDialog.show();
    }// method ends// method for sending notiifcationpublicvoidsendNotification() {
        intMY_NOTIFICATION_ID=1;
        PendingIntentcontentIntent= PendingIntent.getActivity(
                getApplicationContext(), 0, newIntent(MyService.this,
                        MainActivity.class), 0);
        NotificationmyNotification=newNotificationCompat.Builder(
                getApplicationContext())
                .setContentTitle("Notification for Lat and Long")
                .setContentText("hi testing notiifaction on lat and long")
                .setTicker(" ToDoList Notification")
                .setWhen(System.currentTimeMillis())
                .setContentIntent(contentIntent)
                .setDefaults(Notification.DEFAULT_SOUND).setAutoCancel(true)
                .setSmallIcon(R.drawable.ic_launcher).build();
        NotificationManagernotificationManager= (NotificationManager) MainActivity
                .getContextForService().getSystemService(
                        Context.NOTIFICATION_SERVICE);
        notificationManager.notify(MY_NOTIFICATION_ID, myNotification);
    } // method ends// writing file onpublicvoidgenerateNoteOnSD(String sFileName, String sBody) {
        try {
            Fileroot=newFile(Environment.getExternalStorageDirectory()
                    + "/sdcard", "Gps_Data");
            if (!root.exists()) {
                root.mkdirs();
            }
            Filegpxfile=newFile(root, sFileName);
            FileWriterwriter=newFileWriter(gpxfile);
            writer.append(sBody);
            writer.flush();
            writer.close();

        } catch (IOException e) {
            e.printStackTrace();

        }
    } // method endsprivatebooleanhaveNetworkConnection() {
        booleanhaveConnectedWifi=false;
        booleanhaveConnectedMobile=false;

        ConnectivityManagercm= (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo[] netInfo = cm.getAllNetworkInfo();
        for (NetworkInfo ni : netInfo) {
            if (ni.getTypeName().equalsIgnoreCase("WIFI"))
                if (ni.isConnected())
                    haveConnectedWifi = true;
            if (ni.getTypeName().equalsIgnoreCase("MOBILE"))
                if (ni.isConnected())
                    haveConnectedMobile = true;
        }
        return haveConnectedWifi || haveConnectedMobile;
    }
} // final class ends

Post a Comment for "Cant Run Background Service"