Android:带有AlarmManager和Service的AsyncTask

Android:带有AlarmManager和Service的AsyncTask,第1张

概述我想每隔60秒定期使用HttpURLConnectionapi将JSON字符串发布到localhost服务器(WAMP),以将其插入数据库中.因此,我正在从计时器方法执行MyAsyncTask.在AlarmManager和Service的帮助下实现该方法是更好的方法,还是足以满足我的目的?感谢您的帮助.PostData类:packagecom.bustrac

我想每隔60秒定期使用httpURLConnection API将JSON字符串发布到localhost服务器(WAMP),以将其插入数据库中.因此,我正在从计时器方法执行MyAsyncTask.在AlarmManager和Service的帮助下实现该方法是更好的方法,还是足以满足我的目的?

感谢您的帮助.

PostData类:

 package com.bustracker;    import java.io.DataOutputStream;    import java.io.IOException;    import java.net.httpURLConnection;    import java.net.URL;    import androID.os.AsyncTask;    import androID.os.Handler;        public class PostData {            String JsONString;            Handler handler = new Handler();            public PostData(String JsONString) {                super();                this.JsONString = JsONString;            }            public String getJsONString() {                return JsONString;            }            public voID setJsONString(String JsONString) {                this.JsONString = JsONString;            }      public voID timer() {    new Thread(new Runnable() {        @OverrIDe        public voID run() {            boolean run = true;            while (run) {               handler.postDelayed(new Runnable() {                   @OverrIDe                   public voID run() {                       new MyAsyncTask().execute(JsONString);                   }               }, 5000);            }        }    }).start();}            class MyAsyncTask extends AsyncTask<String, Integer, VoID> {                @OverrIDe                protected VoID doInBackground(String... params) {                    // Todo auto-generated method stub                    try {                        //This is the ip address of my laptop wifi because I am running the app in my device and I want to send the data to the localhost server(WAMP).                         URL myUrl = new URL("http://192.168.127.56/webservice");                         httpURLConnection myConnection = (httpURLConnection) myUrl                                .openConnection();                        myConnection.setRequestMethod("POST");                        myConnection.setDoOutput(true);                        myConnection.setUseCaches(false);                        myConnection.setConnectTimeout(10000);                        myConnection.setReadTimeout(10000);                        myConnection.setRequestProperty("Content-Type",                                "application/Json");                        myConnection.connect();                        // create data output stream                        DataOutputStream wr = new DataOutputStream(                                myConnection.getoutputStream());                        // write to the output stream from the string                        wr.writeBytes(JsONString);                        wr.close();                    } catch (IOException e) {                        e.printstacktrace();                    }                    return null;                }            }        }

传递给PostData类的JsON字符串:

    {      "latitude":41.86907321,      "longitude":16.66542435,      "formatted":"22.04.2015 11:11:00",       "route":4    }

编辑:

该代码在MainActivity的内部类“ MyLocationListern”的onChanedLocation中被调用:

        String JsONString = convertToJsON(pLong, pLat, formatted);        PostData sender = new PostData(JsONString);                     Intent intent3 = new Intent(MainActivity.this, PostData.class);        PendingIntent pintent3 = PendingIntent.getService(getApplicationContext(), 0, intent3, 0);        AlarmManager alarm3 = (AlarmManager) getSystemService(Context.ALARM_SERVICE);        Calendar cal = Calendar.getInstance();        // for 30 mint 60*60*1000        alarm3.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),                1000, pintent3);        startService(new Intent(getBaseContext(), PostData.class));

具有IntentService的新PostData类:

package com.bustracker;import java.io.DataOutputStream;import java.io.IOException;import java.net.httpURLConnection;import java.net.URL;import androID.app.IntentService;import androID.content.Intent;import androID.os.AsyncTask;import androID.os.Handler;public class PostData extends IntentService {    String JsONString;    Handler handler = new Handler();    public PostData(String JsONString) {        super("some");        this.JsONString = JsONString;    }    public String getJsONString() {        return JsONString;    }    public voID setJsONString(String JsONString) {        this.JsONString = JsONString;    }    @OverrIDe    public int onStartCommand(Intent intent, int flags, int startID) {        new MyAsyncTask().execute(JsONString);        return super.onStartCommand(intent, flags, startID);    }    @OverrIDe    protected voID onHandleIntent(Intent intent) {        // Todo auto-generated method stub    }    class MyAsyncTask extends AsyncTask<String, Integer, VoID> {        @OverrIDe        protected VoID doInBackground(String... params) {            // Todo auto-generated method stub            try {                //This is the ip address of my laptop wifi because I am running the app in my device and I want to send the data to the localhost server(WAMP).                 URL myUrl = new URL("http://192.168.x.x/webservice");                 httpURLConnection myConnection = (httpURLConnection) myUrl                        .openConnection();                myConnection.setRequestMethod("POST");                myConnection.setDoOutput(true);                myConnection.setUseCaches(false);                myConnection.setConnectTimeout(10000);                myConnection.setReadTimeout(10000);                myConnection.setRequestProperty("Content-Type",                        "application/Json");                myConnection.connect();                // create data output stream                DataOutputStream wr = new DataOutputStream(                        myConnection.getoutputStream());                // write to the output stream from the string                wr.writeBytes(JsONString);                wr.close();            } catch (IOException e) {                e.printstacktrace();            }            return null;        }    }}

解决方法:

首先,我们创建这样的服务

public class ChatSevice extends IntentService{    public ChatSevice() {        super("Some");    }    @OverrIDe    public int onStartCommand(Intent intent, int flags, int startID) {        // Todo auto-generated method stub        //this is asynk task class        new ChatConnect(ChatSevice.this).execute();        return super.onStartCommand(intent, flags, startID);    }    @OverrIDe    protected voID onHandleIntent(Intent intent) {        // Todo auto-generated method stub    }}

现在以这种方式调用此服务

Intent intent3 = new Intent(this, ChatSevice.class);        PendingIntent pintent3 = PendingIntent.getService(this, 0, intent3, 0);        AlarmManager alarm3 = (AlarmManager) getSystemService(Context.ALARM_SERVICE);        // for 30 mint 60*60*1000        alarm3.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),                1000, pintent3);        startService(new Intent(getBaseContext(), ChatSevice.class));
总结

以上是内存溢出为你收集整理的Android:带有AlarmManager和Service的AsyncTask全部内容,希望文章能够帮你解决Android:带有AlarmManager和Service的AsyncTask所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1093437.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-28
下一篇 2022-05-28

发表评论

登录后才能评论

评论列表(0条)

保存