简体   繁体   English

如何在后台android的电话和应用程序期间处理asynctask

[英]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. 我做了一个应用程序,它连续不断地向/从服务器发送/接收经纬度。还从服务器检索和显示信息。我已经使用asynctask进行网络通话了。 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? 就像如果我要使用凌空抽签, 那么单例类可能有助于解决此问题 。asynctask是否有任何解决方案?

this is my asynctask: 这是我的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. 我是android的新手,无法找到此问题的解决方案。请提供任何帮助。 TIA 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. 您需要使用IncomingCallReceiver(用户定义:下面给出的代码)收听传入的呼叫,并在收到呼叫时挂起/停止Asynctask,并在呼叫结束后恢复/重新启动它。

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. 对于停止重新启动的情况 :在您的Asynctask中,您可以使其在sharedpreference标志变量上循环以实现连续行为,并在调用到来时将标志设置为false。 When call ends, you can initiate the Asynctask again. 通话结束后,您可以再次启动Asynctask。

Code for IncomingCallReceiver: 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 来电接听器教程: http : //www.theappguruz.com/blog/detecting-incoming-phone-calls-in-android

Shared preferences tutorial : https://www.tutorialspoint.com/android/android_shared_preferences.htm 共享首选项教程: https : //www.tutorialspoint.com/android/android_shared_preferences.htm

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

Singleton class tutorial: https://sourcemaking.com/design_patterns/singleton Singleton类教程: https //sourcemaking.com/design_patterns/singleton

You can run that code in a Service . 您可以在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. 要在Service中运行AsyncTask,请在创建Service时创建该任务的实例(请参阅Service lifecycle ),然后在其中运行任务。

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. 当您尝试启动已经运行的服务时,它不会创建另一个实例,而是会返回正在运行的服务的一个实例,但是它将再次调用onStartCommand。

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);
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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