• After 15+ years, we've made a big change: Android Forums is now Early Bird Club. Learn more here.

Apps How to invoke an activity from a service?

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:
package com.example;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class ServicesDemo extends Activity implements OnClickListener {
  private static final String TAG = "ServicesDemo";
  Button buttonStart, buttonStop, buttonShow;

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    buttonStart = (Button) findViewById(R.id.buttonStart);
    buttonStop = (Button) findViewById(R.id.buttonStop);
    buttonShow = (Button) findViewById(R.id.buttonShow);

    buttonStart.setOnClickListener(this);
    buttonStop.setOnClickListener(this);
    buttonShow.setOnClickListener(this);
  }

  public void onClick(View src) {
    switch (src.getId()) {
    case R.id.buttonStart:
      Log.d(TAG, "onClick: starting service");
      startService(new Intent(this, MyService2.class));
      break;
    case R.id.buttonStop:
      Log.d(TAG, "onClick: stopping service");
      stopService(new Intent(this, MyService2.class));
      break;
    case R.id.buttonShow:
        Log.d(TAG, "onClick: showing records");
        startActivity(new Intent(this, ProjectsActivity.class));
        break;
    }
  }
}

and for my service class -

Code:
package com.example;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;

public class MyService2 extends Service {
    private static final String TAG = "MyService";
    
    private ArrayList <NameValuePair> params;
    private ArrayList <NameValuePair> headers;
 
    private String url;
 
    private int responseCode;
    private String message;
 
    private String response;
    
    public enum RequestMethod
    {
    GET,
    POST
    }
 
    public String getResponse() {
        return response;
    }
 
    public String getErrorMessage() {
        return message;
    }
 
    public int getResponseCode() {
        return responseCode;
    }
 
    public void SetURL(String url)
    {
        this.url = url;
        params = new ArrayList<NameValuePair>();
        headers = new ArrayList<NameValuePair>();
    }
 
    public void AddParam(String name, String value)
    {
        params.add(new BasicNameValuePair(name, value));
    }
 
    public void AddHeader(String name, String value)
    {
        headers.add(new BasicNameValuePair(name, value));
    }

    
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
    /*----------------------------------------------------------------------------*/
    @Override
    public void onCreate() {
        Toast.makeText(this, "My Service Created", Toast.LENGTH_LONG).show();
        Log.d(TAG, "onCreate");
        
        SetURL("http://192.148.1.1/testhttpphp.php");
        AddParam("task_id","20");
    
    }
    

    @Override
    public void onDestroy() {
        Toast.makeText(this, "My Service Stopped", Toast.LENGTH_LONG).show();
        Log.d(TAG, "onDestroy");
    
    }
    
    @Override
    public void onStart(Intent intent, int startid) {
        Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG).show();
        Log.d(TAG, "onStart");
        
        try {
            Execute(RequestMethod.POST);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            Log.e(TAG, "error is = "+ e.toString());
        }
    
    }
    
    /*----------------------------------------------------------------------------*/
    
     public void Execute(RequestMethod post) throws Exception
        {
            switch(post) {
                case GET:
                {
                    //add parameters
                    String combinedParams = "";
                    if(!params.isEmpty()){
                        combinedParams += "?";
                        for(NameValuePair p : params)
                        {
                            String paramString = p.getName() + "=" + p.getValue();
                            if(combinedParams.length() > 1)
                            {
                                combinedParams  +=  "&" + paramString;
                            }
                            else
                            {
                                combinedParams += paramString;
                            }
                        }
                    }
     
                    HttpGet request = new HttpGet(url + combinedParams);
     
                    //add headers
                    for(NameValuePair h : headers)
                    {
                        request.addHeader(h.getName(), h.getValue());
                    }
     
                    executeRequest(request, url);
                    break;
                }
                case POST:
                {
                    HttpPost request = new HttpPost(url);
     
                    //add headers
                 /*   for(NameValuePair h : headers)
                    {
                        request.addHeader(h.getName(), h.getValue());
                    }*/
     
                    if(!params.isEmpty()){
                        request.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
                    }
     
                    executeRequest(request, url);
                    break;
                }
            }
        }
     
        private void executeRequest(HttpUriRequest request, String url)
        {
            HttpClient client = new DefaultHttpClient();
     
            HttpResponse httpResponse;
     
            try {
                httpResponse = client.execute(request);
                responseCode = httpResponse.getStatusLine().getStatusCode();
                message = httpResponse.getStatusLine().getReasonPhrase();
     
                HttpEntity entity = httpResponse.getEntity();
     
                if (entity != null) {
     
                    InputStream instream = entity.getContent();
                    response = convertStreamToString(instream);
     
                    // Closing the input stream will trigger connection release
                    instream.close();
                }
     
            } catch (ClientProtocolException e)  {
                client.getConnectionManager().shutdown();
                e.printStackTrace();
            } catch (IOException e) {
                client.getConnectionManager().shutdown();
                e.printStackTrace();
            }
        }
     
        private static String convertStreamToString(InputStream is) {
     
            BufferedReader reader = new BufferedReader(new InputStreamReader(is));
            StringBuilder sb = new StringBuilder();
     
            String line = null;
            try {
                while ((line = reader.readLine()) != null) {
                    sb.append(line + "\n");
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return sb.toString();
        }
    
    
}

ProjectsActivity is an activity class where i would like to display the JSON document that i receive.

Thanks in advance!
 
Hmm your post confused me, so I'll just answer your title:

Code:
// do this in onStart() of your service
// Add onclick listener
                final Intent startApp = new Intent(getApplicationContext(), MainActivity.class);
                startApp.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        final PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), 0, startApp, 0);       
        remoteView.setOnClickPendingIntent(R.id.widgetLayout, pendingIntent);

This will start an activity when the widget is clicked.
 
  • Like
Reactions: learning_intern
Upvote 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:
package com.example;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;

public class MyService3 extends Service {
    private static final String TAG = "MyService3";

    private ArrayList <NameValuePair> params;
    private ArrayList <NameValuePair> headers;
 
    private String url;
 
    private int responseCode;
    private String message;
 
    private String response;

    
List<Map<String, String>> groupData = new ArrayList<Map<String, String>>();
    
    public enum RequestMethod
    {
    GET,
    POST
    }
 
    public String getResponse() {
        return response;
    }
    
    public List<Map<String, String>> getGroupData() {
        return groupData;
    }
 
    public String getErrorMessage() {
        return message;
    }
 
    public int getResponseCode() {
        return responseCode;
    }
 
    public void SetURL(String url)
    {
        this.url = url;
        params = new ArrayList<NameValuePair>();
        headers = new ArrayList<NameValuePair>();
    }
 
    public void AddParam(String name, String value)
    {
        params.add(new BasicNameValuePair(name, value));
    }
 
    public void AddHeader(String name, String value)
    {
        headers.add(new BasicNameValuePair(name, value));
    }
    
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
    
    /*-------------------------------------------*/
    @Override
    public void onCreate() {
        Toast.makeText(this, "My Service Created", Toast.LENGTH_LONG).show();
        Log.d(TAG, "onCreate");
        
        SetURL("http://192.168.1.8/testhttpphp.php");
        AddParam("task_id","20");

    }

    @Override
    public void onDestroy() {
        Toast.makeText(this, "My Service Stopped", Toast.LENGTH_LONG).show();
        Log.d(TAG, "onDestroy");

    }
    
    @Override
    public void onStart(Intent intent, int startid) {
        Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG).show();
        Log.d(TAG, "onStart");
        
        try {
            Execute(RequestMethod.POST);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            Log.e(TAG, "error is = " + e.toString());
        }
        //player.start();
    }
    
    /*--------------------------------------------------*/
    
     public void Execute(RequestMethod post) throws Exception
        {
            switch(post) {
                case GET:
                {
                    //add parameters
                    String combinedParams = "";
                    if(!params.isEmpty()){
                        combinedParams += "?";
                        for(NameValuePair p : params)
                        {
                            String paramString = p.getName() + "=" + p.getValue();
                            if(combinedParams.length() > 1)
                            {
                                combinedParams  +=  "&" + paramString;
                            }
                            else
                            {
                                combinedParams += paramString;
                            }
                        }
                    }
     
                    HttpGet request = new HttpGet(url + combinedParams);
     
                    //add headers
                    for(NameValuePair h : headers)
                    {
                        request.addHeader(h.getName(), h.getValue());
                    }
     
                    executeRequest(request, url);
                    break;
                }
                case POST:
                {
                    HttpPost request = new HttpPost(url);
     
                    //add headers
                 /*   for(NameValuePair h : headers)
                    {
                        request.addHeader(h.getName(), h.getValue());
                    }*/
     
                    if(!params.isEmpty()){
                        request.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
                    }
     
                    executeRequest(request, url);
                    break;
                }
            }
        }
     
        private void executeRequest(HttpUriRequest request, String url)
        {
            HttpClient client = new DefaultHttpClient();
     
            HttpResponse httpResponse;
     
            try {
                httpResponse = client.execute(request);
                responseCode = httpResponse.getStatusLine().getStatusCode();
                message = httpResponse.getStatusLine().getReasonPhrase();
     
                HttpEntity entity = httpResponse.getEntity();
     
                if (entity != null) {
     
                    InputStream instream = entity.getContent();
                    response = convertStreamToString(instream);
     
                    // Closing the input stream will trigger connection release
                    instream.close();
                    
                    parseJSONData(response);
                }
     
            } catch (ClientProtocolException e)  {
                client.getConnectionManager().shutdown();
                e.printStackTrace();
            } catch (IOException e) {
                client.getConnectionManager().shutdown();
                e.printStackTrace();
            }
        }
        
        
        private static String convertStreamToString(InputStream is) {
            
            BufferedReader reader = new BufferedReader(new InputStreamReader(is));
            StringBuilder sb = new StringBuilder();
     
            String line = null;
            try {
                while ((line = reader.readLine()) != null) {
                    sb.append(line + "\n");
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return sb.toString();
        }
    
        
        private void parseJSONData(String response){
            try{
                 JSONArray jArray = new JSONArray(response);
                  // -- list item hash re-used
                   Map<String, String> group;
                   
                   for(int i=0;i<jArray.length();i++){

                         JSONObject json_data = jArray.getJSONObject(i);
                   
                         group = new HashMap<String, String>();
                         group.put( "name",json_data.getString("name") );
                         
                         groupData.add(group);
                         
                           Log.i("log_tag","id: "+json_data.getInt("id")+

                                 ", name: "+json_data.getString("name")+
                                   ", sd: "+json_data.getString("start_date")+

                                 ", ed: "+json_data.getString("end_date"));
                   }
            }
             catch(JSONException e){
                  
                Log.e("log_tag", "Error parsing data "+e.toString());

            }
        }
    
    
}

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 :)!
 
Upvote 0
i tried this code in my onStart() function of my service -

Code:
try{
         final Intent startApp = new Intent(getApplicationContext(), ProjectsActivity.class);
         startApp.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
 final PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), 0, startApp, 0);       
 remoteView.setOnClickPendingIntent(R.id.buttonStart, pendingIntent);
        } catch(Exception e){
            Log.e(TAG, "error is = " + e.toString());
        }

I also tried changing my
final Intent startApp = new Intent(getApplicationContext(), ProjectsActivity.class);

to

final Intent startApp = new Intent(getApplicationContext(), ServicesDemo.class);

*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?
 
Upvote 0

BEST TECH IN 2023

We've been tracking upcoming products and ranking the best tech since 2007. Thanks for trusting our opinion: we get rewarded through affiliate links that earn us a commission and we invite you to learn more about us.

Smartphones