安卓:AsyncTask的使用AlarmManager和服务 [英] Android: AsyncTask with AlarmManager and Service

查看:120
本文介绍了安卓:AsyncTask的使用AlarmManager和服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要发布JSON字符串HttpURLConnection类API到本地主机服务器(WAMP)定期每60秒在数据库中插入。因此,我从计时器方法执行MyAsyncTask。会是更好的方法来实现,随着AlarmManager的帮助和服务,或者是足够的,我的目的?

我AP preciate任何帮助。

类的PostData:

 包com.bustracker;

    进口java.io.DataOutputStream中;
    进口java.io.IOException异常;
    进口java.net.HttpURLConnection中;
    进口的java.net.URL;

    进口android.os.AsyncTask;
    进口android.os.Handler;

        公共类{的PostData
            字符串jSONString;
            处理程序处理程序=新的处理程序();

            公众的PostData(字符串jSONString){
                超();
                this.jSONString = jSONString;
            }

            公共字符串getjSONString(){
                返回jSONString;
            }

            公共无效setjSONString(字符串jSONString){
                this.jSONString = jSONString;
            }

      公共无效定时器(){

    新主题(新的Runnable(){
        @覆盖
        公共无效的run(){
            布尔运行=真;
            而(运行){
               handler.postDelayed(新的Runnable(){
                   @覆盖
                   公共无效的run(){
                       新MyAsyncTask()执行(jSONString);
                   }
               },5000);
            }
        }
    })。开始();
}

            类MyAsyncTask扩展的AsyncTask<字符串,整数,太虚> {

                @覆盖
                保护无效doInBackground(字符串... PARAMS){
                    // TODO自动生成方法存根

                    尝试 {
                        //这是我的笔记本电脑无线上网的IP地址,因为我跑在我的设备中的应用程序,我想将数据发送到本地主机服务器(WAMP)。
                        URL myUrl =新的URL(http://192.168.127.56/webservice);
                        HttpURLConnection的MyConnection的=(HttpURLConnection类)myUrl
                                .openConnection();
                        myConnection.setRequestMethod(POST);
                        myConnection.setDoOutput(真正的);
                        myConnection.setUseCaches(假);
                        myConnection.setConnectTimeout(10000);
                        myConnection.setReadTimeout(10000);
                        myConnection.setRequestProperty(内容类型,
                                应用/ JSON);
                        myConnection.connect();
                        //创建数据输出流
                        DataOutputStream类WR =新DataOutputStream类(
                                myConnection.getOutputStream());
                        //写入字符串中的输出流
                        wr.writeBytes(jSONString);
                        wr.close();
                    }赶上(IOException异常E){

                        e.printStackTrace();
                    }
                    返回null;

                }

            }

        }
 

传递的JSON字符串的类的PostData:

  {
      纬度:41.86907321,
      东经:16.66542435,
      格式化:2015年4月22日11:11:00
       路线:4
    }
 

编辑:

这code是贝因从MainActivity的内部类MyLocationListern之称的onChanedLocation:

 字符串jSONString = convertToJSON(PLONG,开发平台,格式);
        发件人的PostData =新的PostData(jSONString);
        意图int​​ent3 =新的意图(MainActivity.this,PostData.class);
        PendingIntent pintent3 = PendingIntent.getService(getApplicationContext(),0,intent3,0);
        AlarmManager ALARM3 =(AlarmManager)getSystemService(Context.ALARM_SERVICE);
        日历CAL = Calendar.getInstance();
        // 30薄荷60 * 60 * 1000
        alarm3.setRepeating(AlarmManager.RTC_WAKEUP,cal.getTimeInMillis(),
                1000年,pintent3);

        startService(新意图(getBaseContext(),PostData.class));
 

与IntentService新类的PostData:

 包com.bustracker;

进口java.io.DataOutputStream中;
进口java.io.IOException异常;
进口java.net.HttpURLConnection中;
进口的java.net.URL;

进口android.app.IntentService;
进口android.content.Intent;
进口android.os.AsyncTask;
进口android.os.Handler;

公共类扩展的PostData {IntentService
    字符串jSONString;
    处理程序处理程序=新的处理程序();

    公众的PostData(字符串jSONString){
        超(一些);
        this.jSONString = jSONString;
    }

    公共字符串getjSONString(){
        返回jSONString;
    }

    公共无效setjSONString(字符串jSONString){
        this.jSONString = jSONString;
    }


    @覆盖
    公众诠释onStartCommand(意向意图,诠释标志,诠释startId){
        新MyAsyncTask()执行(jSONString);

        返回super.onStartCommand(意向,标志,startId);
    }
    @覆盖
    保护无效onHandleIntent(意向意图){
        // TODO自动生成方法存根

    }

    类MyAsyncTask扩展的AsyncTask<字符串,整数,太虚> {

        @覆盖
        保护无效doInBackground(字符串... PARAMS){
            // TODO自动生成方法存根

            尝试 {
                //这是我的笔记本电脑无线上网的IP地址,因为我跑在我的设备中的应用程序,我想将数据发送到本地主机服务器(WAMP)。
                URL myUrl =新的URL(HTTP://192.168.xx/webservice);
                HttpURLConnection的MyConnection的=(HttpURLConnection类)myUrl
                        .openConnection();
                myConnection.setRequestMethod(POST);
                myConnection.setDoOutput(真正的);
                myConnection.setUseCaches(假);
                myConnection.setConnectTimeout(10000);
                myConnection.setReadTimeout(10000);
                myConnection.setRequestProperty(内容类型,
                        应用/ JSON);
                myConnection.connect();
                //创建数据输出流
                DataOutputStream类WR =新DataOutputStream类(
                        myConnection.getOutputStream());
                //写入字符串中的输出流
                wr.writeBytes(jSONString);
                wr.close();
            }赶上(IOException异常E){

                e.printStackTrace();
            }
            返回null;

        }

    }



}
 

解决方案

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

 公共类ChatSevice扩展IntentService {

    公共ChatSevice(){
        超(有些);
    }



    @覆盖
    公众诠释onStartCommand(意向意图,诠释标志,诠释startId){
        // TODO自动生成方法存根

        //这是asynk任务等级
        新ChatConnect(ChatSevice.this).execute();

        返回super.onStartCommand(意向,标志,startId);
    }

    @覆盖
    保护无效onHandleIntent(意向意图){
        // TODO自动生成方法存根

    }




}
 

和现在调用这个服务像这样

 意图int​​ent3 =新的意图(这一点,ChatSevice.class);
        PendingIntent pintent3 = PendingIntent.getService(此,0,intent3,0);
        AlarmManager ALARM3 =(AlarmManager)getSystemService(Context.ALARM_SERVICE);
        // 30薄荷60 * 60 * 1000
        alarm3.setRepeating(AlarmManager.RTC_WAKEUP,cal.getTimeInMillis(),
                1000年,pintent3);

        startService(新意图(getBaseContext(),ChatSevice.class));
 

I want to post JSON string with HttpURLConnection api to the localhost server(WAMP) periodically every 60 seconds to be inserted in the database. Therefore, I am executing MyAsyncTask from the timer method. Would it be better approach to implement that with help of AlarmManager and Service or it is sufficient for my purposes?

I appreciate any help.

PostData class:

 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;

                }

            }

        }

The passed JSON string to the PostData class:

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

Edit:

this code is bein called in the onChanedLocation from the inner class "MyLocationListern" of the MainActivity:

        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));

The new PostData class with IntentService:

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;

        }

    }



}

解决方案

first we create a service like this

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

    }




}

and now call this service like this way

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));

这篇关于安卓:AsyncTask的使用AlarmManager和服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆