Android: start service with parameter

前端 未结 2 1980
情话喂你
情话喂你 2021-01-01 13:43

To start my service from an Activiy I use startService(MyService.class). This works great, but in a special case the service should be started differently. I wa

相关标签:
2条回答
  • 2021-01-01 13:57

    Step #1: Delete your BroadcastReceiver implementation.

    Step #2: Examine the Intent your service gets in onStartCommand() and look at the action via getAction().

    0 讨论(0)
  • 2021-01-01 14:09
    Intent serviceIntent = new Intent(this,ListenLocationService.class); 
    serviceIntent.putExtra("From", "Main");
    startService(serviceIntent);
    //and get the parameter in onStart method of your service class
    
    @Override
    public void onStart(Intent intent, int startId) {
        super.onStart(intent, startId);
        Bundle extras = intent.getExtras();
    
        if(extras == null) {
            Log.d("Service","null");
        } else {
            Log.d("Service","not null");
            String from = (String) extras.get("From");
            if(from.equalsIgnoreCase("Main"))
                StartListenLocation();
        }
    }
    
    0 讨论(0)
提交回复
热议问题