我是 Android 的初学者,我正在创建 android 应用程序,与 Siemens PLC 的通信工作正常,但如果我单击按钮仅显示 android 中显示的数据,我想在服务中运行此代码我不知道如何添加代码(下面)在服务中
protected String doInBackground(String... strings) {
try{
client.SetConnectionType(S7.S7_BASIC);
int res = client.ConnectTo("10.0.2.2",0,1);
if(res == 0)
{
byte[] data = new byte[4];
res = client.ReadArea(S7.S7AreaDB,1,0,2,data);
ret = "Values "+S7.GetWordAt(data,0);
}
else {
ret = "Err:"+S7Client.ErrorText(res);
}
client.Disconnect();
}
catch (Exception e)
{
ret= "Exe"+e.toString();
Thread.interrupted();
}
return "Executed";
}
上面的代码工作正常,但是这个代码添加到服务我创建了一个服务
public class MyService extends Service {
S7Client client = new S7Client();
String ret = "";
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
PlcReader task=new PlcReader();
task.execute("");
return START_NOT_STICKY;
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
public class PlcReader extends android.os.AsyncTask<String,Void,String>{
@Override
protected String doInBackground(String... strings) {
try{
client.SetConnectionType(S7.S7_BASIC);
int res = client.ConnectTo("10.0.2.2",0,1);
if(res == 0)
{
byte[] data = new byte[4];
client.ReadArea(S7.S7AreaDB,1,0,4,data);
ret = "Values "+S7.GetWordAt(data,0);
}
else {
ret = "Err:"+S7Client.ErrorText(res);
}
client.Disconnect();
}
catch (Exception e)
{
ret= "Exe"+e.toString();
Thread.interrupted();
}
return "Executed";
}
@Override
protected void onPostExecute(String s) {
Toast.makeText(getApplicationContext(),ret,Toast.LENGTH_LONG).show();
}
}
我添加了带有服务的代码,但显示连接问题