0

It's probably pretty obvious, but I'm completely new to programming or asking a question at stackoverflow, so I apologize in advance if I can't explain myself properly. Also, there are some parts I have no idea what they are for anymore since the code is basically a mix of tutorials. What I need the app to do is for it to keep doing what it's doing (the handler part), but while it's is closed (not minimized). But instead of changing the background, I need it to send a notification instead. In other words, every 10 minutes, if the value of temperBU is 19, I get a notification even if the app is closed. For that, if I'm not mistaken, what I need is a service, but I don't understand what type is better for this situation. I tried some tutorials, but nothing seems to work, and if it's possible to start the service as soon as the app gets started.

public class MainActivity extends AppCompatActivity {

ConstraintLayout layout;

class Weather extends AsyncTask<String, Void, String> {

    @Override
    protected String doInBackground(String... address) {

        try {
            URL url = new URL(address[0]);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.connect();

            InputStream is = connection.getInputStream();
            InputStreamReader isr = new InputStreamReader(is);
            int data = isr.read();
            String content = "";
            char ch;
            while (data != -1) {
                ch = (char) data;
                content = content + ch;
                data = isr.read();
            }
            Log.i("Content", content);
            return content;

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main);

    String content;
    Weather weather = new Weather();

    {
        {

            try {
                content = weather.execute("https://api.openweathermap.org/data/2.5/weather?q=budapest,hu&units=metric&appid=ce2fd10cdcc8ab209f979f6a41c27cfe").get();
                JSONObject jsonObject = new JSONObject(content);
                String mainData = jsonObject.getString("main");
                Log.i("mainData", mainData);

                JSONObject object = new JSONObject(mainData);
                Double temp = object.getDouble("temp");
                Log.i("temp", String.valueOf(temp));
                int temperBU = (int) Math.round(temp);
                Log.i("temperBU", String.valueOf(temperBU));

                layout = findViewById(R.id.hs_n);

                if (temperBU == 19)
                    layout.setBackgroundResource(R.drawable.hungry_summer_premium_yes_simple);
                else layout.setBackgroundResource(R.drawable.hungry_summer_premium_no_simple);


                Handler handler = new Handler();

                Runnable r = new Runnable() {
                    public void run() {

                        String content;
                        Weather weather = new Weather();


                        try {
                            content = weather.execute("https://api.openweathermap.org/data/2.5/weather?q=budapest,hu&units=metric&appid=ce2fd10cdcc8ab209f979f6a41c27cfe").get();
                            JSONObject jsonObject = new JSONObject(content);
                            String mainData = jsonObject.getString("main");
                            Log.i("mainData", mainData);//*

                            JSONObject object = new JSONObject(mainData);
                            Double temp = object.getDouble("temp");
                            Log.i("temp", String.valueOf(temp));
                            int temperBU = (int) Math.round(temp);
                            Log.i("temperBU", String.valueOf(temperBU));//*

                            layout = findViewById(R.id.hs_n);

                            if (temperBU == 19)
                                layout.setBackgroundResource(R.drawable.hungry_summer_premium_yes_simple);
                            else
                                layout.setBackgroundResource(R.drawable.hungry_summer_premium_no_simple);


                        } catch (Exception e) {

                            e.printStackTrace();
                        }

                        handler.postDelayed(this::run, 600000);

                    }
                };
                handler.postDelayed(r, 600000);
            } catch (Exception e) {

                e.printStackTrace();
            }
        }
    }
}

}

Thank you so much for the help.

1 Answers1

0

Please note that AsyncTask is deprecated, so use the following to do a background work: Android AsyncTask API deprecating in Android 11.What are the alternatives?

In order to continue doing something after the user closed your app try using foreground service, like this:

  1. in Android manifest, add

    uses-permission android:name="android.permission.FOREGROUND_SERVICE"

this inside the application tag:

service android:name=".services.WorkerSvc"
  1. add this class:

     class WorkerSvc : Service() {
    
    
     override fun onBind(intent: Intent?): IBinder? {
         return null
     }
    
    
    
     override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
         LogUtil.i("onStartCommand")
         startForeground(
             NotificationUtil.NOTIFICATION_ID,
             NotificationUtil.makeForeGroundNotification(getString(R.string.please_wait))
         )
         processIntent(intent)
         return START_STICKY
     }
    
     private fun processIntent(intent: Intent?) {
         if (intent == null) {
             stopSelf()
         } else {
             // DO YOUR WORK HERE. USE INTENT EXTRAS TO PASS DATA TO SERVICE
             // NOTE THIS IS EXECUTED IN MAIN THREAD SO USE ONE OF THE SOLUTION PROVIDED IN A LINK ABOVE
         }
     }
    

    }

  2. To start the service:

     val svcIntent = Intent(App.instance, WorkerSvc::class.java)
     svcIntent.putExtra(
     //DATA TO PASS TO SERVICE
     )
     if (context != null) {
     ContextCompat.startForegroundService(context, svcIntent)
     }
    
Pavel B.
  • 805
  • 10
  • 13