簡體   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