Android服务无效

时间:2015-09-01 14:06:18

标签: android

预期的输出:点击start_service按钮后,会向www.google.com发送请求,具体取决于请求是否成功,应显示带有相应消息的AlertDialog。

当前输出:首次点击start_service按钮后,它会显示一个AlertDialog" NO INTERNET ACCESS"。 但是,从第二次单击开始,它会显示AlertDialog "互联网访问"。

我做错了什么?

服务类

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类

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;
    }
};

}

2 个答案:

答案 0 :(得分:1)

您正在返回布尔值:

return intenetAccess;
在请求完成之前

。调用onResponse侦听器并将布尔值更改为true时,您已经返回了默认值false。

那么你能做些什么来解决这个问题呢?一种方法是将侦听器传递给realService.SendRequest,并从onResponse和onErrorResponse触发侦听器。

答案 1 :(得分:1)

雅各布拉斯是对的。目前您检查internetAcces是真还是假,它还没有更新。

解决方案:一旦您的服务中的intenetAccess值更新(onResponse函数,您将internetAccess设置为true),您应该使用SendBroadCast将广播发送到您有活动的活动(并在收到你的活动中的BroadCast你应该显示对话框)。

查看此主题,了解如何在服务与活动(https://androidexperinz.wordpress.com/2012/02/14/communication-between-service-and-activity-part-1/

之间进行通信