本文介绍了onStartCommand在服务Android中仅调用一次?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的服务需要在后台运行.下面是该服务的代码.我只想出于测试目的就重复在onStartCommand中运行该代码,但我却显示了toast.但是Toast也只调用了一次

i have a simple service need to run in background.below is the code for the service.i want to run the code in onStartCommand repeatedly simply for test purpose i displayed toast.but Toast also calling only once

import android.app.IntentService;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.net.wifi.WifiManager;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.support.annotation.Nullable;
import android.util.Log;
import android.widget.Toast;




/**
 * An {@link IntentService} subclass for handling asynchronous task requests in
 * a service on a separate handler thread.
 * <p>
 * TODO: Customize class - update intent actions and extra parameters.
 */
public class WiFiCheck extends Service {




    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // Let it continue running until it is stopped.


        Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();


        return super.onStartCommand(intent, flags, startId);

    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }



    /**
     * Handle action Foo in the provided background thread with the provided
     * parameters.
     */
    private void handleActionFoo(String param1, String param2) {
        // TODO: Handle action Foo
        throw new UnsupportedOperationException("Not yet implemented");
    }

    /**
     * Handle action Baz in the provided background thread with the provided
     * parameters.
     */
    private void handleActionBaz(String param1, String param2) {
        // TODO: Handle action Baz
        throw new UnsupportedOperationException("Not yet implemented");
    }
}

但是onStartCommand只调用一次,只有一次烤面包.

but onStartCommand is calling only once getting toast only once.

我用过

return START_STICKY;

如下所示启动服务

        startService(new Intent(this, WiFiCheck.class));

但仍然没有用.任何帮助

but still no use.any help

推荐答案

简短答案

拨打StartService电话的次数要多于您希望吐司面包出现的时间.

Call StartService as much times as you want the toast to show up.

关于返还START_STICKY(为什么不返还START_STICKY却要两次烤面包?)

onStartCommand()方法末尾返回START_STICKY可使服务重新启动(onStartCommand()再次调用)(onStartCommand())(由于某些原因,例如系统资源耗尽).因此,return START_STICKY;与您的目标之间没有任何关联.

Returning START_STICKY at the end of onStartCommand() method lets your service start again(onStartCommand() is called again) when your service is KILLED(by some reasons like system resource depletion). So there is no relevence between return START_STICKY; and your goal.

达成目标的解决方案

就像Kalyzunyu的答案一样,只需拨两次StartService()两次就可以了. 它不会两次实例化您的服务,但是会两次调用您的onStartService().因此,请再次调用它.

Like the Kalyzunyu's answer, just call StartService() twice to show your toast twice. It does not instantiate your Service twice, but calls your onStartService() twice. So be free to call it again.

此处进行引用.

或者,如果您想每10秒钟显示一次烤面包,直到停止,请尝试一下.

Or if you want to show the toast every 10 seconds until it is stopped try this.

public class WiFiCheck extends Service
{

    private Thread thread;




    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // Let it continue running until it is stopped.
        startForeground(1, new Notification());
        thread=new Thread(new Runnable(){

                @Override
                public void run()
                {
                    // TODO: Implement this method
                    while(true)
                    {
                        Toast.makeText(WiFiCheck.this, "Service Started", Toast.LENGTH_LONG).show();
                        try
                        {
                            Thread.sleep((long)10000);
                        }
                        catch (InterruptedException e)
                        {}
                    }


                }
            });
            thread.start();
        Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();


        return super.onStartCommand(intent, flags, startId);

    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }



    /**
     * Handle action Foo in the provided background thread with the provided
     * parameters.
     */
    private void handleActionFoo(String param1, String param2) {
        // TODO: Handle action Foo
        throw new UnsupportedOperationException("Not yet implemented");
    }

    /**
     * Handle action Baz in the provided background thread with the provided
     * parameters.
     */
    private void handleActionBaz(String param1, String param2) {
        // TODO: Handle action Baz
        throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    public void onDestroy()
    {
        // TODO: Implement this method
        thread.stop();
        super.onDestroy();
    }

}

下面的代码等同于上面的代码.

This code below is equivalant to above.

活动中

    new Thread(new Runnable()
        {
             @Override
             public void run()
             {
                   while(!isInterrupted()){
startService(new Intent(MainActivity.this, WiFiCheck.class));
                       Thread.sleep(10000L);
                   }
             }
        }).start();

等效代码2:

public class WiFiCheck extends IntentService
{
  public WiFiCheck() {
     super("WiFiCheck");
 }
 @Override
 protected void onHandleIntent(Intent intent)
 {
Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();

 }
@Override
        public int onStartCommand(Intent intent, int flags, int startId) {
            // Let it continue running until it is stopped.
            startForeground(1, new Notification());
            Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();

       super.onStartCommand(intent, flags, startId);
      return START_STICKY;

        }
 }

要添加单词,启动服务并不会不是,这意味着系统会反复调用它,但是它可以在没有UI的情况下存活更长的时间.实际上,它的上下文一直持续到您在服务上手动调用stopSelf()或任何组件调用stopService()为止.

To add words, starting a service does not mean it is repeatedly called by the system, but rather it can live longer without UI. Actually its context is continued until you manually call stopSelf() or any component calls stopService() on your service.

这篇关于onStartCommand在服务Android中仅调用一次?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-29 20:16