繁体   English   中英

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

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

我做了一个应用程序,它连续不断地向/从服务器发送/接收经纬度。还从服务器检索和显示信息。我已经使用asynctask进行网络通话了。 但是当电话打进来并且后台的应用程序断开连接时,我遇到了一个问题;例如不显示任何服务器信息,或者长时间不发送消息到正确目的地的服务器。 如何解决呢? 就像如果我要使用凌空抽签, 那么单例类可能有助于解决此问题 。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);
            }
        }

    }

我是android的新手,无法找到此问题的解决方案。请提供任何帮助。 TIA

在此处输入图片说明

在此处输入图片说明

您需要使用IncomingCallReceiver(用户定义:下面给出的代码)收听传入的呼叫,并在收到呼叫时挂起/停止Asynctask,并在呼叫结束后恢复/重新启动它。

对于停止重新启动的情况 :在您的Asynctask中,您可以使其在sharedpreference标志变量上循环以实现连续行为,并在调用到来时将标志设置为false。 通话结束后,您可以再次启动Asynctask。

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

来电接听器教程: http : //www.theappguruz.com/blog/detecting-incoming-phone-calls-in-android

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

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

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

您可以在Service中运行该代码。 该服务可以在后台运行(即使应用程序已暂停/停止)-这意味着即使有电话打进(这会使您的活动处于暂停状态),您的代码也应无中断运行。

确保阅读有关服务生命周期的更多信息,以实现您要正确执行的操作。

编辑:

要在Service中运行AsyncTask,请在创建Service时创建该任务的实例(请参阅Service lifecycle ),然后在其中运行任务。

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

您可以服务绑定到您的活动以与其进行通信。

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