如何正确地将代码添加到后台进程代码中

时间:2018-06-04 11:37:26

标签: java android http android-studio

我发现了一个现成的项目,其源代码可以作为服务使用,并希望稍微更改一下并在行之间添加我的算法。这个的本质是我想创建一个在后台运行的程序,每10秒向服务器发送一个请求,并作为响应接收数字。

HttpHandler类

<input type="number" formControlName="PATIENT_AGE"  placeholder="Enter Age b/w 1 and 100" class="form-control input-sm"  min="1" max="100" [(ngModel)]="PATIENT_AGE" name="PATIENT_AGE" required/>
 <div id="forAgeDiv"><span id="forAge"></span></div>
</td>

<td>
    <input type="radio" name="PATIENT_TYPE"  formControlName="PATIENT_TYPE"  value="Pediatric" [attr.disabled]="PATIENT_AGE < 18 || null">Pediatric 
</td>

<td>
    <input type="radio" name="PATIENT_TYPE"  formControlName="PATIENT_TYPE"  value="Adolescent" [attr.disabled]="PATIENT_AGE >= 18 || null"> Adolescent
    <br>
</td>

MyService文件

import android.util.Log;
 import java.io.BufferedInputStream;
 import java.io.BufferedReader;
 import java.io.IOException;
 import java.io.InputStream;
 import java.io.InputStreamReader;
 import java.net.HttpURLConnection;
 import java.net.MalformedURLException;
 import java.net.ProtocolException;
 import java.net.URL;

public class HttpHandler {

    private static final String TAG = HttpHandler.class.getSimpleName();

    public HttpHandler() {
    }

    public String makeServiceCall(String reqUrl) {
        String response  = "";
        String response1 = "";
        String response2 = "";
        String response3 = "";
        String response4 = "";
        String response5 = "";

        try {
            URL url = new URL(reqUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            // read the response
            InputStream in = new BufferedInputStream(conn.getInputStream());
            response1 = convertStreamToString(in);
        } catch (MalformedURLException e) {
            response2=e.getMessage();
        } catch (ProtocolException e) {
            response3=e.getMessage();
        } catch (IOException e) {
            response4=e.getMessage();
        } catch (Exception e) {
            response5=e.getMessage();
        }
        String k="r1="+response+"r2="+response1+"r3="+response2+"r4="+response3+"r5="+response4+"r6="+response5;
        return k;
    }

    private String convertStreamToString(InputStream is) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();

        String line;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line).append('\n');
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return sb.toString();
    }
}

MainActivity代码

public class MyService extends Service {
    private static final String TAG = "MyService";
    private boolean isRunning  = false;
    private Looper looper;
    private MyServiceHandler myServiceHandler;

    String MyResult;
    private class GetContacts extends AsyncTask<Void, Void, Void> {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            //Toast.makeText(infoobj.this,"start download",Toast.LENGTH_LONG).show();
        }

        @Override
        protected Void doInBackground(Void... arg0)
        {
            HttpHandler sh2 = new HttpHandler();
            // Making a request to url and getting response
            String url2;
            url2 = "http://myUrl/check.php?x=1";

            String jsonStr2 = sh2.makeServiceCall(url2);
            MyResult=jsonStr2;
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);

        }
    }

    @Override
    public void onCreate() {
        HandlerThread handlerthread = new HandlerThread("MyThread", Process.THREAD_PRIORITY_BACKGROUND);
        handlerthread.start();
        looper = handlerthread.getLooper();
        myServiceHandler = new MyServiceHandler(looper);
        isRunning = true;
    }
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Message msg = myServiceHandler.obtainMessage();
        msg.arg1 = startId;

        new GetContacts().execute();

        myServiceHandler.sendMessage(msg);
        Toast.makeText(this, "MyService Started.", Toast.LENGTH_SHORT).show();

        Toast.makeText(this, MyResult, Toast.LENGTH_SHORT).show();

        //If service is killed while starting, it restarts.
        return START_STICKY;
    }
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
    @Override
    public void onDestroy() {
        isRunning = false;
        Toast.makeText(this, "MyService Completed or Stopped."+MyResult, Toast.LENGTH_SHORT).show();
    }
    private final class MyServiceHandler extends Handler {
        public MyServiceHandler(Looper looper) {
            super(looper);
        }
        @Override
        public void handleMessage(Message msg) {
            synchronized (this) {
                for (int i = 0; i < 10; i++) {
                    try {
                        Log.i(TAG, "MyService running...");

                        Thread.sleep(1000);
                    } catch (Exception e) {
                        Log.i(TAG, e.getMessage());
                    }
                    if(!isRunning){
                        break;
                    }
                }

            }
            //stops the service for the start id.
            stopSelfResult(msg.arg1);
        }
    }
}

和MainActivityLayout

public class MainActivity extends AppCompatActivity {

    String MyResult;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        View.OnClickListener listener = new View.OnClickListener() {
            public void onClick(View view) {
                Intent intent = new Intent(MainActivity.this, MyService.class);
                switch (view.getId()) {
                    case R.id.service_start:
                        //starts service for the given Intent
                        startService(intent);
                        break;
                    case R.id.service_stop:
                        //stops service for the given Intent
                        stopService(intent);
                        break;
                }
            }
        };
        findViewById(R.id.service_start).setOnClickListener(listener);
        findViewById(R.id.service_stop).setOnClickListener(listener);
    }
}

0 个答案:

没有答案