我正在尝试实现一项服务来处理与服务器的通信以获取以下代码。我对这些设计架构知之甚少。
这是我的服务类
public class BgService extends Service {
private static final String TAG = BgService.class.getSimpleName();
private Timer timer;
SendJsonRequest sjr;
private TimerTask updateTask = new TimerTask(){
@Override
public void run(){
try{
SendJsonRequest sjr = new SendJsonRequest();
sjr.carMake();
Log.i(TAG, "LOOK AT ME");
}
catch(Exception e){
Log.w(TAG,e);
}
}
};
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
@Override
public void onCreate(){
super.onCreate();
Log.i(TAG, "Service creating");
timer = new Timer("Server listening timer");
timer.schedule(updateTask, 1000L, 60*1000L);
}
@Override
public void onDestroy(){
super.onDestroy();
Log.i(TAG, "Service Destroying");
timer.cancel();
timer = null;
}
}
这是我的SendJsonRequest类
public class SendJsonRequest{
private static final String TAG = "SendJsonRequest";
private static String URL = "xxxxxxxxx";
private static String infoRec;
public static void createJsonObj(String path, Map x){
infoRec = CreateJsonRequest.jsonRequest(URL+path, x );
System.out.println(infoRec);
}
public static void carMake(){
String path = "/CarMake";
Map<String, Object> z = new HashMap<String,Object>();
z.put("Name", "Ford");
z.put("Model", "Mustang");
createJsonObj(path, z);
}
}
这是我的CreateJsonObject类
public class CreateJsonRequest {
public static String jsonRequest(String URL, Map<String,Object> params){
try{
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(URL);
JSONObject holder = new JSONObject();
for (Map.Entry<String, Object> m : params.entrySet()){
try {
holder.put(m.getKey(), m.getValue());
}
catch (JSONException e) {
Log.e("Hmmmm", "JSONException : "+e);
}
}
StringEntity se;
se = new StringEntity(holder.toString());
httpPost.setEntity(se);
httpPost.setHeader("Accept", "text/json");
httpPost.setHeader("Content-type", "text/json");
HttpResponse response = (HttpResponse) httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
if(entity != null){
InputStream is = entity.getContent();
Header contentEncoding = response.getFirstHeader("Content-Encoding");
String result= convertToString(is);
is.close();
System.out.println(result);
return result;
}
}
catch(Exception e)
{
e.printStackTrace();
}
return null;
}
对于大量的代码感到抱歉。我如何实现我的服务显然是不正确的,我只是不知道从哪里开始获取服务处理服务器的json请求。提前谢谢。
更清楚一点,这确实适用于按钮点击,现在我正试图让它全部在后台运行该服务。所以我想我的问题是服务中的位置是什么?
我的活动成功启动了服务,该服务将工作并每分钟向logcat打印“看着我”。然后我添加了try{ sjr.carMake()}
,它捕获了一个异常。
答案 0 :(得分:0)
您可以使用广播接收器。这是让您的代码在Android操作系统指示的特定时间开始的一种方式 - 例如,您可以在Android完成启动时启动它(这是我经常运行我的服务的地方。
最好的方法是使用AlarmManager类,并告诉您的服务运行的频率。
告诉我们更多关于您正在尝试做什么,以及问题是什么,我们可以给您一个更简洁的答案......
<强>更新强>
您是否在该服务的manifest.xml文件中创建了一个条目?
<强>更新强> 这是我在我的应用程序中执行此操作的方式。这是操作系统的“挂钩”。当它完成引导时会触发它(不要忘记在清单中输入它!)
public class TmBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(final Context context, final Intent bootintent) {
try{
Log.i("Taskmotion-ROBOT", "Robot Broadcast signal received on Boot. Trying to start Alarm scheduler");
Intent mServiceIntent = new Intent(context, ServiceAlarm.class);
context.startService(mServiceIntent);
}
catch(Exception e)
{
Log.i("Taskmotion", "Failed to start service...");
}
}
}
此Broadcast接收器调用实现AlarmManager类的服务。警报管理器设置计划以指定的间隔运行我的服务。请注意,当手机关闭时会删除警报 - 但是当手机重新启动并再次运行BroadcastReceiver时,重复进程时会再次重新启动警报。
public class ServiceAlarm extends Service {
private PendingIntent mAlarmSender;
@Override
public void onCreate() {
try{
Log.i("Taskmotion-ROBOT", "Setting Service Alarm Step 1");
mAlarmSender = PendingIntent.getService(this.getApplicationContext(),
0, new Intent(this.getApplicationContext(), BackgroundService.class), 0);
}
catch(Exception e)
{
Log.i("Taskmotion-ROBOT", "Problem at 1 :" + e.toString());
}
long firstTime = SystemClock.elapsedRealtime();
Log.i("Taskmotion-ROBOT", "Setting Service Alarm Step 2");
// Schedule the alarm!
AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE);
am.setRepeating(AlarmManager.ELAPSED_REALTIME,
firstTime, AlarmManager.INTERVAL_HOUR, mAlarmSender);
this.stopSelf();
}
@Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
}
我还没有重构这段代码,这是我第一次尝试。我现在看到我再次看到它我可以在BroadcastReceiver中进行调度,但是为了让你得到有用的东西,我会继续。
如AlarmManager.INTERVAL_HOUR所示,我的服务将每小时运行一次。我想要运行的服务在pendingIntent(BackgroundService.class)中定义。这是您放置自己的服务类的地方。 我为您重新设计了服务类,并删除了计时器(由BroadcastReceiver&amp; AlarmManager取代的功能)。
public class BgService extends Service {
private static final String TAG = BgService.class.getSimpleName();
SendJsonRequest sjr;
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
@Override
public void onCreate(){
super.onCreate();
Log.i(TAG, "Service creating");
//DO YOUR WORK WITH YOUR JSON CLASS HERE
//**************************************
//Make sure to call stopSelf() or your service will run in the background, chewing up
//battery life like rocky mountain oysters!
this.stopSelf();
}
@Override
public void onDestroy(){
super.onDestroy();
}
}