[英]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
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.