-2

I have the following code and it works fine with in an activity. But how can we use it from inside a service?

The service is running in background and whenever user copies any text, it triggers onPrimaryClipChanged(), and an HTTP Get request is made to send this data to the server. Then we process the result and show a toast notification based on the result.

The Service runs globally and need to be in background as a service.

    @Override
    protected Void doInBackground(Void... arg0) {
       HttpHandler sh = new HttpHandler();

        // Making a request to url and getting response
        String jsonStr = sh.makeServiceCall(url);

        if (jsonStr != null) {
            try {

                JSONObject jsonObj = new JSONObject(jsonStr);

                JSONArray place = jsonObj.getJSONArray("tuc");
                JSONObject address = place.getJSONObject(0).getJSONObject("phrase");
                meaning = address.getString("text");

            } catch (final JSONException e) {
               // Log.e(TAG, "Json parsing error: " + e.getMessage());
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getApplicationContext(),
                                "Json parsing error: " + e.getMessage(),
                                Toast.LENGTH_LONG)
                                .show();
                    }
                });

            }
        } else {
         //   Log.e(TAG, "Couldn't get json from server.");
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(getApplicationContext(),
                            "Couldn't get json from server. Check LogCat for possible errors!",
                            Toast.LENGTH_LONG)
                            .show();
                }
            });

        }

        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);
        // Dismiss the progress dialog
        if (pd.isShowing())
            pd.dismiss();        


        showToast(result);

    }

}

Tried using same code inside a service class,but it does not works. It compiles, but do nothing when run..

please help me, how can i parse json in service class. THANK YOU in advance

  • Y you want to parse json in service ? give some scenario so we can help. – Wasim K. Memon Apr 14 '18 at 04:58
  • the service is running in background and whenever user copies any text, it triggers this json, to send a http request based on the text for some processing, then displays the result as a toast. Its an app which runs as a background service, and operates system wide. Copying of text is detected by using onPrimaryClipChanged(), inside this service. It works perfect. Now I need to send this copied text inside a http get request and get back the json fromm server, then parse it and display result in a toast, without showing the activity. – Habeeb Mohamed Apr 14 '18 at 05:06
  • This is not a good way to perform such operations in service. Services are heavy and consume more battery and resources. You can use Intent service with Intent Filters and from it you can start transparent activity which can perform all this things and display result and then you can destroy it or system will destroy it. – Wasim K. Memon Apr 14 '18 at 05:21
  • Can You please elaborate? Can we detect text copy from Intent Service? – Habeeb Mohamed Apr 14 '18 at 05:24
  • I don't know much about clipboard framework. But you should check this - https://stackoverflow.com/questions/6931359/how-to-listen-for-a-copy-in-android – Wasim K. Memon Apr 14 '18 at 06:13
  • it requires service, and service callback to onPrimaryClipChanged() ; and there lies the problem with json parsing. – Habeeb Mohamed Apr 14 '18 at 07:36

2 Answers2

0

Asynctask itself runs in the background so I dont understand why you would want to run asynctask in a bg service.

This link has the basics to setup an asynctask https://developer.android.com/reference/android/os/AsyncTask.html

Hope this helps.

shiredude95
  • 560
  • 3
  • 7
  • Iam using Async Task only, protected Void doInBackground(Void... arg0) is part of it,as shown in the question. It works inside an activity. But the issue is it is not working inside service, which is mandatory. – Habeeb Mohamed Apr 14 '18 at 05:30
  • Since you are doing this inside a service class, a quick try would be to try and call the toast method from inside a runOnUiThread runnable. Because you are nesting your asynctask inside a service I think the UI is not being updated from the onPostExecute. – shiredude95 Apr 14 '18 at 05:35
  • Async tasks are for shorter operations. This App need to run infinitely. Additionally, clipboard manager requires a service trigger, Please read the question. – Habeeb Mohamed Apr 14 '18 at 05:38
  • Please read my latest comment. Since you are using asynctask inside a service it would be well worth a try to try running your UI calls from inside a runOnUIThread runnable to see if the results are what you are looking for. – shiredude95 Apr 14 '18 at 05:40
  • Services cant run runOnUiThread(new Runnable() ; there is a work around using handler. but that doesn't solve the problem. Still no result displayed. – Habeeb Mohamed Apr 14 '18 at 07:39
  • Have you tried doing a runonuithread from inside onPostExecute? – shiredude95 Apr 14 '18 at 08:48
0

The only easy option in this scenario is to start a transparent activity and do the processing from with in it.

<?xml version="1.0" encoding="utf-8"?>
<resources>
 <style name="Theme.Transparent" parent="android:Theme">
<item name="android:windowIsTranslucent">true</item>
<item name="android:windowBackground">@android:color/transparent</item>
<item name="android:windowContentOverlay">@null</item>
<item name="android:windowNoTitle">true</item>
<item name="android:windowIsFloating">true</item>
<item name="android:backgroundDimEnabled">false</item>
</style>
</resources>

this will create an invisible activity.