Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 5996313
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 23, 20262026-05-23T00:05:08+00:00 2026-05-23T00:05:08+00:00

I’m trying to implement a service to handle the communication with the server for

  • 0

I’m trying to implement a service to handle the communication with the server for the following code. I don’t know much about the design architecture for these.

Here is my service class

public class BgService extends Service {
    private static final String TAG = BgService.class.getSimpleName();
    private Timer timer;
    SendJsonRequest sjr;

    private TimerTask updateTask = new TimerTask(){
        @Override
        public void run(){
            try{
                SendJsonRequest sjr = new SendJsonRequest();
                sjr.carMake();
                Log.i(TAG, "LOOK AT ME");
            }
            catch(Exception e){
                Log.w(TAG,e);
            }
        }
    };
    @Override
    public IBinder onBind(Intent intent) {
        // TODO Auto-generated method stub
        return null;
    }
    @Override
    public void onCreate(){
        super.onCreate();
        Log.i(TAG, "Service creating");
        timer = new Timer("Server listening timer");
        timer.schedule(updateTask, 1000L, 60*1000L);
    }

    @Override
    public void onDestroy(){
        super.onDestroy();
        Log.i(TAG, "Service Destroying");
        timer.cancel();
        timer = null;
    }
}

Here is my SendJsonRequest class

public class SendJsonRequest{
         private static final String TAG = "SendJsonRequest";
         private static String URL = "xxxxxxxxx";
         private static String infoRec;

         public static void createJsonObj(String path, Map x){
             infoRec = CreateJsonRequest.jsonRequest(URL+path, x );
             System.out.println(infoRec);
         }
         public static void carMake(){
             String path = "/CarMake";
             Map<String, Object> z = new HashMap<String,Object>();
             z.put("Name", "Ford");
             z.put("Model", "Mustang");
             createJsonObj(path, z);
         }

        }

Here is my CreateJsonObject class

public class CreateJsonRequest {
    public static String jsonRequest(String URL, Map<String,Object> params){
        try{
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(URL);

            JSONObject holder = new JSONObject();

            for (Map.Entry<String, Object> m : params.entrySet()){
                try {
                    holder.put(m.getKey(), m.getValue());
                }
                catch (JSONException e) {
                    Log.e("Hmmmm", "JSONException : "+e);
                }
            }   
            StringEntity se;
            se = new StringEntity(holder.toString());

            httpPost.setEntity(se);
            httpPost.setHeader("Accept", "text/json");
            httpPost.setHeader("Content-type", "text/json");

            HttpResponse response = (HttpResponse) httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();

            if(entity != null){
                InputStream is = entity.getContent();
                Header contentEncoding = response.getFirstHeader("Content-Encoding");

                String result= convertToString(is);
                is.close();

                System.out.println(result);
                return result;

            }
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
        return null;
    }

Sorry for the massive amount of code. How I implemented my service is obviously not correct, I just have no clue where to start to get a service handling the json requests to the server. Thanks in advance.

To be more clear, this did work on a button click, now I’m trying to get it to all run in the background with the service. So I guess my question is what goes where in the service?

My activity successfully starts the service, the service would work and print “look at me” to the logcat every minute. Then I added the try{ sjr.carMake()} and it catches an exception.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-23T00:05:08+00:00Added an answer on May 23, 2026 at 12:05 am

    You can use a broadcast receiver. This is a way to have your code start at certain times indicated by Android OS – for example, you can have it start when Android finished booting up (this is where I run my services usually.

    The best way is to use the AlarmManager class, and tell your service how often to run.

    Tell us more about what you’re trying to do, and what the problem is, and we can give you a more concise answer…

    UPDATE:

    Have you created an entry in the manifest.xml file for the service?

    UPDATE
    Here is how I’m doing it in my application. This is your “hook” to the OS. It’s going to fire when it finishes booting (don’t forget to make in entry in the manifest for this!)

    public class TmBroadcastReceiver extends BroadcastReceiver {
     @Override
         public void onReceive(final Context context, final Intent bootintent) {
    
             try{
                 Log.i("Taskmotion-ROBOT", "Robot Broadcast signal received on Boot. Trying to start Alarm scheduler");
                  Intent mServiceIntent = new Intent(context, ServiceAlarm.class);
                  context.startService(mServiceIntent);
    
             }
             catch(Exception e)
             {
                Log.i("Taskmotion", "Failed to start service..."); 
    
             }
         }
    }
    

    This Broadcast receiver calls a service that implements the AlarmManager class. The alarm manager sets up a schedule to run my service at a specified interval. Note that the alarms are deleted when the phone is shut down – but then recreated again when process is repeated as the phone boots back up and runs the BroadcastReceiver again.

    public class ServiceAlarm extends Service {
     private PendingIntent mAlarmSender;
    
    
     @Override
     public void onCreate() {
    
         try{
             Log.i("Taskmotion-ROBOT", "Setting Service Alarm Step 1");
             mAlarmSender = PendingIntent.getService(this.getApplicationContext(),
                     0, new Intent(this.getApplicationContext(), BackgroundService.class), 0);
         }
         catch(Exception e)
         {
             Log.i("Taskmotion-ROBOT", "Problem at 1 :" + e.toString());
    
         }
    
         long firstTime = SystemClock.elapsedRealtime();
    
         Log.i("Taskmotion-ROBOT", "Setting Service Alarm Step 2");
         // Schedule the alarm!
         AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE);
         am.setRepeating(AlarmManager.ELAPSED_REALTIME,
                         firstTime, AlarmManager.INTERVAL_HOUR, mAlarmSender);
    
         this.stopSelf();
    
    
     }
    
    
    
    @Override
    public IBinder onBind(Intent arg0) {
        // TODO Auto-generated method stub
        return null;
    }
    
    
    }
    

    I haven’t refactored this code yet, it was my first go at it. I see now that I’m looking at it again that I could probably do the scheduling inside the BroadcastReceiver, but for the sake of getting you something that works, I’ll continue.

    As indicated by AlarmManager.INTERVAL_HOUR, my service will run once an hour. The service that I want to run is defined in the pendingIntent (BackgroundService.class). This is where you put your own service class.
    I reworked your service class for you, and removed the timer (functionality replaced by the BroadcastReceiver & AlarmManager).

    public class BgService extends Service {
        private static final String TAG = BgService.class.getSimpleName();
        SendJsonRequest sjr;
    
    
        @Override
        public IBinder onBind(Intent intent) {
            // TODO Auto-generated method stub
            return null;
        }
        @Override
        public void onCreate(){
            super.onCreate();
            Log.i(TAG, "Service creating");
    
    
    //DO YOUR WORK WITH YOUR JSON CLASS HERE
    //**************************************
    
    //Make sure to call stopSelf() or your service will run in the background, chewing up
    //battery life like rocky mountain oysters!
    this.stopSelf();
    
    
        }
    
        @Override
        public void onDestroy(){
            super.onDestroy();
        }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I ran into a problem. Wrote the following code snippet: teksti = teksti.Trim() teksti
I am trying to understand how to use SyndicationItem to display feed which is
Basically, what I'm trying to create is a page of div tags, each has
link Im having trouble converting the html entites into html characters, (&# 8217;) i
That's pretty much it. I'm using Nokogiri to scrape a web page what has
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
I am reading a book about Javascript and jQuery and using one of the
I'm using v2.0 of ClassTextile.php, with the following call: $testimonial_text = $textile->TextileRestricted($_POST['testimonial']); ... and
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
I have this code: - (void)parser:(NSXMLParser *)parser foundCDATA:(NSData *)CDATABlock { NSString *someString = [[NSString

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.