Android のバックグラウンド スレッドでコードを実行するにはどうすればいいですか? 質問する

Android のバックグラウンド スレッドでコードを実行するにはどうすればいいですか? 質問する

いくつかのコードをバックグラウンドで継続的に実行したいのですが、サービス内で実行したくありません。他に方法はあるでしょうか?

Thread自分のクラスを呼び出そうとしましたActivityが、Activityしばらくバックグラウンドに留まり、その後停止します。Threadクラスも動作を停止します。

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

    }

ベストアンサー1

もしあなたが必要ならば:

  1. バックグラウンドスレッドでコードを実行する

  2. UI を変更/更新しないコードを実行する

  3. 完了までに最大数秒かかる(短い)コードを実行する

次に、AsyncTask を使用する次のクリーンかつ効率的なパターンを使用します。

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

おすすめ記事