'Use alarm to check for new data in SQL Server not working

My application has an alarm that is triggered every 5 hours to check for a new record in SQL Server. When the app is open, it runs ok. If I close the app, the alarm works, but it can't connect to SQL.

Can anyone guide me on what I should do?

This is my code.

public class iPPNews extends BroadcastReceiver {

    Connection myConn = null;

    @Override
    public void onReceive(Context context, Intent intent) {

        String currentDateTimeString = java.text.DateFormat.getDateTimeInstance().format(new Date());
        Toast.makeText(context, "\niPP - Noticias\n" + currentDateTimeString + "\n", Toast.LENGTH_LONG).show();
        Vibrator v = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
        v.vibrate(200);

        try {
            Bundle bundle = null;
            String v_ip = null;
            String v_port = "16132";
            String v_class = "net.sourceforge.jtds.jdbc.Driver";
            String v_DB = "XXXXXXXXX";
            String v_user = null;
            String v_pass = null;
            String v_url = null;

            try {
                ApplicationInfo app = context.getPackageManager().getApplicationInfo(context.getPackageName(), PackageManager.GET_META_DATA);
                bundle = app.metaData;
                v_ip = bundle.getString("V_IP_SECRET");
                v_user = bundle.getString("V_USER_SECRET");
                v_pass = bundle.getString("V_PASS_SECRET");
                v_url = "jdbc:jtds:sqlserver://" + v_ip + ":" + v_port + "/" + v_DB;

            } catch (PackageManager.NameNotFoundException e) {
                e.printStackTrace();
            } catch (NullPointerException e) {
                e.printStackTrace();
            }

            Connection myConn = null;

            try {
                Class.forName(v_class);
                try {
                    myConn = DriverManager.getConnection(v_url, v_user, v_pass);

                } catch (SQLException ex) {
                     // error
                }
            } catch (ClassNotFoundException ex) {
                // error
            }
            if (myConn != null) {
                String myQuery = "Select * from tbNoticias where order by tbNewsId desc";
                Statement mySt = myConn.createStatement();
                ResultSet myRes = mySt.executeQuery(myQuery);
                if (myRes.next()) {
                    do {
                         // my code here
                    } while (myRes.next());
                }
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }
}


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source