在IntentService中等待结果

时间:2013-02-22 09:34:43

标签: android android-intent intentservice

使用IntentService时是否有办法等待结果?

情景。

服务应用正在运行 - >从另一个应用程序接收登录凭据 - >服务应用程序然后检查数据库(由于某种原因,我总是让连接超时。我知道这是不好的,但对于POC和快速黑客,这将立即做) - >等待验证查询然后结果。

这可能吗?

我尝试在服务中使用AsynTask但仍无济于事,我总是遇到连接超时错误。

DEMOSERVICE

@Override
public IBinder onBind(Intent intent) {

    return new IDemoService.Stub() {

        @Override
        /**
         * Login validation implementation
         */
        public boolean login(String id, String password)
                throws RemoteException {
            UserLoginTask userLoginTask = new UserLoginTask(id, password);
            try {
                return userLoginTask.execute((Void) null).get();
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (ExecutionException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return false;
        }
    };
}

USERLOGINTASK

 private class UserLoginTask extends AsyncTask<Void, Void, Boolean> {
    private String uId;
    private String uPassword;

    public UserLoginTask(String id, String password) {
        uId = id;
        uPassword = password;
    }

    @Override
    protected Boolean doInBackground(Void... arg0) {
        Connection conn;
        try {
            int count = 0;
            Class.forName("org.postgresql.Driver");
            String url = "jdbc:postgresql://xxx.xxx.x.xxx/test_db?user=postgres&password=password";
            conn = DriverManager.getConnection(url);
            if (conn != null) {
                Statement st = conn.createStatement();
                String sql = "Select count(*) as cnt from tbl_persons where id = '"
                        + uId.toUpperCase(Locale.getDefault()).trim()
                        + "' AND pwd='" + uPassword.trim() + "';";

                Log.d("DemoService", "Login sql - " + sql);
                ResultSet rs = st.executeQuery(sql);
                while (rs.next()) {
                    count = rs.getInt("cnt");
                }

                rs.close();
                st.close();
                conn.close();

                if (count == 0)
                    return false;

                return true;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return false;
    }

}

0 个答案:

没有答案