Android: Passing variables to an already running service

前端 未结 2 1950
情话喂你
情话喂你 2021-02-19 04:29

I am having issues passing a value from an Activity to an already running service. I was wondering what the best approach to take would be? Adding extras wont work as I believe

2条回答
  •  渐次进展
    2021-02-19 04:47

    pass intent extra to service from activity start this intent if service is running try this from activity and pass param with putExtra.

    Intent rc = new Intent(getApplicationContext(), myService.class);
    rc.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); //important for Android 10
    rc.putExtra("parama","ciao");
    rc.putExtra("paramb","hello");
    startService(rc);
    

    Remember, new thread, exit to main Thread.

    new Thread(){
        @Override
            public void run() {
                super.run();
                //start service..
            }    
    }
    

    your service

     public class myService extends Service {
                   @Override
                    public int onStartCommand(Intent intent, int flags, int startId) {
                    if (intent.hasExtra("parama")){            
                    Bundle b=new Bundle();
                    b=intent.getExtras();
                    String par_a=b.getString("parama");
                    }
                    if (intent.hasExtra("paramb")){            
                    Bundle b=new Bundle();
                    b=intent.getExtras();
                    String par_b =b.getString("paramb");
                    }
            }
        }
    

提交回复
热议问题