作为服务运行异步

时间:2019-03-06 06:47:04

标签: android android-asynctask android-service android-permissions

我正在尝试将此代码作为后台任务运行。

package com.ibm.watson.developer_cloud.android.myapplication;

import android.app.AlertDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.widget.Toast;

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;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

public class BackgroundReadTranscriptWorker extends AsyncTask<String, Void, String> {
    Context context;
    AlertDialog alertDialog;
    String json_string;
    StringBuilder stringBuilder;
    String results;
    BackgroundReadTranscriptWorker(Context ctx){
        context = ctx;
    }

    @Override
    protected String doInBackground(String... params) {
        String type = params[0];
        String login_url = "http://colconnect.eodtranslations.asia/gettranscripts.php";
        if(type.equals("insert")){
            try {
                String tuid = params[1];


                URL url = new URL(login_url);
                HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
                httpURLConnection.setRequestMethod("POST");
                httpURLConnection.setDoOutput(true);
                httpURLConnection.setDoInput(true);
                OutputStream outputStream = httpURLConnection.getOutputStream();
                BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, StandardCharsets.UTF_8));
                String post_data = URLEncoder.encode("user_num","UTF-8")+"="+URLEncoder.encode(tuid,"UTF-8");

                bufferedWriter.write(post_data);
                bufferedWriter.flush();
                bufferedWriter.close();
                outputStream.close();
                /*InputStream inputStream = httpURLConnection.getInputStream();



                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.ISO_8859_1));
               stringBuilder=new StringBuilder();
                String result="";
                String line="";
                while((json_string = bufferedReader.readLine())!= null) {
                 stringBuilder.append(json_string+"\n");

                }


                bufferedReader.close();
                inputStream.close();
                httpURLConnection.disconnect();
               results= stringBuilder.toString().trim();*/
                InputStream inputStream = httpURLConnection.getInputStream();
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.ISO_8859_1));
                String result="";
                String line="";
                while((line = bufferedReader.readLine())!= null) {
                    result += line;
                }
                bufferedReader.close();
                inputStream.close();
                httpURLConnection.disconnect();
                return result;
            } catch (MalformedURLException e) {
                e.printStackTrace();
            }
            catch (IOException e) {
                e.printStackTrace();
            }

        }
        return null;
    }

    @Override
    protected void onPreExecute() {

    }

    @Override
    protected void onPostExecute(String result) {

        if (result.contains("success")){

          //  System.out.println(results);
            //Toast.makeText(context, results,Toast.LENGTH_SHORT).show();
        }
        else{
            Toast.makeText(context, "Unable to get!",Toast.LENGTH_SHORT).show();
        }
    }

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

它的任务是从在线数据库中获取数据并将其显示给烤面包。 一旦有来电,我就尝试执行此代码,但实际上确实有来电时,它似乎没有执行。可以将其作为服务执行吗?

这是我的手机状态监听器

 public class CallReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getStringExtra(TelephonyManager.EXTRA_STATE).equals(TelephonyManager.EXTRA_STATE_OFFHOOK)){
               // startService(v);
                //startRecordingService(context);
               // startSTT();
                showToast(context, "Call started. . .");
                String type= "insert";
                BackgroundReadTranscriptWorker brtw = new BackgroundReadTranscriptWorker(MainActivity.this);
                brtw.execute(type,number);



            }
            else if (intent.getStringExtra(TelephonyManager.EXTRA_STATE).equals(TelephonyManager.EXTRA_STATE)){
                showToast(context, "Call ended. . .");

                int pid = android.os.Process.myPid();
                android.os.Process.killProcess(pid);
            }
        }

    }

0 个答案:

没有答案