Pradip Shenolkar
Pradip Shenolkar

Reputation: 817

Android Service not working

Expected ouptput : Once start_service button is clicked a request is sent to www.google.com and depending on whether the request was successful or not an AlertDialog should be displayed with appropriate message.

Current output : After clicking first time on start_service button it displays an AlertDialog "NO INTERNET ACCESS". However from second click onwards it displays an AlertDialog "INTERNET ACCESS".

What am I doing wrong ?

Service class

public class RealService extends Service{

    private static final String TAG="RealService";
    private boolean isRunning=false;
    private IBinder mBinder=new MyBinder();
    private boolean intenetAccess=false;

    Context context=this;
    private RequestQueue reQueue=null;;

    private final String url="http://www.google.com";

    public boolean SendRequest()
    {
        reQueue=Volley.newRequestQueue(this);
        StringRequest request=new StringRequest(com.android.volley.Request.Method.GET,
                url, 
                new Response.Listener<String>() {

            @Override
            public void onResponse(
                    String response) {


                intenetAccess=true;
                Log.i(TAG,"intenetAccess=true");
            }
        },

        new Response.ErrorListener() {

            @Override
            public void onErrorResponse(
                    VolleyError error) {

                intenetAccess=false;

            }
        });

        try{
            reQueue.add(request);
        }
        catch(Exception e){}

        return intenetAccess;

    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.i(TAG, "Service onCreate");

        isRunning=true;

    }



    @Override
    public IBinder onBind(Intent intent) {
        Log.i(TAG, "Service onBind");
        return mBinder;
    }

    @Override
    public void onRebind(Intent intent) {
        Log.i(TAG, "Service onRebind");
        super.onRebind(intent);
    }

    @Override
    public boolean onUnbind(Intent intent) {
        Log.i(TAG, "Service onUnBind");
        return true;
    }

    @Override
    public void onDestroy() {

    isRunning=false;
    intenetAccess=false;
        Log.i(TAG, "Service onDestroy");
        super.onDestroy();
    }



    public class MyBinder extends Binder
    {
        RealService getService()
        {
            return RealService.this;
        }
    }
}

MainActivity class

public class MainActivity extends AppCompatActivity{

    private Button checkbtn;
    private Button start_service_btn;
    private Button stop_service_btn;

    RealService  realService=new RealService();
    boolean serviceBound=false;
    boolean internetPresent=false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        start_service_btn=(Button) findViewById(R.id.start_service_btn);

        start_service_btn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
            internetPresent= realService.SendRequest();
            if(internetPresent)
            {
                showAlertDialog(MainActivity.this, "INTERNET  ACCESS", "You have internet access");

            }
            else
            {
                showAlertDialog(MainActivity.this, "NO INTERNET ACCESS", "You do not have internet access");

            }
            }
        });

        stop_service_btn=(Button) findViewById(R.id.stop_service_btn);

        stop_service_btn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent intent=new Intent(MainActivity.this,RealService.class);
                stopService(intent);
                internetPresent=false;
            }
        });


    public void showAlertDialog(Context context, String title,String message) {

        AlertDialog alertDialog=new AlertDialog.Builder(context).create();
        alertDialog.setTitle(title);
        alertDialog.setMessage(message);

        alertDialog.show();

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

@Override
protected void onStart() {
    super.onStart();
    Intent intent=new Intent(this,RealService.class);
    startService(intent);
    bindService(intent, realServiceConnection, Context.BIND_AUTO_CREATE);
}

@Override
protected void onStop() {
    super.onStop();
    if(serviceBound)
    {
        unbindService(realServiceConnection);
        serviceBound=false;
    }
}

private ServiceConnection realServiceConnection=new ServiceConnection() 
{

    @Override
    public void onServiceDisconnected(ComponentName name) {

        serviceBound=false;
    }

    @Override
    public void onServiceConnected(ComponentName name, IBinder service) {

        MyBinder myBinder=(MyBinder) service;
        realService=myBinder.getService();
        serviceBound=true;
    }
};

}

Upvotes: 1

Views: 65

Answers (2)

Frank D.
Frank D.

Reputation: 1306

Jacob Ras is right. At the moment you check if internetAcces is true or false it hasn't been updated yet.

Solution: As soon as the value of intenetAccess in your Service has been updated (the onResponse function where you set internetAccess to true), you should use SendBroadCast to send a Broadcast to your activity that you have a connection (and upon receiving the BroadCast in your Activity you should show the dialog).

Check out this topic on how to communicate between from your Service to your Activity (https://androidexperinz.wordpress.com/2012/02/14/communication-between-service-and-activity-part-1/)

Upvotes: 1

Jacob Ras
Jacob Ras

Reputation: 5969

You are returning the boolean:

return intenetAccess;

before the request has finished. When your onResponse listener gets called and changes the boolean to true, you have already returned the default value of false.

So what can you do to fix this? One way would be to pass a listener to realService.SendRequest, and trigger the listener from your onResponse and onErrorResponse.

Upvotes: 1

Related Questions