Java 尝试运行服务以执行HTTP GET请求时应用程序崩溃
大约几周前,我刚刚开始Android编程,任务是编写一个程序,将HTTP GET请求发送到外部WeMos D1 mini pro进行处理,以便上传到内部SQL数据库 这是我的主要活动代码Java 尝试运行服务以执行HTTP GET请求时应用程序崩溃,java,android,arduino,Java,Android,Arduino,大约几周前,我刚刚开始Android编程,任务是编写一个程序,将HTTP GET请求发送到外部WeMos D1 mini pro进行处理,以便上传到内部SQL数据库 这是我的主要活动代码 package com.sp.androidesp8266wifi; import android.app.Activity; import android.app.AlertDialog; import android.app.Service; import android.content.Context;
package com.sp.androidesp8266wifi;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ToggleButton;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URISyntaxException;
public class MainActivity extends Activity implements View.OnClickListener {
public final static String PREF_IP = "PREF_IP_ADDRESS";
public final static String PREF_PORT = "PREF_PORT_NUMBER";
// declare buttons and text inputs
private ToggleButton buttonPin2,buttonPin3,buttonPin4,buttonPin5,buttonPin6,buttonPin7;
// shared preferences objects used to save the IP address and port so that the user doesn't have to
// type them next time he/she opens the app.
private EditText editTextIPAddress, editTextPortNumber;
SharedPreferences.Editor editor;
SharedPreferences sharedPreferences;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sharedPreferences = getSharedPreferences("HTTP_HELPER_PREFS",Context.MODE_PRIVATE);
editor = sharedPreferences.edit();
// assign buttons
buttonPin2 = (ToggleButton)findViewById(R.id.buttonPin2);
buttonPin3 = (ToggleButton)findViewById(R.id.buttonPin3);
buttonPin4 = (ToggleButton)findViewById(R.id.buttonPin4);
buttonPin5 = (ToggleButton)findViewById(R.id.buttonPin5);
buttonPin6 = (ToggleButton)findViewById(R.id.buttonPin6);
buttonPin7 = (ToggleButton)findViewById(R.id.buttonPin7);
// set button listener (this class)
buttonPin2.setOnClickListener(this);
buttonPin3.setOnClickListener(this);
buttonPin4.setOnClickListener(this);
buttonPin5.setOnClickListener(this);
buttonPin6.setOnClickListener(this);
buttonPin7.setOnClickListener(this);
// get the IP address and port number from the last time the user used the app,
// put an empty string "" is this is the first time.
editTextIPAddress = (EditText)findViewById(R.id.editTextIPAddress);
editTextPortNumber = (EditText)findViewById(R.id.editTextPortNumber);
editTextIPAddress.setText(sharedPreferences.getString(PREF_IP,""));
editTextPortNumber.setText(sharedPreferences.getString(PREF_PORT,""));
}
@Override
public void onClick(View view) {
// get the ip address
String ipAddress = editTextIPAddress.getText().toString().trim();
// get the port number
String portNumber = editTextPortNumber.getText().toString().trim();
// save the IP address and port for the next time the app is used
editor.putString(PREF_IP,ipAddress); // set the ip address value to save
editor.putString(PREF_PORT,portNumber); // set the port number to save
editor.commit(); // save the IP and PORT
// get the pin number
String parameterValue = "";
String parameter = "";
// get the pin number from the button that was clicked
if(view.getId()==buttonPin2.getId())
{
if (buttonPin2.getText().equals("ON"))
{
parameter = "2";
parameterValue = "1";
}
}
else if(view.getId()==buttonPin3.getId())
{
if (buttonPin3.getText().equals("ON"))
{
parameter = "3";
parameterValue = "1";
}
}
else if(view.getId()==buttonPin4.getId())
{
if (buttonPin4.getText().equals("ON"))
{
parameter = "4";
parameterValue = "1";
}
}
else if(view.getId()==buttonPin5.getId())
{
if (buttonPin5.getText().equals("ON"))
{
parameter = "5";
parameterValue = "1";
}
}
else if(view.getId()==buttonPin6.getId())
{
if (buttonPin6.getText().equals("ON"))
{
parameter = "6";
parameterValue = "1";
}
}
else if(view.getId()==buttonPin7.getId())
{
if (buttonPin7.getText().equals("ON"))
{
parameter = "7";
parameterValue = "1";
}
}
Intent intent = new Intent("com.sp.androidesp8266wifi.ServiceStatusUpdate");
intent.putExtra("parameterValue", parameterValue);
intent.putExtra("ipAddress", ipAddress);
intent.putExtra("portNumber", portNumber);
intent.putExtra("parameter", parameter);
// execute HTTP request
if(ipAddress.length()>0 && portNumber.length()>0) {
startService(intent);
}
}
/**
* Description: Send an HTTP Get request to a specified ip address and port.
* Also send a parameter "parameterName" with the value of "parameterValue".
* @param parameterValue the pin number to toggle
* @param ipAddress the ip address to send the request to
* @param portNumber the port number of the ip address
* @param parameterName
* @return The ip address' reply text, or an ERROR message is it fails to receive one
*/
/* public String sendRequest(String parameterValue, String ipAddress, String portNumber, String parameterName) {
String serverResponse = "ERROR";
try {
HttpClient httpclient = new DefaultHttpClient(); // create an HTTP client
// define the URL e.g. http://myIpaddress:myport/?pin=13 (to toggle pin 13 for example)
URI website = new URI("http://"+ipAddress+":"+portNumber+"/"+parameterName+"/"+parameterValue);
HttpGet getRequest = new HttpGet(); // create an HTTP GET object
getRequest.setURI(website); // set the URL of the GET request
HttpResponse response = httpclient.execute(getRequest); // execute the request
} catch (ClientProtocolException e) {
// HTTP error
serverResponse = e.getMessage();
e.printStackTrace();
} catch (IOException e) {
// IO error
serverResponse = e.getMessage();
e.printStackTrace();
} catch (URISyntaxException e) {
// URL syntax error
serverResponse = e.getMessage();
e.printStackTrace();
}
// return the server's reply/response text
return serverResponse;
} */
/**
* An AsyncTask is needed to execute HTTP requests in the background so that they do not
* block the user interface.
*/
/* private class HttpRequestAsyncTask extends AsyncTask<Void, Void, Void> {
// declare variables needed
private String ipAddress, portNumber;
private Context context;
private String parameter;
private String parameterValue;
/**
* Description: The asyncTask class constructor. Assigns the values used in its other methods.
* @param context the application context, needed to create the dialog
* @param parameterValue the pin number to toggle
* @param ipAddress the ip address to send the request to
* @param portNumber the port number of the ip address
*/
/*public HttpRequestAsyncTask(Context context, String parameterValue, String ipAddress, String portNumber, String parameter)
{
this.context = context;
this.ipAddress = ipAddress;
this.parameterValue = parameterValue;
this.portNumber = portNumber;
this.parameter = parameter;
} */
/**
* Name: doInBackground
* Description: Sends the request to the ip address
* @param voids
* @return
*/
/*@Override
protected Void doInBackground(Void... voids) {
new Handler().postDelayed(new Runnable() {
public void run() {
sendRequest(parameterValue,ipAddress,portNumber, parameter);
}
}, 4000);
return null;
}
/**
* Name: onPostExecute
* Description: This function is executed after the HTTP request returns from the ip address.
* The function sets the dialog's message with the reply text from the server and display the dialog
* if it's not displayed already (in case it was closed by accident);
* @param aVoid void parameter
*/
/**
* Name: onPreExecute
* Description: This function is executed before the HTTP request is sent to ip address.
* The function will set the dialog's message and display the dialog.
*/
}
package com.sp.androidesp8266wifi;
导入android.app.Activity;
导入android.app.AlertDialog;
导入android.app.Service;
导入android.content.Context;
导入android.content.Intent;
导入android.content.SharedReferences;
导入android.os.AsyncTask;
导入android.os.Bundle;
导入android.os.Handler;
导入android.os.IBinder;
导入android.view.view;
导入android.widget.Button;
导入android.widget.CompoundButton;
导入android.widget.EditText;
导入android.widget.ToggleButton;
导入org.apache.http.HttpResponse;
导入org.apache.http.client.ClientProtocolException;
导入org.apache.http.client.HttpClient;
导入org.apache.http.client.methods.HttpGet;
导入org.apache.http.impl.client.DefaultHttpClient;
导入java.io.BufferedReader;
导入java.io.IOException;
导入java.io.InputStream;
导入java.io.InputStreamReader;
导入java.net.URI;
导入java.net.URISyntaxException;
公共类MainActivity扩展活动实现View.OnClickListener{
公共最终静态字符串PREF_IP=“PREF_IP_地址”;
公共最终静态字符串PREF\u PORT=“PREF\u PORT\u NUMBER”;
//声明按钮和文本输入
私人开关按钮按钮2、按钮3、按钮4、按钮5、按钮6、按钮7;
//共享首选项对象用于保存IP地址和端口,以便用户不必
//下次他/她打开应用程序时键入这些内容。
私有EditText EditTextIP地址,editTextPortNumber;
SharedReferences.Editor;
SharedReferences SharedReferences;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SharedReferences=getSharedReferences(“HTTP\u HELPER\u PREFS”,Context.MODE\u PRIVATE);
editor=SharedReferences.edit();
//分配按钮
buttonPin2=(ToggleButton)findViewById(R.id.buttonPin2);
buttonPin3=(ToggleButton)findViewById(R.id.buttonPin3);
buttonPin4=(ToggleButton)findViewById(R.id.buttonPin4);
buttonPin5=(ToggleButton)findViewById(R.id.buttonPin5);
buttonPin6=(ToggleButton)findViewById(R.id.buttonPin6);
buttonPin7=(ToggleButton)findViewById(R.id.buttonPin7);
//设置按钮侦听器(此类)
buttonPin2.setOnClickListener(这个);
buttonPin3.setOnClickListener(这个);
buttonPin4.setOnClickListener(此);
buttonPin5.setOnClickListener(此);
buttonPin6.setOnClickListener(此);
buttonPin7.setOnClickListener(此);
//获取用户上次使用应用程序时的IP地址和端口号,
//放一个空字符串“”是第一次。
editTextIPAddress=(EditText)findViewById(R.id.editTextIPAddress);
editTextPortNumber=(EditText)findViewById(R.id.editTextPortNumber);
editTextIPAddress.setText(SharedReferences.getString(PREF_IP,“”));
editTextPortNumber.setText(SharedReferences.getString(PREF_PORT,“”));
}
@凌驾
公共void onClick(视图){
//获取ip地址
字符串ipAddress=editTextIPAddress.getText().toString().trim();
//获取端口号
字符串端口号=editTextPortNumber.getText().toString().trim();
//保存IP地址和端口,以便下次使用应用程序时使用
editor.putString(PREF_IP,ipAddress);//设置要保存的IP地址值
editor.putString(PREF_PORT,portNumber);//设置要保存的端口号
editor.commit();//保存IP和端口
//获取pin码
字符串参数value=“”;
字符串参数=”;
//从单击的按钮获取pin码
if(view.getId()==buttonPin2.getId())
{
if(buttonPin2.getText().equals(“ON”))
{
参数=“2”;
参数value=“1”;
}
}
else if(view.getId()==buttonPin3.getId())
{
if(buttonPin3.getText().equals(“ON”))
{
参数=“3”;
参数value=“1”;
}
}
else if(view.getId()==buttonPin4.getId())
{
if(buttonPin4.getText().equals(“ON”))
{
参数=“4”;
参数value=“1”;
}
}
else if(view.getId()==buttonPin5.getId())
{
if(buttonPin5.getText().equals(“ON”))
{
参数=“5”;
参数value=“1”;
}
}
else if(view.getId()==buttonPin6.getId())
{
if(buttonPin6.getText().equals(“ON”))
{
参数=“6”;
参数value=“1”;
}
}
else if(view.getId()==buttonPin7.getId())
{
if(buttonPin7.getText().equals(“ON”))
{
参数=“7”;
参数value=“1”;
}
}
意向意向=新意向(“com.sp.androidesp8266wifi.ServiceStatusUpdate”);
intent.putExtra(“参数值”,参数值);
intent.putExtra(“ipAddress”,ipAddress);
intent.putExtra(“端口号”,端口号);
intent.putExtra(“参数”,参数);
//执行HTTP请求
if(ipAddress.length()>0&&portNumber.length()>0){
startService(意向);
}
}
/**
*描述:向指定的ip地址和端口发送HTTP Get请求。
*还发送一个值为“parameterValue”的参数“parameterName”。
*@param parameterValue要切换的管脚编号
*@param ipAddress将请求发送到的ip地址
*@param portNumber ip地址的端口号
*@param参数名
*@返回ip地址的回复文本,或接收不到错误消息
*/
/*公共字符串sendRequest(字符串参数值、字符串IP地址、字符串端口号、字符串参数名称){
字符串serverResponse=“ERROR”;
package com.sp.androidesp8266wifi;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.IBinder;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
public class ServiceStatusUpdate extends Service {
String ipAddress, parameter,parameterValue,portNumber;
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (intent.getAction().equals("com.sp.androidesp8266wifi.ServiceStatusUpdate")) {
ipAddress = intent.getStringExtra("ipAddress");
parameter = intent.getStringExtra("parameter");
parameterValue = intent.getStringExtra("parameterValue");
portNumber = intent.getStringExtra("portNumber");
while (true) {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
new DoBackgroundTask().execute();
e.printStackTrace();
}
}
}
return START_STICKY;
}
public class DoBackgroundTask extends AsyncTask<Void, Void, Void> {
public void sendRequest(String parameterValue, String ipAddress, String portNumber, String parameterName) {
try {
HttpClient httpclient = new DefaultHttpClient(); // create an HTTP client
// define the URL e.g. http://myIpaddress:myport/?pin=13 (to toggle pin 13 for example)
URI website = new URI("http://"+ipAddress+":"+portNumber+"/"+parameterName+"/"+parameterValue);
HttpGet getRequest = new HttpGet(); // create an HTTP GET object
getRequest.setURI(website); // set the URL of the GET request
HttpResponse response = httpclient.execute(getRequest); // execute the request
} catch (ClientProtocolException e) {
// HTTP error
e.printStackTrace();
} catch (IOException e) {
// IO error
e.printStackTrace();
} catch (URISyntaxException e) {
// URL syntax error
e.printStackTrace();
}
}
@Override
protected Void doInBackground(Void... params) {
sendRequest(parameterValue,ipAddress,portNumber,parameter);
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
new Handler().postDelayed(new Runnable() {
public void run() {
sendRequest(parameterValue,ipAddress,portNumber, parameter);
}
}, 5000);
}
}
}
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.sp.androidesp8266wifi">
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".ServiceStatusUpdate"></service>
</application>
</manifest>
public void onClick(View view) {
[...]
Intent intent = newIntent("com.sp.androidesp8266wifi.ServiceStatusUpdate");
intent.putExtra("parameterValue", parameterValue);
intent.putExtra("ipAddress", ipAddress);
intent.putExtra("portNumber", portNumber);
intent.putExtra("parameter", parameter);
// execute HTTP request
if(ipAddress.length()>0 && portNumber.length()>0) {
startService(intent);
}