2017-02-27 81 views
0

我有一個服務類別MyService及其方法MyMethod,其中類別B(非活動)被實例化並且類別B的方法被調用。該方法顯示吐司味精從服務類別調用的非活動類別中顯示吐司味精

public class MyService extends Service { 

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

Class B 
{ 
void methodOfB(){ 
Toast(.....); 
} 
} 

請告訴如何使這個祝酒消息工作。

+0

的敬酒你需要一個語境。服務與活動相同。 –

+1

將上下文傳遞給methodofB(Context context) –

+1

嘗試'Toast.makeText(MyService.this.getApplicationConext(),「My Text」,Toast.LENGHT_LONG).show()'。 –

回答

0

您可以將MyService(父類)擴展到它的B類(Child類),然後可以輕鬆使用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(); 
} 
} 
0

將您的活動的背景下,非活動像

BMethod=new BMethod(MainActivity.this); 
0

ServiceContext一個子類。因此,我們可以把它傳遞給類B爲:

public class MyService extends Service { 

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

和B類有一個Context基準爲:

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(); 
    } 
}