2011-06-13 18 views
0

我有一个MyService命名的类,它扩展了下面的Service。一切都会一直运行到 我删除线程的run方法中的​​行。从Android的服务类的线程访问活动中的UI组件

为什么?我怎样才能从Thread类的run方法访问Activity组件?

public class MyService extends Service { 

@Override 
public IBinder onBind(Intent intent) { return null; } 

@Override 
public void onCreate() { 
    Toast.makeText(this, "This msg will be shown", Toast.LENGTH_LONG).show(); 
    Log.d("Bilgi", "This msg will be shown."); 
    super.onCreate(); 
} 

@Override 
public void onStart(Intent intent, int startId) { 
    Toast.makeText(this, "This msg will be shown", Toast.LENGTH_LONG).show(); 
    super.onStart(intent, startId); 

    timer.scheduleAtFixedRate(new TimerTask() { 
     @Override 
     public void run() { 
      try { 
       Log.d("This msg will ","be shown"); //if I remove next line 
       Toast.makeText(this, "This msg will NOT be shown", Toast.LENGTH_LONG).show(); 

       Thread.sleep(2000); 
      } catch (InterruptedException e) { 
       e.printStackTrace(); 
      } 
     } 
    }, 5000, 8000); 
} 

回答

1

和我如何可以从Thread类的run方法访问活动部件?

你不知道。使用MessengerMessage服务中的对象发送到活动的Handler。活动(仅限活动)可以更新其小部件,并且只能从主应用程序线程更新小部件。

Here is a sample application证明了这一点。

+0

能否通过[扩展binder类](https://developer.android.com/guide/components/bound-services.html#Binder)来使用绑定服务? Android文档似乎暗示了当“您的服务仅仅是您自己的应用程序的后台工作人员”时,使用'Messenger'的方法。 – AST 2016-07-26 13:38:32

+1

@AST:这将是另一种选择,就像事件总线一样。 – CommonsWare 2016-07-26 13:53:10

0

我所知道的唯一方法是使用广播接收器的活动里面,它捕捉任何你想要的信息并更新UI,或者你。

1

Don't use Threads - 使用AyncTasks。另外,您不应该通过线程/任务访问Activity方法/ UI。看看第一个链接,了解活动及其“线程”如何协同工作。

0

在创建吐司,通过在ApplicationContext中,您可以通过getApplicationContext得到()

+0

您的意思是,从Activity传递上下文给MyService,并将其作为Toa​​st.makeText(context.getApplicationContext(),“textextexte”,Toast.LENGTH_SHORT)参数传递给Context.getApplicationContext() .show();'? – uzay95 2011-06-13 16:04:31

+0

不,因为Service是Context的扩展,所以您可以在Service中调用getApplicationContext(); Toast.makeText(getApplicationContext()) – 2011-06-13 16:15:10

+0

在MyService类的OnStart方法中,第一个Toast.makeText方法正在工作,但是'timer.scheduleAtFixedRate(new TimerTask(){ @Override public void run(){ try {Toast。 makeText ....... ' – uzay95 2011-06-13 17:34:33

0

的UI组件不是线程安全的所以你不能更新UI部件,除非在主(UI)线程,你的情况,使得Toast是在另一个线程这是被禁止的。

您可能需要使用类似Handler的东西,并使用Messenger将消息发送到在活动UI线程中创建的处理程序。然后在方法handleMessage(Message msg)中处理小部件。