简体   繁体   中英

How to handle asynctask during phone call and apps in background android

i have made an app, which sending/receiving lat long to/from server continuously.also retrieving and showing information from server.i have used asynctask for network call. but one problem when phonecall came and apps in background my apps lost its connection;like not show any server information nor send lat long to server in right destination. how to solve this? like if i would use volley then singleton class may help to solve this problem is there any solution for asynctask?

this is my asynctask:

     import android.app.ProgressDialog;
        import android.content.Context;

        import android.os.AsyncTask;

        import android.util.Log;

        import java.io.BufferedReader;
        import java.io.BufferedWriter;
        import java.io.IOException;
        import java.io.InputStream;
        import java.io.InputStreamReader;
        import java.io.OutputStream;
        import java.io.OutputStreamWriter;

        import java.net.HttpURLConnection;
        import java.net.MalformedURLException;
        import java.net.URL;


public class
GetPostAsyncTask extends AsyncTask<String, Void, String> {

    public AsyncResult asyncResult;
//    HttpURLConnection httpURLConnection;


//    private static String responseStr = "";
//    private static String responseStrLogin = "";



    ProgressDialog progressDialog;
    private final String baseUrl = UserInfo.getBaseUrl();

    Context context;


        GetPostAsyncTask(Context context,AsyncResult asyncResult) {

            this.context=context;
            this.asyncResult= asyncResult;
        }

        @Override
        protected void onPreExecute() {
            //Toast.makeText(context,"Loading..",Toast.LENGTH_SHORT).show();
            progressDialog=new ProgressDialog(context);
            progressDialog.show();

        }

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

            try {
                // setting the URL
                URL url = new URL(baseUrl+args[1]);
                HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
                httpURLConnection.addRequestProperty("User-Agent", "RealTimeApps/1.0");
                // setting the method type
                httpURLConnection.setRequestMethod(args[0]);
    //                httpURLConnection.setChunkedStreamingMode(0);
                httpURLConnection.setDoInput(true);
                httpURLConnection.setDoOutput(true);
                OutputStream outputStream = httpURLConnection.getOutputStream();
                BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));

                Log.v("Url",args[2]);
                // setting the identification key name with query params
                bufferedWriter.write(args[2]);
                bufferedWriter.flush();
                bufferedWriter.close();

                Log.v("GetPostA", url.toString());

                httpURLConnection.connect();
                int getPostStatus = httpURLConnection.getResponseCode();

                Log.v("GetPostSts", String.valueOf(getPostStatus));



                String line = "";
                String res = "";
    //                if(getPostStatus == 200){

                // prepare the output buffer
                InputStream inputStream = httpURLConnection.getInputStream();
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));

                while ((line = bufferedReader.readLine()) != null) {

                    res += line;

                }

                inputStream.close();

    //                }

                httpURLConnection.disconnect();

                return res.toString();

            } catch (MalformedURLException e) {

                e.printStackTrace();
                Log.v("GetPostCatchMal",e.toString());

            } catch (IOException e) {
                e.printStackTrace();
                Log.v("GetPostCatchIOE", e.toString());
            }

            return null;

        }

        @Override
        protected void onProgressUpdate(Void... values) {
            super.onProgressUpdate(values);
        }


        @Override
        protected void onPostExecute(String result) {

            super.onPostExecute(result);
            progressDialog.dismiss();
            if(result!=null) {
                asyncResult.asyncResult(result);
            }
        }

    }

i am very new in android and unable to find the solution of this problem.any help please. TIA

在此处输入图片说明

在此处输入图片说明

You need to listen to incoming calls using an IncomingCallReceiver (user-defined : code given below) and suspend/stop your Asynctask when you receive a call, and resume/restart it when the call ends.

For stop-restart case : In your Asynctask you can make it loop on a sharedpreference flag variable for continuous behavior and set the flag to false when call comes. When call ends, you can initiate the Asynctask again.

Code for IncomingCallReceiver:

public class IncomingCallReceiver extends BroadcastReceiver {                            
@Override
public void onReceive(Context context, Intent intent) {
                              // 2
    this.context = context;
    try{

     String state = intent.getStringExtra(TelephonyManager.EXTRA_STATE);  

     if (TelephonyManager.EXTRA_STATE_RINGING.equals(state))
     {
          //Call incoming
     }
     else if(TelephonyManager.EXTRA_STATE_OFFHOOK.equals(state))
     {
         //Call picked up
     }
     else if(TelephonyManager.EXTRA_STATE_IDLE.equals(state))
     {
         //Call ends 
     }
     }
    catch(Exception e)
    {
       e.printStackTrace();
    }

Incoming call receiver tutorial: http://www.theappguruz.com/blog/detecting-incoming-phone-calls-in-android

Shared preferences tutorial : https://www.tutorialspoint.com/android/android_shared_preferences.htm

Asynctask tutorial: https://developer.android.com/reference/android/os/AsyncTask.html

Singleton class tutorial: https://sourcemaking.com/design_patterns/singleton

You can run that code in a Service . The service can run in the background (even when app is paused/stopped) - which means that even when a phone call comes in (which puts your activity in paused state) your code should run without interruptions.

Make sure you read more about the lifecycle of the Service to implement what you're trying to do properly.

EDIT:

To run the AsyncTask within the Service, create an instance of that task when creating the Service (see Service lifecycle ) and run the task there.

When you try to start a Service that is already running, it won't create another instance but rather will return an instance of the running Service, however it will call onStartCommand again.

You can bind the service to your activity(s) to communicate with it.

1.

 <service
            android:name=".AsyncTaskInServiceService">
        </service>
2.

public class ServiceReciever extends BroadcastReceiver {

    @Override
    public void onReceive(final Context context, Intent intent) {
        TelephonyManager telephony = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
        telephony.listen(new PhoneStateListener(){
            @Override
            public void onCallStateChanged(int state, String incomingNumber) {
                super.onCallStateChanged(state, incomingNumber);
                System.out.println("incomingNumber : " + incomingNumber);
                Toast.makeText(context,incomingNumber,Toast.LENGTH_LONG).show();
Asynchtask().execute();//Write the code here
            }
        },PhoneStateListener.LISTEN_CALL_STATE);
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM