How to invoke an activity from a service?


Last Updated:

  1. learning_intern

    learning_intern Member This Topic's Starter

    Joined:
    Jul 28, 2010
    Messages:
    15
    Likes Received:
    0
    hi
    I am trying to run a service that does my REST operations. i would like it to start as soon as my app starts and grab the records from the backend server and display them as a ListView inside a Tab Layout.

    I found a post that asks more or less the same question of invoking an activity from a service, but there were no good replies, rather no one replied to it except the guy who asked the question, so i had to re-post it!

    Right now i have an activity which basically has 3 buttons. first one is to create and start my service, second one is to stop it and the 3rd one is to display the records i get from my backend server through my service in a ListView inside a Tab Layout.

    the part that i have been able to achieve is -
    1. i was able to create the buttons and write their onclick listeners, so that they do the appropriate job that they are supposed to do

    2. i was able to write a service that does a simple get and post and gets me the records from the backend server as a JSON document. i know it works because in my php script (that is resting on the server side) that returns me the JSON document, i also made a provision to write that Document in a text file so that i know that my GET/POST are working.

    THE ISSUE that i am facing is that i am not able to find a way through which i could display my JSON document as a ListView inside a Tab layout .

    And also where in my app should i be inserting those retrieved records in my SQLite3 database (in the service or in a separate activity) ( i have a DbAdapter file to help me with).

    i would also provide my code -

    Code (Text):
    1.  
    2. package com.example;
    3.  
    4. import android.app.Activity;
    5. import android.content.Intent;
    6. import android.os.Bundle;
    7. import android.util.Log;
    8. import android.view.View;
    9. import android.view.View.OnClickListener;
    10. import android.widget.Button;
    11.  
    12. public class ServicesDemo extends Activity implements OnClickListener {
    13.   private static final String TAG = "ServicesDemo";
    14.   Button buttonStart, buttonStop, buttonShow;
    15.  
    16.   @Override
    17.   public void onCreate(Bundle savedInstanceState) {
    18.     super.onCreate(savedInstanceState);
    19.     setContentView(R.layout.main);
    20.  
    21.     buttonStart = (Button) findViewById(R.id.buttonStart);
    22.     buttonStop = (Button) findViewById(R.id.buttonStop);
    23.     buttonShow = (Button) findViewById(R.id.buttonShow);
    24.  
    25.     buttonStart.setOnClickListener(this);
    26.     buttonStop.setOnClickListener(this);
    27.     buttonShow.setOnClickListener(this);
    28.   }
    29.  
    30.   public void onClick(View src) {
    31.     switch (src.getId()) {
    32.     case R.id.buttonStart:
    33.       Log.d(TAG, "onClick: starting service");
    34.       startService(new Intent(this, MyService2.class));
    35.       break;
    36.     case R.id.buttonStop:
    37.       Log.d(TAG, "onClick: stopping service");
    38.       stopService(new Intent(this, MyService2.class));
    39.       break;
    40.     case R.id.buttonShow:
    41.         Log.d(TAG, "onClick: showing records");
    42.         startActivity(new Intent(this, ProjectsActivity.class));
    43.         break;
    44.     }
    45.   }
    46. }
    47.  
    and for my service class -

    Code (Text):
    1.  
    2. package com.example;
    3.  
    4. import java.io.BufferedReader;
    5. import java.io.IOException;
    6. import java.io.InputStream;
    7. import java.io.InputStreamReader;
    8. import java.util.ArrayList;
    9.  
    10. import org.apache.http.HttpEntity;
    11. import org.apache.http.HttpResponse;
    12. import org.apache.http.NameValuePair;
    13. import org.apache.http.client.ClientProtocolException;
    14. import org.apache.http.client.HttpClient;
    15. import org.apache.http.client.entity.UrlEncodedFormEntity;
    16. import org.apache.http.client.methods.HttpGet;
    17. import org.apache.http.client.methods.HttpPost;
    18. import org.apache.http.client.methods.HttpUriRequest;
    19. import org.apache.http.impl.client.DefaultHttpClient;
    20. import org.apache.http.message.BasicNameValuePair;
    21. import org.apache.http.protocol.HTTP;
    22.  
    23. import android.app.Service;
    24. import android.content.Intent;
    25. import android.os.IBinder;
    26. import android.util.Log;
    27. import android.widget.Toast;
    28.  
    29. public class MyService2 extends Service {
    30.     private static final String TAG = "MyService";
    31.    
    32.     private ArrayList <NameValuePair> params;
    33.     private ArrayList <NameValuePair> headers;
    34.  
    35.     private String url;
    36.  
    37.     private int responseCode;
    38.     private String message;
    39.  
    40.     private String response;
    41.    
    42.     public enum RequestMethod
    43.     {
    44.     GET,
    45.     POST
    46.     }
    47.  
    48.     public String getResponse() {
    49.         return response;
    50.     }
    51.  
    52.     public String getErrorMessage() {
    53.         return message;
    54.     }
    55.  
    56.     public int getResponseCode() {
    57.         return responseCode;
    58.     }
    59.  
    60.     public void SetURL(String url)
    61.     {
    62.         this.url = url;
    63.         params = new ArrayList<NameValuePair>();
    64.         headers = new ArrayList<NameValuePair>();
    65.     }
    66.  
    67.     public void AddParam(String name, String value)
    68.     {
    69.         params.add(new BasicNameValuePair(name, value));
    70.     }
    71.  
    72.     public void AddHeader(String name, String value)
    73.     {
    74.         headers.add(new BasicNameValuePair(name, value));
    75.     }
    76.  
    77.    
    78.     @Override
    79.     public IBinder onBind(Intent intent) {
    80.         return null;
    81.     }
    82.     /*----------------------------------------------------------------------------*/
    83.     @Override
    84.     public void onCreate() {
    85.         Toast.makeText(this, "My Service Created", Toast.LENGTH_LONG).show();
    86.         Log.d(TAG, "onCreate");
    87.        
    88.         SetURL("http://192.148.1.1/testhttpphp.php");
    89.         AddParam("task_id","20");
    90.    
    91.     }
    92.    
    93.  
    94.     @Override
    95.     public void onDestroy() {
    96.         Toast.makeText(this, "My Service Stopped", Toast.LENGTH_LONG).show();
    97.         Log.d(TAG, "onDestroy");
    98.    
    99.     }
    100.    
    101.     @Override
    102.     public void onStart(Intent intent, int startid) {
    103.         Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG).show();
    104.         Log.d(TAG, "onStart");
    105.        
    106.         try {
    107.             Execute(RequestMethod.POST);
    108.         } catch (Exception e) {
    109.             // TODO Auto-generated catch block
    110.             Log.e(TAG, "error is = "+ e.toString());
    111.         }
    112.    
    113.     }
    114.    
    115.     /*----------------------------------------------------------------------------*/
    116.    
    117.      public void Execute(RequestMethod post) throws Exception
    118.         {
    119.             switch(post) {
    120.                 case GET:
    121.                 {
    122.                     //add parameters
    123.                     String combinedParams = "";
    124.                     if(!params.isEmpty()){
    125.                         combinedParams += "?";
    126.                         for(NameValuePair p : params)
    127.                         {
    128.                             String paramString = p.getName() + "=" + p.getValue();
    129.                             if(combinedParams.length() > 1)
    130.                             {
    131.                                 combinedParams  +=  "&" + paramString;
    132.                             }
    133.                             else
    134.                             {
    135.                                 combinedParams += paramString;
    136.                             }
    137.                         }
    138.                     }
    139.      
    140.                     HttpGet request = new HttpGet(url + combinedParams);
    141.      
    142.                     //add headers
    143.                     for(NameValuePair h : headers)
    144.                     {
    145.                         request.addHeader(h.getName(), h.getValue());
    146.                     }
    147.      
    148.                     executeRequest(request, url);
    149.                     break;
    150.                 }
    151.                 case POST:
    152.                 {
    153.                     HttpPost request = new HttpPost(url);
    154.      
    155.                     //add headers
    156.                  /*   for(NameValuePair h : headers)
    157.                     {
    158.                         request.addHeader(h.getName(), h.getValue());
    159.                     }*/
    160.      
    161.                     if(!params.isEmpty()){
    162.                         request.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
    163.                     }
    164.      
    165.                     executeRequest(request, url);
    166.                     break;
    167.                 }
    168.             }
    169.         }
    170.      
    171.         private void executeRequest(HttpUriRequest request, String url)
    172.         {
    173.             HttpClient client = new DefaultHttpClient();
    174.      
    175.             HttpResponse httpResponse;
    176.      
    177.             try {
    178.                 httpResponse = client.execute(request);
    179.                 responseCode = httpResponse.getStatusLine().getStatusCode();
    180.                 message = httpResponse.getStatusLine().getReasonPhrase();
    181.      
    182.                 HttpEntity entity = httpResponse.getEntity();
    183.      
    184.                 if (entity != null) {
    185.      
    186.                     InputStream instream = entity.getContent();
    187.                     response = convertStreamToString(instream);
    188.      
    189.                     // Closing the input stream will trigger connection release
    190.                     instream.close();
    191.                 }
    192.      
    193.             } catch (ClientProtocolException e)  {
    194.                 client.getConnectionManager().shutdown();
    195.                 e.printStackTrace();
    196.             } catch (IOException e) {
    197.                 client.getConnectionManager().shutdown();
    198.                 e.printStackTrace();
    199.             }
    200.         }
    201.      
    202.         private static String convertStreamToString(InputStream is) {
    203.      
    204.             BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    205.             StringBuilder sb = new StringBuilder();
    206.      
    207.             String line = null;
    208.             try {
    209.                 while ((line = reader.readLine()) != null) {
    210.                     sb.append(line + "\n");
    211.                 }
    212.             } catch (IOException e) {
    213.                 e.printStackTrace();
    214.             } finally {
    215.                 try {
    216.                     is.close();
    217.                 } catch (IOException e) {
    218.                     e.printStackTrace();
    219.                 }
    220.             }
    221.             return sb.toString();
    222.         }
    223.    
    224.    
    225. }
    226.  
    ProjectsActivity is an activity class where i would like to display the JSON document that i receive.

    Thanks in advance!
     

    Advertisement
  2. blundell

    blundell Well-Known Member

    Joined:
    Apr 23, 2010
    Messages:
    125
    Likes Received:
    17
    Hmm your post confused me, so I'll just answer your title:

    Code (Text):
    1.  
    2. // do this in onStart() of your service
    3. // Add onclick listener
    4.                 final Intent startApp = new Intent(getApplicationContext(), MainActivity.class);
    5.                 startApp.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    6.         final PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), 0, startApp, 0);      
    7.         remoteView.setOnClickPendingIntent(R.id.widgetLayout, pendingIntent);
    8.  
    This will start an activity when the widget is clicked.
     
    learning_intern likes this.
  3. learning_intern

    learning_intern Member This Topic's Starter

    Joined:
    Jul 28, 2010
    Messages:
    15
    Likes Received:
    0
    hi blundell,

    I would like to apologize if you had difficulty understand my POST service. what it does is, its sends the POST to a php script, the PHP script generates a JSON file and sends it back to my service, and my service then parses the JSON document and stores it in a List<Map<String, String>> object as key-value pairs.

    i added the JSON parsing function in my service -

    Code (Text):
    1.  
    2. package com.example;
    3.  
    4. import java.io.BufferedReader;
    5. import java.io.IOException;
    6. import java.io.InputStream;
    7. import java.io.InputStreamReader;
    8. import java.util.ArrayList;
    9. import java.util.HashMap;
    10. import java.util.List;
    11. import java.util.Map;
    12.  
    13. import org.apache.http.HttpEntity;
    14. import org.apache.http.HttpResponse;
    15. import org.apache.http.NameValuePair;
    16. import org.apache.http.client.ClientProtocolException;
    17. import org.apache.http.client.HttpClient;
    18. import org.apache.http.client.entity.UrlEncodedFormEntity;
    19. import org.apache.http.client.methods.HttpGet;
    20. import org.apache.http.client.methods.HttpPost;
    21. import org.apache.http.client.methods.HttpUriRequest;
    22. import org.apache.http.impl.client.DefaultHttpClient;
    23. import org.apache.http.message.BasicNameValuePair;
    24. import org.apache.http.protocol.HTTP;
    25. import org.json.JSONArray;
    26. import org.json.JSONException;
    27. import org.json.JSONObject;
    28.  
    29. import android.app.Service;
    30. import android.content.Intent;
    31. import android.os.IBinder;
    32. import android.util.Log;
    33. import android.widget.Toast;
    34.  
    35. public class MyService3 extends Service {
    36.     private static final String TAG = "MyService3";
    37.  
    38.     private ArrayList <NameValuePair> params;
    39.     private ArrayList <NameValuePair> headers;
    40.  
    41.     private String url;
    42.  
    43.     private int responseCode;
    44.     private String message;
    45.  
    46.     private String response;
    47.  
    48.    
    49. List<Map<String, String>> groupData = new ArrayList<Map<String, String>>();
    50.    
    51.     public enum RequestMethod
    52.     {
    53.     GET,
    54.     POST
    55.     }
    56.  
    57.     public String getResponse() {
    58.         return response;
    59.     }
    60.    
    61.     public List<Map<String, String>> getGroupData() {
    62.         return groupData;
    63.     }
    64.  
    65.     public String getErrorMessage() {
    66.         return message;
    67.     }
    68.  
    69.     public int getResponseCode() {
    70.         return responseCode;
    71.     }
    72.  
    73.     public void SetURL(String url)
    74.     {
    75.         this.url = url;
    76.         params = new ArrayList<NameValuePair>();
    77.         headers = new ArrayList<NameValuePair>();
    78.     }
    79.  
    80.     public void AddParam(String name, String value)
    81.     {
    82.         params.add(new BasicNameValuePair(name, value));
    83.     }
    84.  
    85.     public void AddHeader(String name, String value)
    86.     {
    87.         headers.add(new BasicNameValuePair(name, value));
    88.     }
    89.    
    90.     @Override
    91.     public IBinder onBind(Intent intent) {
    92.         return null;
    93.     }
    94.    
    95.     /*-------------------------------------------*/
    96.     @Override
    97.     public void onCreate() {
    98.         Toast.makeText(this, "My Service Created", Toast.LENGTH_LONG).show();
    99.         Log.d(TAG, "onCreate");
    100.        
    101.         SetURL("http://192.168.1.8/testhttpphp.php");
    102.         AddParam("task_id","20");
    103.  
    104.     }
    105.  
    106.     @Override
    107.     public void onDestroy() {
    108.         Toast.makeText(this, "My Service Stopped", Toast.LENGTH_LONG).show();
    109.         Log.d(TAG, "onDestroy");
    110.  
    111.     }
    112.    
    113.     @Override
    114.     public void onStart(Intent intent, int startid) {
    115.         Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG).show();
    116.         Log.d(TAG, "onStart");
    117.        
    118.         try {
    119.             Execute(RequestMethod.POST);
    120.         } catch (Exception e) {
    121.             // TODO Auto-generated catch block
    122.             Log.e(TAG, "error is = " + e.toString());
    123.         }
    124.         //player.start();
    125.     }
    126.    
    127.     /*--------------------------------------------------*/
    128.    
    129.      public void Execute(RequestMethod post) throws Exception
    130.         {
    131.             switch(post) {
    132.                 case GET:
    133.                 {
    134.                     //add parameters
    135.                     String combinedParams = "";
    136.                     if(!params.isEmpty()){
    137.                         combinedParams += "?";
    138.                         for(NameValuePair p : params)
    139.                         {
    140.                             String paramString = p.getName() + "=" + p.getValue();
    141.                             if(combinedParams.length() > 1)
    142.                             {
    143.                                 combinedParams  +=  "&" + paramString;
    144.                             }
    145.                             else
    146.                             {
    147.                                 combinedParams += paramString;
    148.                             }
    149.                         }
    150.                     }
    151.      
    152.                     HttpGet request = new HttpGet(url + combinedParams);
    153.      
    154.                     //add headers
    155.                     for(NameValuePair h : headers)
    156.                     {
    157.                         request.addHeader(h.getName(), h.getValue());
    158.                     }
    159.      
    160.                     executeRequest(request, url);
    161.                     break;
    162.                 }
    163.                 case POST:
    164.                 {
    165.                     HttpPost request = new HttpPost(url);
    166.      
    167.                     //add headers
    168.                  /*   for(NameValuePair h : headers)
    169.                     {
    170.                         request.addHeader(h.getName(), h.getValue());
    171.                     }*/
    172.      
    173.                     if(!params.isEmpty()){
    174.                         request.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
    175.                     }
    176.      
    177.                     executeRequest(request, url);
    178.                     break;
    179.                 }
    180.             }
    181.         }
    182.      
    183.         private void executeRequest(HttpUriRequest request, String url)
    184.         {
    185.             HttpClient client = new DefaultHttpClient();
    186.      
    187.             HttpResponse httpResponse;
    188.      
    189.             try {
    190.                 httpResponse = client.execute(request);
    191.                 responseCode = httpResponse.getStatusLine().getStatusCode();
    192.                 message = httpResponse.getStatusLine().getReasonPhrase();
    193.      
    194.                 HttpEntity entity = httpResponse.getEntity();
    195.      
    196.                 if (entity != null) {
    197.      
    198.                     InputStream instream = entity.getContent();
    199.                     response = convertStreamToString(instream);
    200.      
    201.                     // Closing the input stream will trigger connection release
    202.                     instream.close();
    203.                    
    204.                     parseJSONData(response);
    205.                 }
    206.      
    207.             } catch (ClientProtocolException e)  {
    208.                 client.getConnectionManager().shutdown();
    209.                 e.printStackTrace();
    210.             } catch (IOException e) {
    211.                 client.getConnectionManager().shutdown();
    212.                 e.printStackTrace();
    213.             }
    214.         }
    215.        
    216.        
    217.         private static String convertStreamToString(InputStream is) {
    218.            
    219.             BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    220.             StringBuilder sb = new StringBuilder();
    221.      
    222.             String line = null;
    223.             try {
    224.                 while ((line = reader.readLine()) != null) {
    225.                     sb.append(line + "\n");
    226.                 }
    227.             } catch (IOException e) {
    228.                 e.printStackTrace();
    229.             } finally {
    230.                 try {
    231.                     is.close();
    232.                 } catch (IOException e) {
    233.                     e.printStackTrace();
    234.                 }
    235.             }
    236.             return sb.toString();
    237.         }
    238.    
    239.        
    240.         private void parseJSONData(String response){
    241.             try{
    242.                  JSONArray jArray = new JSONArray(response);
    243.                   // -- list item hash re-used
    244.                    Map<String, String> group;
    245.                    
    246.                    for(int i=0;i<jArray.length();i++){
    247.  
    248.                          JSONObject json_data = jArray.getJSONObject(i);
    249.                    
    250.                          group = new HashMap<String, String>();
    251.                          group.put( "name",json_data.getString("name") );
    252.                          
    253.                          groupData.add(group);
    254.                          
    255.                            Log.i("log_tag","id: "+json_data.getInt("id")+
    256.  
    257.                                  ", name: "+json_data.getString("name")+
    258.                                    ", sd: "+json_data.getString("start_date")+
    259.  
    260.                                  ", ed: "+json_data.getString("end_date"));
    261.                    }
    262.             }
    263.              catch(JSONException e){
    264.                  
    265.                 Log.e("log_tag", "Error parsing data "+e.toString());
    266.  
    267.             }
    268.         }
    269.    
    270.    
    271. }
    272.  
    I tried your code but i was not able to get good results, probably because i could not understand some of the stuff, as to "how is the data that i want to display as listview is being sent to my ProjectsActivity ( the activity where I want to display data, not the one with the buttons).
    As I don't have a lot of android experience, I would request you to please provide some more explanation on your code.

    thanks in advance :)!
     
  4. learning_intern

    learning_intern Member This Topic's Starter

    Joined:
    Jul 28, 2010
    Messages:
    15
    Likes Received:
    0
    Also is there something i need to have in my ProjectsActivity in order to receive the data from the service? i read something about interfaces, do i require them? if yes then how can i use them in my activity?
     
  5. learning_intern

    learning_intern Member This Topic's Starter

    Joined:
    Jul 28, 2010
    Messages:
    15
    Likes Received:
    0
    i tried this code in my onStart() function of my service -

    Code (Text):
    1.  
    2.  
    3. try{
    4.          final Intent startApp = new Intent(getApplicationContext(), ProjectsActivity.class);
    5.          startApp.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    6.  final PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), 0, startApp, 0);      
    7.  remoteView.setOnClickPendingIntent(R.id.buttonStart, pendingIntent);
    8.         } catch(Exception e){
    9.             Log.e(TAG, "error is = " + e.toString());
    10.         }
    11.  
    I also tried changing my
    to

    *Note - ServicesDemo.class is the activity class that has the buttons to start my service and is the first activity that gets loaded in my app. ( the code for it is provided in my first post of this thread)

    in both situations, I get this error in my logcat -

    error is = java.lang.NullPointerException

    what could possibly the issue as I do have a ProjectsActivity class and the ServicesDemo class?
     
  6. styla786

    styla786 Member

    Joined:
    Jun 7, 2010
    Messages:
    9
    Likes Received:
    0
    Your proxy sould be used as a simple WCF proxy. Activities generated are only for workflows (as composite activity).
    To respect good practice, you should use your proxy in an asynCodeActivity.
     

Share This Page

Loading...