I want to run some Extension Methods in Synchronous Task

but what is reason this is killing app ?

how to use ????
import android.os.AsyncTask;

Currently This is Working Tested Now.

@SimpleFunction(description = "Threded Functon")
      public void onSuccess() {
        form.runOnUiThread(new Runnable() {
          @Override
          public void run() {
          texter() ;
          }
        });
      }

This code will run function on UI/Main thread. If function is a long running operation then app will get freezed until operation is completed.

Use AsynchUtil to run a function in background thread and the post result to main thread using form.runOnUiThread() .

1 Like

How to use AsynchUtil ? any Tutorial code ?

But We know that Thread means Parallel Process or Function.Then Why App UI will Freeze. I am Using Thread for Sorting Freezing Problem. :smile: :sweat_smile: :laughing:

Is this is correct way to use as following ?

import com.google.appinventor.components.runtime.util.AsynchUtil;

 AsynchUtil.runAsynchronously(new Runnable() {
      @Override
      public void run() {
       myMethod();
      }
      });

See source code of web component. Here is a sample code from my personal extension with concurrent package

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class FileHelper extends AndroidNonvisibleComponent {

    private final ExecutorService executor = Executors.newSingleThreadExecutor();

    public FileHelper(ComponentContainer container) {
        super(container.$form());
    }
// Part of code after skipping some code

@SimpleFunction(description = "Creates a new file on server.")
    public void CreateFile(String bucketId, String fileId, String projectId, String cookie, String filePath, YailList permissionsYailList) {
        executor.execute(() -> {
            try {
                // Again some code here...

                OutputStream outputStream = connection.getOutputStream();
                DataOutputStream request = new DataOutputStream(outputStream);

                // Include the fileId as part of the request
                writeFormField(request, "fileId", fileId, boundary);
                writeFileField(request, "file", new java.io.File(filePath), boundary);

                // Include permissions if specified
                if (permissionsYailList != null) {
                    for (Object permission : permissionsYailList.toArray()) {
                        writeFormField(request, "permissions[]", permission.toString(), boundary);
                    }
                }
                
                request.writeBytes("--" + boundary + "--\r\n");
                request.flush();
                request.close();

                int responseCode = connection.getResponseCode();
                if (responseCode == HttpURLConnection.HTTP_CREATED) {
                    BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                    StringBuilder response = new StringBuilder();
                    String line;
                    while ((line = reader.readLine()) != null) {
                        response.append(line);
                    }
                    reader.close();
                    form.runOnUiThread(() -> FileCreated(response.toString(), responseCode));
                } else {
                    String errorMsg = readErrorResponse(connection);
                    form.runOnUiThread(() -> ReportError("HTTP Error: " + responseCode + " - " + errorMsg));
                }

            } catch (Exception e) {
                e.printStackTrace();
                form.runOnUiThread(() -> ReportError("Failed to create file: " + e.getMessage()));
            }
        });
    }
// Other Code Continues......

That's right.

1 Like
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class FileHelper extends AndroidNonvisibleComponent {

    private final ExecutorService executor = Executors.newSingleThreadExecutor();

    public FileHelper(ComponentContainer container) {
        super(container.$form());
    }
// Part of code after skipping some code

@SimpleFunction(description = "That Simple Right ?.")
    public void CreateFile() {
        executor.execute(() -> {
        
        muMethod();
        // My concurrent Methods .
        
        
        });
    }

can i use concurreny ... again for following problem ?

image

What do you want to achieve? Can you elaborate?

I think all Solution are right !

image

but chek this diagram . simple issue is

simply if myMethod( ); is calling from same device there is no need to worry.

if myMethod( ); is calling from 50+ client device in network. it would like deadlock for that method. and data of method may misbehave. so i am Clearing this future concept.

Also there is chances of Terminating app Automatically ?

There is no way to identify whether server is busy delivering data or not.

If you are dealing with server, then you should write an async cloud function, so when 10 users request a resource they will get the resource based on their position in the line. Though it will delay the response time but will not overload server.

1 Like

after Using with AsynchUtil App getting Terminated and Ended. I don't know Why ?

Show complete code.


  @SimpleFunction(description = "")
  public void printPOS(final String Tabs) {

    AsynchUtil.runAsynchronously(new Runnable() {
      @Override
      public void run() {
        bgPrint(Tabs) ;
      }
      });

  }
  /* //Its Working ...
   @SimpleFunction(description = "Threded Functon")
      public void printPOS(final String Tabs) {
        form.runOnUiThread(new Runnable() {
          @Override
          public void run() {
          bgPrint(Tabs) ;
          }
        });
      }*/



 @SimpleFunction(description = "Printing Future")
public void bgPrint(String Tabs) {
           bgQTotal = 0;
            bgTotal = 0;
      bgGrand_Total = 0;

         bgDiscount = 0;
  bgDiscount_in_Per = 0;


      List11.clear();
      List12.clear();
      List13.clear();
      List14.clear();

    bgIns =  getDB(Tabs);

        float bgFqty = 0;



        boolean bgbint = false;

          for(int i=0;i< Ins.size();i++){

                if(bgbint){

                bgFqty = Float.parseFloat(bgIns.get(i));
                bgQuentity.add(String.format("%.1f", bgFqty));

                }else{
                bgFqty = Float.parseFloat(bgIns.get(i+1));
                bgItem.add(bgIns.get(i));
                GetRateOfItem(bgIns.get(i));
                bgRate.add( String.format("%.2f",RateFromTDB));//50 is Temperary rate
                bgAmount.add(String.format("%.2f",RateFromTDB * bgFqty));
                }
            bgbint=!bgbint;
            }

  //int LengthCheck =  Item.size();
  for(int i=0;i< bgQuentity.size();i++){
                bgQTotal = bgQTotal + Float.parseFloat(bgQuentity.get(i));
				}

  for(int i=0;i< bgAmount.size();i++){
                bgTotal = bgTotal + Float.parseFloat(bgAmount.get(i));
				}

				bgPrint();
}

You can't update views or give commands from background thread.
Call bgPrint inside form.runOnUiThread method.

Ok I try

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.