Android - 使用多个线程执行不同的功能

时间:2014-09-30 17:04:49

标签: java android multithreading service timer

我对Android编程很陌生,但在其他语言方面有一些经验。我想创建一个像这样的原理工作的APP。

enter image description here

  1. APP是一个过程,如果有要执行的事件,则每10秒询问一次我的Web /数据库服务器。

  2. Web- / Database-Server以事件ID或函数名称回答。

  3. APP打开一个新线程,该线程使用id执行事件,甚至更好地直接执行函数名称。
  4. 我的问题是:

    1. 这是性能吗?或者这可以很容易地发生冲突吗?
    2. 是否仅限于进程中的2个线程,或者每次我想要执行的函数的新线程都可以打开?也许是因为其他功能还在运行?
    3. 如何使用返回值执行函数?例如

      InputStream in = response.getEntity().getContent(); //Get the data in the entity

      public in(void) { // execute a function which got´s the same name as the variable "in" }

    4. 结果应该是:如果有事件,一个线程每10秒询问一次我的Web- / Database-Server。事件在一个线程中执行,这是并行的(同时没有崩溃甚至被卡住)。

      这些主题的示例代码将不胜感激。

      直到我的代码:

        

      公共类服务扩展服务{       private static final String TAG =" MyService&#34 ;;

      @Override
      public IBinder onBind(Intent intent) 
      {
          return null;
      }
      
      public void onDestroy() 
      {
          Toast.makeText(this, "My Service Stopped", Toast.LENGTH_LONG).show();
          Log.d(TAG, "onDestroy");
      }
      
      @Override
      public int onStartCommand(Intent intent, int flags, int startid)
      {
      
          Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG).show();
          Log.d(TAG, "onStart");
      
          Thread thread = new Thread(new Runnable()
          {
            @Override
            public void run()
            {
               new Timer().scheduleAtFixedRate(new TimerTask() 
               {
                @Override
                  public void run() 
                {
                           System.out.println("Send GO!");
                           Device dev = new Device();
      
                           dev.getDeviceId(getBaseContext());
                           dev.getEmail(getBaseContext());
      
                           dev.sendDeviceItems();
                         }
                     }, 0, 10000);//put here time 1000 milliseconds=1 second
                }
                });
      
          thread.start();   
          return Service.START_STICKY;
         } }
      

1 个答案:

答案 0 :(得分:2)

  1. 这是性能吗?或者这可以很轻松地哼唱?
    • 是的,它会受到性能影响。每10秒钟要求一次api也会耗尽你的电池。
    • 通过适当的异常处理,它不会轻易崩溃。
  2. 它是否仅限于进程中的2个线程,或者每次我想要执行的函数的新线程时都可以打开?也许是因为其他功能还在运行?

    • 你可以运行你想要的多个线程但是很难维护代码  案件 。您可以使用VOLLY或OKHTTP来处理与线程相关的网络相关内容  部分也。

    如何使用返回值执行函数?例如

    InputStream in = response.getEntity()。getContent();  //获取实体中的数据

    public in(void)  {  //执行一个与变量“in”同名的函数  }

    • 要在运行时使用方法名称调用方法,您只需在java中使用REFLECTION即可。这将满足您的需求。