2017-02-27 12 views
0

サービスクラスMyServiceとそのメソッドMyMethod(クラスB(非アクティビティ)がインスタンス化され、クラスBのメソッドが呼び出される)があります。方法はトーストmsgを表示します。サービスクラスによって呼び出される非アクティビティクラスからtoastメッセージを表示

public class MyService extends Service { 

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

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

このトーストmsgの作り方を教えてください。

+0

。サービスはアクティビティと同じコンテキストです。 –

+1

は、コンテキストをmethodofB(コンテキストコンテキスト)に渡します。 –

+1

Toast.makeText(MyService.this.getApplicationConext()、My Text "、Toast.LENGHT_LONG).show()'を試してください。 –

答えて

0

MyService(Parentクラス)を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

Serviceのような非活動にあなたの活動のコンテキストを送信Contextのサブクラスです。したがって、我々はとクラス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(); 
    } 
} 
関連する問題