0

I know there are lots of codes related this! But I am still facing problem I googled many tutorials and documents, I am able to run service when i minimize the app! but its not responding when app is closed or terminated

Here is my code! this is my service class

public class MyService extends Service {

    final public static String ONE_TIME = "onetime";
    public static final String MyPREFERENCES = "MyPrefs";
    SharedPreferences sharedpreferences;

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

    @Override
    public void onStart(Intent intent, int startId) {
        // TODO Auto-generated method stub
        super.onStart(intent, startId);
        Toast.makeText(this, "ServiceClass.onStart()", Toast.LENGTH_LONG).show();
        Log.d("Testing", "Service got started");
    }

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


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


        sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);

        //I need to call this every say-10 second
        final String URL = "http://nrna.org.np/nrna_app/app_user/set_location/" + sharedpreferences.getString("Save_user_app_id", null) + "/np";
        // if (isNetworkAvailable() == true) {
        RequestQueue queue = Volley.newRequestQueue(MyService.this);

        StringRequest stringRequest = new StringRequest(Request.Method.GET, URL, null, null);
// Add the request to the RequestQueue.
        queue.add(stringRequest);

        // Let it continue running until it is stopped.
        Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
        return START_STICKY;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show();
    }

}

And I called this service from my main activity

// Method to start the service
    public void startService(Context context) {
        Intent intent = new Intent(MainActivity.this, MyService.class);
        PendingIntent pintent = PendingIntent.getService(MainActivity.this, 0, intent, 0);
        AlarmManager alarm = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
        alarm.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 10 * 1000, pintent);
        //startService(new Intent(getBaseContext(), MyService.class));
    }

my manifest file

 <service android:name=".MyService"/>

I need to run if the app is closed!!

UPDATE I Did used BroadCastReceiver! But not working again.

public class BaseNotificationManager extends BroadcastReceiver {


    public static final String BaseAction = "Com.TST.BaseAction";
    public static final String FireService = "Com.TST.FireNotificationAction";


    private  static  final long timeFrame =  1000*10;  // 5 mints

    public BaseNotificationManager() {
    }

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

        if (Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction())) {
            /// add base alarm manager
            startBaseAlarmManager(context);

        }else  if (BaseAction.equals(intent.getAction())){
            //  StartYourService();
            intent = new Intent(context,MyService.class);
            PendingIntent pintent = PendingIntent.getService(context, 0, intent, 0);
            AlarmManager alarm = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
            alarm.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 10 * 1000, pintent);

        }
    }       public  static  void startBaseAlarmManager (Context context){


        AlarmManager alarmMgr;
        PendingIntent alarmIntent;

        alarmMgr = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
        Intent intent = new Intent(context, BaseNotificationManager.class);
        intent.setAction(BaseAction);
        alarmIntent = PendingIntent.getBroadcast(context, 0, intent, 0);

        alarmMgr.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
                5000,  timeFrame, alarmIntent);

    }}
Ganesh Pandey
  • 5,216
  • 1
  • 33
  • 39
Tripathee Gaurav
  • 371
  • 3
  • 11

2 Answers2

2

Try

    public class MyService extends Service {
      @Override
        protected void onHandleIntent(Intent workIntent) {
            // Gets data from the incoming Intent
            String dataString = workIntent.getDataString();
            ...
            // Do work here, based on the contents of dataString
            ...
        }
}

Seems your app has GUI and you are using Service class. The main drawback here is

The Service runs in background but it runs on the Main Thread of the application.

The IntentService runs on a separate worker thread.

Ganesh Pandey
  • 5,216
  • 1
  • 33
  • 39
1

What you want to do is have some kind of loop running on a background thread in the service. Your code doesn't give any indication that you want the actions to be repeated. What you really want is something like the following (using C# syntax):

new Thread(obj =>
{
   while (true)
   {
      // Do actions that you want repeated (poll web site, etc.)

      // Sleep for awhile
      Thread.Sleep(10000);
    }
}

See also the below thread: Android Service Stops When App Is Closed

Incidentally, I might be misunderstanding your goals here, but could you also use push notifications (e.g. GCM) to accomplish the same thing here? (The reason I ask is that using GCM tends to be better from a power management perspective than repeatedly polling).

If you're curious, there's a good talk about conserving power and having your app be a "good citizen" in terms of battery life on the Android Developers Backstage podcast. I think you should be able to get it here: https://www.acast.com/androiddevelopersbackstage/episode-44-power-on

Edit: If you're uploading the result, you could do something like the following to post it to your web service (again using C#/Web API syntax but you could just as easily use Java with Web API or Node.js or whatever):

    public class Location
    {
        public double Latitude
        {
            get;
            set;
        }

        public double Longitude
        {
            get;
            set;
        }

        public Location(double latitude, double longitude)
        {
            this.Latitude = latitude;
            this.Longitude = longitude;
        }
    }

    // This call goes in your main thread
    private async void PostLocation(Location location)
    {
        using (var client = new HttpClient())
        {
            client.BaseAddress = new Uri("[your base address]");

            string json = JsonConvert.SerializeObject(location);
            HttpResponseMessage message = await client.PostAsync("controller/method", new StringContent(json));
        }
    }
Community
  • 1
  • 1