onStartCommand只在服务android中调用一次?

时间:2018-04-19 13:28:18

标签: android android-service

我有一个简单的服务需要在后台运行。下面是service.i的代码。我想重复运行onStartCommand中的代码只是为了测试目的我显示toast.but Toast也只调用一次

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只调用一次吐司。

我用过

return START_STICKY;

启动服务如下

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

但仍然没有用。任何帮助

3 个答案:

答案 0 :(得分:1)

如果再次开始服务

,将会两次调用Toast

e.g。

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

new IntentonStartCommand(Intent intent

中的意图

答案 1 :(得分:1)

简短回答

尽可能多地调用StartService来显示吐司。

关于返回START_STICKY(为什么不返回START_STICKY两次显示你的祝酒词?)

当您的服务 KILLED 时,START_STICKY方法结束时返回onStartCommand()可让您的服务重新开始(再次调用onStartCommand())(由于某些原因)像系统资源耗尽)。因此return START_STICKY;与您的目标之间存在无关联

达到目标的解决方案

就像Kalyzunyu的回答一样,只需拨打StartService()两次,就可以两次展示你的祝酒词。 它不会实例化您的服务两次,但会两次调用您的onStartService()。所以可以自由再次打电话。

参考here

如果您希望每隔10秒显示一次吐司,直到停止尝试。

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();
    }

}

以下代码与上述代码相同。

活动

    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;

        }
 }

要添加字词,启动服务意味着系统会重复调用,而是在没有用户界面的情况下更长寿。实际上,在您的服务上手动呼叫stopSelf()或任何组件呼叫stopService()之前,其上下文将一直持续。

答案 2 :(得分:-1)

是..,您只需返回START_STICKY作为KYHSGeekCode建议。它被投了票,但这是正确答案。所以我把它投了回来。谢谢