开发者

Confused by Android Services

开发者 https://www.devze.com 2023-02-27 10:12 出处:网络
I\'ve read the documentation on Services thoroughly, but I\'m still completely confused as to how to use/code a service.

I've read the documentation on Services thoroughly, but I'm still completely confused as to how to use/code a service.

What I'm trying to accomplish: My main activity: The user selects all options for a timer and then clicks a button to start up a timer (in a service) with the click. I'm trying to pass the options to the service with putExtra.

The service will collect the variables into new variables for the service's use.

I have an onCreate section that calls my public counter which I've declared inside of the service, but not in the onCreate section. I've also declared all my variables that need to be enumerated from options being passed from the activity here.

Do I need to bind to the service to truely pass the variables with putExtra?

I have an onStart which is where I'm trying to enumerate the variable values by doing a series of gets. This is triggered by the button mentioned earlier in the activity. Inside of the activity - Ex:

mSet.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            //if toggled on
            if (mEnableDisable.isChecked()){
                getCurrentTime();
                //start passing our variables to the service
                Intent passvars = new Intent(getBaseContext(),TimerService.class);
                passvars.putExtra("mHour24", mHour24);
                     //start the service now
                     startService(new Intent(TimerService.class.getName()));
            }
        }
    });

Inside of the service - Ex:

public void onStart(Intent intent, int startId) {
     super.onStart(intent, startId);
     //Collecting data from Activity for calcs
     Bundle getvars = intent.getExtras();
     mHour24 = getvars.getInt("mHour24");
             //start the counter now that I have my values
             countDown.start();

}

Also if I can get the service to start without crashing I need to pass a value back to the activity. So I imagine I am doing that with putExtra in the service and getExtra in the activity. Once again, will I need to bind to the service to obtain the new values?

To bind if I need to I would do this on the button press. I would also add in a section to the main activity if the program exits, but then resumes to re-bind and collecting that value. The value I'm trying to pull is the time remaining from the counter. So inside of the counter service I would have an onTick put the remaining time into a variable and do a putExtra of that variable, where in the activity I want to collect that value and display it in the UI.

This is my first service attempt and I'm just not sure how to create and use properly. Thanks in advance for all the help and sorry for such a long convoluted post.

UPDATE: So I have the service working now. I'm just having trouble getting information back from the service to the main activity.

I have added a function to try and retrieve the data from the service which is launched after the button click launches the service:

startService(passvars);
                //Init. variable for getDisplayInf() function to update the display with counter strings
                Running = 1;
                getDisplayInf();

And the getDisplayInf() ex:

public void getDisplayInf() {
        //Intent stIntent = new Intent(MainActivity.this,MainActivity.class);
        //Intent passvars = new Intent(MainActivity.this,Service.class);
        Bundle getvars = getIntent().getExtras();
        String Remaining;
        String CountDown;
        do {
            Remaining = getvars.getString("Remaining");
            CountDown = getvars.getString("CountDown");
            mRemaining.setText(Remaining);
            mCountDown.setText(CountDown);
            Running = getvars.getInt("Running");
        }
        while (Running == 1);
    };

The timer will set the Running variable to 0 on finish. As soon as I click the button with this new function in place is crashes the app.

In the service I'm doing this on the counter's onTick:

            @Override
        public void onTick(long millisUntilFinished) {
            Running = 1;
            Remaining = "Time Remaining:  ";
            CountDown = formatTime(millisUntilFinished);
            ticker();
        }

ticker's code:

public void ticker () {
         Intent passvars = new Intent(Service.this,MainActivity.class);
        //this is for the activity to keep looping to grab the countdown values while run开发者_开发知识库ning this timer

        //now send it to the activity
        passvars.putExtra("Running", Running);
        //String Values to be passed to the activity

        //now send it to the activity
        passvars.putExtra("mRemaining", Remaining);


        //now send it to the activity
        passvars.putExtra("mCountDown", CountDown);
     };


Try starting your service with the passvars Intent rather than creating a new second intent:

Intent passvars = new Intent(MainActivity.this,TimerService.class);
passvars.putExtra("mHour24", mHour24);
//start the service now
startService(passvars);


If your Activity wants to get a value back from your Service you have a couple of choices:

  1. Send an Intent from the Activity to the Service and get the result asynchronously using a ResultReceiver. The link given here by Claszen is excellent.

  2. Use Binder. You can make a synchronous call that returns with the result.

  3. Implement a Content Provider. This choice is for making your own data retrieval and storage component.


I realized I could obtain the amount of awareness that I wanted for the user by using the Notification Manager. So I implemented the notification manager and displayed my countdown information onTick() there.

The reason this worked best for me was because my service is technically a remote service (setup to run in its own process, which is defined in the manifest file.) It is far more complex to connect to a remote service and obtain data synchronously (which is what I wanted.) The notification manager option actually worked best for me here, as the program docks it's icon and updates the notification on each second.

0

精彩评论

暂无评论...
验证码 换一张
取 消