Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/218.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在Android上的后台线程上运行代码?_Android_Multithreading - Fatal编程技术网

如何在Android上的后台线程上运行代码?

如何在Android上的后台线程上运行代码?,android,multithreading,Android,Multithreading,我想要一些代码在后台连续运行。我不想在服务中这样做。还有别的办法吗 我已尝试在我的活动中调用线程类,但我的活动在后台保留了一段时间,然后停止。线程类也停止工作 class testThread implements Runnable { @Override public void run() { File file = new File( Environment.getExternalStorageDirectory(), "/BPCLTr

我想要一些代码在后台连续运行。我不想在服务中这样做。还有别的办法吗

我已尝试在我的
活动中调用
线程
类,但我的
活动
在后台保留了一段时间,然后停止。
线程
类也停止工作

class testThread implements Runnable {
        @Override
        public void run() {
            File file = new File( Environment.getExternalStorageDirectory(), "/BPCLTracker/gpsdata.txt" );
            int i = 0;

            RandomAccessFile in = null;

            try {
                in = new RandomAccessFile( file, "rw" );
            } catch (FileNotFoundException e) {
// TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
// TODO Auto-generated catch block
                e.printStackTrace();
            }
//String line =null;
            while ( true ) {
                HttpEntity entity = null;
                try {
                    if ( isInternetOn() ) {
                        while ( ( line = in.readLine() ) != null ) {

                            HttpClient client = new DefaultHttpClient();
                            String url = "some url";
                            HttpPost request = new HttpPost( url );
                            StringEntity se = new StringEntity( line );
                            se.setContentEncoding( "UTF-8" );
                            se.setContentEncoding( new BasicHeader( HTTP.CONTENT_TYPE, "application/json" ) );
                            entity = se;
                            request.setEntity( entity );
                            HttpResponse response = client.execute( request );
                            entity = response.getEntity();
                            i++;
                        }
                        if ( ( line = in.readLine() ) == null && entity != null ) {
                            file.delete();
                            testThread t = new testThread();
                            Thread t1 = new Thread( t );
                            t1.start();
                        }


                    } else {
                        Thread.sleep( 60000 );
                    } // end of else

                } catch (NullPointerException e1) {
                    e1.printStackTrace();
                } catch (InterruptedException e2) {
                    e2.printStackTrace();
                } catch (IOException e1) {
// TODO Auto-generated catch block
                    e1.printStackTrace();
                }
            }// end of while
        }// end of run

    }
我想要一些代码在后台连续运行。我不想要 在服务中这样做。还有别的办法吗

最有可能的是你正在寻找的机械。它直接指定在后台线程上执行后台进程。另外,它的主要优点是提供了一些在主(UI)线程上运行的方法,如果您想向用户通告任务的某些进展或使用从后台进程检索的数据更新UI,则可以更新UI

如果您不知道如何开始,这里有一个不错的教程:


注意:也可以与一起使用,这样也可以工作。

记住跑步背景,连续跑步是两个不同的任务

对于长期的后台进程,使用Android时线程不是最优的。然而,这里的代码,并做它在您自己的风险

请记住,服务或线程将在后台运行,但我们的任务需要触发(一次又一次调用)以获取更新,也就是说,一旦任务完成,我们需要调用函数进行下一次更新

定时器(周期触发器)、报警(时基触发器)、广播(事件基触发器)、递归将唤醒我们的函数。

public静态布尔值isRecursioneable=true;
void runInBackground(){
如果(!isRecursioneble)
//句柄不启动多个并行线程
返回;
//IsRecursonEnable=false;当您要停止时
//线程上的异常使其再次为真
新线程(newrunnable()){
@凌驾
公开募捐{
//你在这里工作吗
//获取数据
如果(活动在后台不是){
runOnUiThread(新的Runnable(){
@凌驾
公开募捐{
//更新用户界面
运行背景();
}
});
}否则{
运行背景();
}
}
}).start();
}
使用服务: 如果您启动一项服务,它将启动、执行该任务,并自行终止。在任务执行之后。终止也可能是由异常或用户从设置中手动终止异常引起的。 START_STICKY(STICKY Service)是android提供的选项,如果服务终止,服务将自动重启

还记得多处理和多线程之间的区别吗? 服务是一个后台进程(就像没有UI的活动一样), 与在活动中启动线程以避免在主线程(活动线程)上加载的方式相同,与在服务上启动线程(或异步任务)以避免在服务上加载的方式相同


在一条语句中,如果要运行后台继续任务,则需要启动StickyService并在基于事件的服务中运行线程

AsyncTask的替代方案是robospice

机器人世界的一些特征

1.异步(在后台AndroidService中)执行网络请求(例如:使用Spring Android的REST请求)。当结果就绪时,在UI线程上通知您的应用程序

2.是强类型的!您使用POJO发出请求,并获得POJO作为请求结果

3.对用于请求的POJO和您在项目中使用的活动类不实施任何约束

4.缓存结果(使用Json与Jackson和Gson,或Xml,或平面文本文件,或二进制文件,甚至使用ORM Lite)

5.当且仅当您的活动(或任何其他上下文)仍处于活动状态时,通知您的活动(或任何其他上下文)网络请求的结果

6.完全没有内存泄漏,就像Android Loader一样,不同于Android AsyncTasks在其UI线程上通知您的活动

7.使用简单但健壮的异常处理模型

首先是样品

如果您需要,请访问。

上的robospice示例:

  • 在后台线程上执行代码

  • 执行不接触/更新UI的代码

  • 执行(短)代码,最多需要几秒钟才能完成

  • 然后使用以下使用AsyncTask的干净高效的模式:

    AsyncTask.execute(new Runnable() {
       @Override
       public void run() {
          //TODO your background code
       }
    });
    

    如果需要使用不同的代码预先运行线程,示例如下:

    听众:

    public interface ESLThreadListener {
    
        public List onBackground();
    
        public void onPostExecute(List list);
    
    }
    
    螺纹类

    public class ESLThread extends AsyncTask<Void, Void, List> {
    
    
        private ESLThreadListener mListener;
    
        public ESLThread() {
    
            if(mListener != null){
    
                mListener.onBackground();
            }
        }
    
        @Override
        protected List doInBackground(Void... params) {
    
            if(mListener != null){
    
                List list = mListener.onBackground();
    
                return list;
            }
    
            return null;
        }
    
        @Override
        protected void onPostExecute(List t) {
            if(mListener != null){
    
                if ( t != null) {
                    mListener.onPostExecute(t);
                }
            }
    
        }
    
    
        public void setListener(ESLThreadListener mListener){
    
            this.mListener = mListener;
        }
    }
    
    public类ESLThread扩展异步任务{
    私人ESLTHREADLISTER mListener;
    公共阅读{
    if(mListener!=null){
    mListener.onBackground();
    }
    }
    @凌驾
    受保护列表doInBackground(无效…参数){
    if(mListener!=null){
    List=mListener.onBackground();
    退货清单;
    }
    返回null;
    }
    @凌驾
    受保护的void onPostExecute(列表t){
    if(mListener!=null){
    如果(t!=null){
    mListener.onPostExecute(t);
    }
    }
    }
    公共void setListener(ESLThreadListener mListener){
    this.mListener=mListener;
    }
    }
    
    运行不同的代码:

      ESLThread thread = new ESLThread();
                            thread.setListener(new ESLThreadListener() {
                                @Override
                                public List onBackground() {
                                    List<EntityShoppingListItems>  data = RoomDB.getDatabase(context).sliDAO().getSL(fId);
    
                                    return data;
    
                                }
    
                                @Override
                                public void onPostExecute(List t) {
    
                                    List<EntityShoppingListItems> data = (List<EntityShoppingListItems>)t;
                                    adapter.setList(data);
                                }
                            });
    
                            thread.execute();
    
    ESLThread thread=new ESLThread();
    setListener(新的ESLThreadListener(){
    @凌驾
    公共列表onBackground(){
    List data=RoomDB.getDatabase(context.sliDAO().getSL(fId);
    返回数据;
    }
    @凌驾
    公共voi
    
      ESLThread thread = new ESLThread();
                            thread.setListener(new ESLThreadListener() {
                                @Override
                                public List onBackground() {
                                    List<EntityShoppingListItems>  data = RoomDB.getDatabase(context).sliDAO().getSL(fId);
    
                                    return data;
    
                                }
    
                                @Override
                                public void onPostExecute(List t) {
    
                                    List<EntityShoppingListItems> data = (List<EntityShoppingListItems>)t;
                                    adapter.setList(data);
                                }
                            });
    
                            thread.execute();
    
    new Thread( new Runnable() { @Override public void run() { 
      // Run whatever background code you want here.
    } } ).start();