2013-01-07 34 views
0

我有一個活動和服務。 該活動有一個TextView成員和一個setText()方法。 我想通過服務調用該方法,我該怎麼做? 下面是代碼:通過服務訪問活動

活動:

public class MainActivity extends Activity { 
    private TextView tv1; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
     this.tv1 = (TextView) findViewById(R.id.textView1); 
     Intent intent = new Intent(this,MyService.class); 
     startService(intent); 
    } 

    // <-- some deleted methods.. --> 

    public void setText(String st) { 
     this.tv1.setText(st); 
    } 
} 

服務:

public class MyService extends Service { 
    private Timer timer; 
    private int counter; 

    public void onCreate() { 
     super.onCreate(); 
     this.timer = new Timer(); 
     this.counter = 0; 
     startService(); 
    } 

    private void startService() { 
     timer.scheduleAtFixedRate(new TimerTask() { 
      public void run() { 
       //MainActivityInstance.setText(MyService.this.counter); somthing like that 
       MyService.this.counter++; 
       if(counter == 1000) 
        timer.cancel(); 
      } 
     },0,100); 
    } 

    @Override 
    public IBinder onBind(Intent arg0) { 
     return null; 
    } 
} 
+1

檢查此鏈接接收活動數據:http://stackoverflow.com/questions/10783688/android-access- activity-method-inside-service – secretlm

+0

非常感謝您的幫助。 –

回答

1

您可以使用意圖以任何信息(即櫃檯TextView的成員)發送到活動。

public void run() { 
    //MainActivityInstance.setText(MyService.this.counter); somthing like that 
    MyService.this.counter++; 
    Intent intentBroadcast = new Intent("MainActivity"); 
    intentBroadcast.putExtra("counter",MyService.this.counter); 
    sendBroadcast(intentBroadcast); 
    if(counter == 1000) 
    timer.cancel(); 
} 

...那麼,你將使用的廣播接收機

/** 
* Declares Broadcast Reciver for recive location from Location Service 
*/ 
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() { 
    @Override 
    public void onReceive(Context context, Intent intent) { 
     // Get data from intent 
     serviceCounter = intent.getIntExtra("counter", 0); 
     // Change TextView 
     setText(String.valueOf(counterService)); 
    } 
}; 
+0

由於某種原因,它不會調用onReceive方法 –

+0

對不起,您必須使用registerReceiver方法在活動中註冊Broadcast Receiver。 – jgonza73

+0

還記得當接收器不再需要時註銷它。 – jgonza73