English 中文(简体)
服用每秒钟的 Android
原标题:Android run thread in service every X seconds

I want to create a thread in an Android service that runs every X seconds

I am currently using , but the postdelayed method seems to really lag out my app.

@Override
public int onStartCommand(Intent intent, int flags, int startId){

    super.onStartCommand(intent, flags, startId);

    startRepeatingTask();

    return startId;
}

private final static int INTERVAL = 20000; //20 milliseconds
Handler m_handler = new Handler();

Runnable m_handlerTask = new Runnable()
{
     @Override 
     public void run() {
         // this is bad
          m_handler.postDelayed(m_handlerTask, INTERVAL);
     }
};

void startRepeatingTask()
{
    m_handlerTask.run(); 
}

void stopRepeatingTask()
{
   m_handler.removeCallbacks(m_handlerTask);
   stopSelf();
}

我想做这样的新read子:

public void threadRun()
{
    Thread triggerService = new Thread(new Runnable(){
        public void run(){
            Looper.prepare();
            try{
                    //do stuff here?

            }catch(Exception ex){
                    System.out.println("Exception in triggerService Thread -- "+ex);
            }//end catch


        }//end run
    }, "aThread");
    triggerService.start();      

    //perhaps do stuff here with a timer?
    timer1=new Timer();

    timer1.scheduleAtFixedRate(new methodTODOSTUFF(), 0, INTERVAL);
}

I m not sure the best way to do a background thread to run at a certain interval, insight appreciated!

最佳回答
问题回答

在这里,我是如何重复的,因为你每秒钟就看到它。 我看不出这种方法。

final Thread t = new Thread(new RepeatingThread());
t.start();

并且:

import android.os.Handler;

public class RepeatingThread implements Runnable {

    private final Handler mHandler = new Handler();

    public RepeatingThread() {

    }

    @Override
    public void run() { 
        mHandler.postDelayed(this, 1000);       
    }
}

Myservice.java

public class MyService extends Service {

    public static final int notify = 5000;  //interval between two services(Here Service run every 5 seconds)
    int count = 0;  //number of times service is display
    private Handler mHandler = new Handler();   //run on another Thread to avoid crash
    private Timer mTimer = null;    //timer handling

    @Override
    public IBinder onBind(Intent intent) {
        throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    public void onCreate() {
        if (mTimer != null) // Cancel if already existed
            mTimer.cancel();
        else
            mTimer = new Timer();   //recreate new
        mTimer.scheduleAtFixedRate(new TimeDisplay(), 0, notify);   //Schedule task
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mTimer.cancel();    //For Cancel Timer
        Toast.makeText(this, "Service is Destroyed", Toast.LENGTH_SHORT).show();
    }

    //class TimeDisplay for handling task
    class TimeDisplay extends TimerTask {
        @Override
        public void run() {
            // run on another thread
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    // display toast
                    Toast.makeText(MyService.this, "Service is running", Toast.LENGTH_SHORT).show();
                }
            });

        }

    }
}

MainActative.java

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        startService(new Intent(this, MyService.class)); //start service which is MyService.java
    }
}

添加以下代码:AndroidManifest.xml

AndroidManifest.xml

<service android:name=".MyService" android:enabled="true" android:exported="true"></service>

开始<代码>可操作 几秒钟是,无论你如何lic,都有些滞后? 我看不出为什么有<代码>Handler的t工作只得罚款。

你们可能会遇到一些麻烦,因为你们有过。

void startRepeatingTask()
{
    m_handlerTask.run(); 
}

相反,你们应该利用残疾人,并做如下事情:

void startRepeatingTask()
{
    m_handler.post(m_handlerTask); 
}

(除此以外, Java公约将使用 came案件,而不是na案件。) 因此,它应当是mHandler,而不是m_handler,等等。 简单地告诉你,因为这可能会使你们的法典更容易阅读。





相关问题
Android - ListView fling gesture triggers context menu

I m relatively new to Android development. I m developing an app with a ListView. I ve followed the info in #1338475 and have my app recognizing the fling gesture, but after the gesture is complete, ...

AsyncTask and error handling on Android

I m converting my code from using Handler to AsyncTask. The latter is great at what it does - asynchronous updates and handling of results in the main UI thread. What s unclear to me is how to handle ...

Android intent filter for a particular file extension?

I want to be able to download a file with a particular extension from the net, and have it passed to my application to deal with it, but I haven t been able to figure out the intent filter. The ...

Android & Web: What is the equivalent style for the web?

I am quite impressed by the workflow I follow when developing Android applications: Define a layout in an xml file and then write all the code in a code-behind style. Is there an equivalent style for ...

TiledLayer equivalent in Android [duplicate]

To draw landscapes, backgrounds with patterns etc, we used TiledLayer in J2ME. Is there an android counterpart for that. Does android provide an option to set such tiled patterns in the layout XML?

Using Repo with Msysgit

When following the Android Open Source Project instructions on installing repo for use with Git, after running the repo init command, I run into this error: /c/Users/Andrew Rabon/bin/repo: line ...

Android "single top" launch mode and onNewIntent method

I read in the Android documentation that by setting my Activity s launchMode property to singleTop OR by adding the FLAG_ACTIVITY_SINGLE_TOP flag to my Intent, that calling startActivity(intent) would ...

From Web Development to Android Development

I have pretty good skills in PHP , Mysql and Javascript for a junior developer. If I wanted to try my hand as Android Development do you think I might find it tough ? Also what new languages would I ...

热门标签