简体   繁体   中英

how to call a service from an activity?

I have a service which starts an activity by

                Intent dialogIntent = new Intent(getBaseContext(), dialog.class);
                dialogIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                getApplication().startActivity(dialogIntent);

But I'm not sure how to pass a call when this new activity finishes to the service?

Note that "startActivityForResult" does not work from a service. ;)

On the other hand, maybe there is some "when focus comes back" listener for the service?

Thanks!

edit:

activity finishes by

Intent dialogIntent = new Intent(getBaseContext(), TotalKeyboard.class);
dialogIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
getApplication().startActivity(dialogIntent);

finish();

yet this, in service, doesn't get the call

     @Override public void onStart(Intent intent, int startid)
     {
         Toast.makeText(getApplicationContext(), "aaa!", Toast.LENGTH_SHORT).show();
     }

当您尝试start service already running start service ,它的onCreate方法无法获取调用,但是它的onStart()方法却可以获取调用...您可以使用此属性来满足您的需要...

You never get foucs on a Service . I'm not sure what you are trying to achieve, and maybe this is not the best solution but you can bound from you Activity to the Service and declare a method in your Service class and then you can call that method from your Activity , after you are bound to your service.

EDIT: You can simulate a dialog show from a Service by creating an Activity that looks like a dialog. You can do this by setting the theme attribute in your AndroidManifest.xml :

   <activity
        android:name="myPackages.ui.DialogActivity"
        android:theme="@android:style/Theme.Dialog"
        android:launchMode="singleInstance"
        android:excludeFromRecents="true"
        android:finishOnTaskLaunch="true" />

You can declare a method in your Service let's say:

   public void performAction(boolean userChoice){
        //implementation
   }

and in your DialogActivity class you can bound to your Service class and on the press of a button you can call :

  mBoundService.performAction(true);

or

  mBoundService.performAction(false);

based on the user choice.

简而言之,Activity本身必须照顾这一点。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM