我正在尝试定期将电池信息发送到我的服务器。我已经测试了 web 服务代码,它在不使用 Android 服务的情况下工作正常,但是当我尝试在服务中的可运行内调用 web 服务方法时抛出异常。
虽然当我尝试在我的 Android 服务中运行可运行的 Toast 时它工作正常。
package com.services;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Handler;
import android.os.IBinder;
import android.widget.Toast;
public class BackService extends Service {
private int m_interval = 20000; // 5 seconds by default, can be changed later
private Handler m_handler;
int Level;
private static final String SOAP_ACTION = "http://xy.xy/insertfeedback";
private static final String METHOD_NAME = "insertfeedback";
private static final String NAMESPACE = "http://xy.xy/";
private static final String URL = "http://192.168.9.2:8080/WebApplication2/NewWebServiceService?WSDL";
SoapObject request;
SoapSerializationEnvelope envelope;
HttpTransportSE ht;
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
Toast.makeText(getApplicationContext(), "Service Created", Toast.LENGTH_SHORT).show();
request= new SoapObject(NAMESPACE, METHOD_NAME);
envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
ht = new HttpTransportSE(URL);
}
@Override
public void onDestroy() {
//code to execute when the service is shutting down
}
@Override
public void onStart(Intent intent, int startid) {
registerReceiver(this.mBatInfoReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
Toast.makeText(getApplicationContext(), "Service Stared", Toast.LENGTH_SHORT).show();
m_handler = new Handler();
m_statusChecker.run();
}
Runnable m_statusChecker = new Runnable()
{
@Override
public void run() {
Toast.makeText(getApplicationContext(), ""+ Level, Toast.LENGTH_SHORT).show();
BatteryService();
//updateStatus(); //this function can change value of m_interval.
m_handler.postDelayed(m_statusChecker, m_interval);
}
};
private final BroadcastReceiver mBatInfoReceiver = new BroadcastReceiver(){
@Override
public void onReceive(Context arg0, Intent intent) {
Level = intent.getIntExtra("level", 0);
//Toast.makeText(getApplicationContext(), ""+Level+"%", Toast.LENGTH_SHORT).show();
}
};
public void BatteryService()
{
request.addPropertyIfValue("value",50);
envelope.setOutputSoapObject(request);
try
{
ht.call(SOAP_ACTION, envelope);
final SoapPrimitive response = (SoapPrimitive)envelope.getResponse();
final String str = response.toString();
Toast.makeText(getApplicationContext(), str, Toast.LENGTH_LONG).show();
}
catch (Exception e) {
Toast.makeText(getApplicationContext(),"Exception", Toast.LENGTH_LONG).show();
}
}
}