Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/201.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 显示服务类调用的非活动类中的toast msg_Android_Service_Toast - Fatal编程技术网

Android 显示服务类调用的非活动类中的toast msg

Android 显示服务类调用的非活动类中的toast msg,android,service,toast,Android,Service,Toast,我有一个服务类MyService和它的方法MyMethod,其中类B(非活动)被实例化,类B的方法被调用。该方法显示一个toast消息 public class MyService extends Service { public void MyMethod() { B b=new B(); b.methodOfB(); } Class B { void methodOfB(){ Toast(.....); } } 请告诉我如何制作这个烤面包味精 您可以将MyServi

我有一个服务类MyService和它的方法MyMethod,其中类B(非活动)被实例化,类B的方法被调用。该方法显示一个toast消息

public class MyService extends Service  {

  public void MyMethod() {
 B b=new B();
 b.methodOfB();
}

 Class B
 {
void methodOfB(){
 Toast(.....);
 }
 }
请告诉我如何制作这个烤面包味精

您可以将MyService(父类)扩展到它的B类(子类),然后您就可以轻松地使用Toast了。像这样:

public class MyService extends Service  {

  public void MyMethod() {
 B b=new B();
 b.methodOfB();
}

 Class B extends MyService
 {
void methodOfB(){
 Toast.makeText(this, "Your message here...", Toast.LENGTH_SHORT).show();
 }
 }

将活动的上下文发送到非活动,如

BMethod=new BMethod(MainActivity.this);

服务
上下文
的子类。因此,我们可以将其传递给类
B
,如下所示:

public class MyService extends Service  {

 public void MyMethod() {
    B b=new B(this);
    b.methodOfB();
}
B类有一个
上下文
参考:

 class B
 {
    private Context context;

    public B(Context context){
        this.context = context;
    }

    public void methodOfB(){

        //now create the toast message
        Toast.makeText(this.context, "Hello World!", Toast.LENGTH_LONG).show();
    }
 }

对于祝酒词,你需要一个上下文。服务是与活动相同的上下文。将上下文传递给methodofB(上下文上下文)Try
Toast.makeText(MyService.this.GetApplicationNext(),“My Text”,Toast.LENGHT\u LONG)。show()
。查看此问题并回答即可