Search code examples
javaandroidhttpphonegap

Android (PhoneGap) - Send HTTP request from a button's click event in Push Notification


I've implemented an action button in my android PhoneGap app Push Notification window that performs HTTP request to my server to handle server actions.

Probably we have an exception when we perform the HTTP request because it doesn't seem to work. (currently, we can't view the exception itself for reason I won't get into here)

We implemented by calling the HTTP request in a different thread because we saw answers here in Stackoverflow that you can't implement calling the HTTP request on the main thread.

Any help will be appreciated.

This is my BroadcastReceiver class:

public class ExpressPayRequest extends BroadcastReceiver{

    @Override
    public void onReceive(Context Context, Intent arg1) {
        Context.startService(new Intent(Context, PostRequestService.class));
    }
}

And the service looks like this:

public class PostRequestService extends Service{

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

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

        try{

        URL url = new URL("http://someGETRequest");                
        HttpURLConnection client = (HttpURLConnection)url.openConnection();

        int responseCode = client.getResponseCode();

        }
        catch(IOException e){
             Log.e("LOGEntry", "error log: " + e.getMessage(),e);
        }

     return START_NOT_STICKY;
  }

  @Override
  public IBinder onBind(Intent arg0) {
    // TODO Auto-generated method stub
    return null;
  }
}

Solution

  • I have figured it out myself
    if anyone interested the solution was creating a new thread instead of starting a new service

    this is the code I used:

    Thread thread = new Thread(){
    public void run(){
      try{                
            URL url = new URL("http://test");                
            HttpURLConnection client = (HttpURLConnection)url.openConnection();
             client.connect();
            int responseCode = client.getResponseCode();
    
        } catch (IOException e) {
            e.printStackTrace();
    
        }
    
     }
    };
    
    thread.start();