2013-02-23 41 views
1

主要活动有一个AlarmManager,每X分钟调用一次服务。我需要一种方法,即服务类中的方法可以更新主活动中的TextView,但我不知道如何获取服务中的TextView对象。有什么办法吗?从服务中获取活动的小部件

下面是部分代码:

Intent myIntent = new Intent(MainActivity.this, MyAlarmService.class); 
pintent = PendingIntent.getService(MainActivity.this, 0, myIntent, 0); 

AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE); 
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 60000, pintent); 

回答

0

在您的报警服务,你有一个的onReceive方法

public void onReceive(Context context, Intent arg1) { 

     String data = "haha"; 
     if (data.isEmpty() == false && data.contentEquals("") == false) { 

      nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); 
      CharSequence from = "sing"; 
      CharSequence message = data; 
        //get the activity 
      PendingIntent contentIntent = PendingIntent.getActivity(context, 0, 
        new Intent(), 0); 
      Notification notif = new Notification(R.drawable.icon, 
        data, System.currentTimeMillis()); 
      notif.defaults |= Notification.DEFAULT_SOUND; 
      notif.setLatestEventInfo(context, from, message, contentIntent); 
      nm.notify(1, notif); 

     } 

方法调用:

AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE); 
     Intent intent = new Intent(this, ReminderReceiverActivity.class); 
     PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, 
       intent, PendingIntent.FLAG_CANCEL_CURRENT); 

     am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 
       100000, pendingIntent); 
    } 
0

我有同样的需求,在一个加速计读取服务和一个应用程序,将启动/停止服务,并显示当前的平均加速度计r量级。

我使用服务绑定来允许服务发送消息给包含加速度计值的活动。

请参阅http://developer.android.com/guide/components/bound-services.html#Messenger关于绑定的背景。例如,请参阅API示例的MessengerServiceActivities和MessengerService类。

我做了以下事情。为了清楚起见,我忽略了一些平凡的细节(例如同步以避免竞争)。请注意,我使用bind()以及StartService()。 bind()用于在Activity和Service之间发送消息; StartService()是这样的,服务在Activity退出后继续运行。

基本上,活动和服务交换信使将允许每个发送消息到另一个。该活动将自定义消息发送到服务以订阅服务消息或取消订阅服务消息。当服务想要将数据发送到活动时,它将自定义消息发送到活动的Messenger。该活动在接收到这样的消息时向用户显示新值。

建议使用通知的答案使用一种简单的方法将数据获取到屏幕上。如果您想在活动中显示数据(与通知栏相比),则需要更复杂的消息传递答案。

对于以下示例代码的长度,我表示歉意,但有很多必要的细节需要传达。

在我的活动,名为AccelServiceControl:

private FromServiceHandler handler; // My custom class for Handling Messages from my Service. 
private Messenger fromService; // For receiving messages from our Service 
... 
public void onCreate(Bundle savedInstanceState) { 
    ... 
    handler = new FromServiceHandler(this); 
    fromService = new Messenger(handler); 
    ... 
} 
protected void onResume() { 
    ... 
    // While we're in the foreground, we want to be bound to our service. 
    // onServiceConnected() will return the IBinder we'll use to communicate back and forth. 
    bindService(new Intent(this, AccelService.class), this, Context.BIND_AUTO_CREATE); 
} 
protected void onPause() { 
    ... 
    // Note: By itself, this doesn't stop the Service from sending messages to us. 
    // We need to send a custom Unsubscribe Message to stop getting messages from the Service. 
    unbindService(this); 

} 
public void onClick(View v) { 
    // Send a custom intent to start or stop our Service. 
    if (buttonStart == v) { 
     startService(new Intent(AccelService.ACTION_START)); 
    } else if (buttonStop == v) { 
     startService(new Intent(AccelService.ACTION_STOP)); 
    } 
    ... 
} 
public void onServiceConnected(ComponentName name, IBinder service) { 
    ... 
    // Ask our Service to send us updates. 
    toService = new Messenger(service); 
    Message msg = Message.obtain(null, FromClientHandler.MSG_SUBSCRIBE); // our custom Subscribe message 
    msg.replyTo = fromService; 
    try { 
     toService.send(msg); 
    } catch (RemoteException e) { 
     // Failed because the Service has died. 
     // We handle this in onServiceDisconnected(). 
    } 
} 

在活动的自定义消息处理

.... 
public void handleMessage(Message msg) { 
    switch (msg.what) { 
    case MSG_ACCEL_UPDATE: 
     ... 
     Bundle bundle = msg.getData(); 
     double accelValue = bundle.getDouble(ACCEL_UPDATE_VALUE); 
     ...then display the new accelValue in, for example, a TextView. 
    ... 
    } 
} 

在服务,名为AccelService:

... 
private Messenger fromClient; // For receiving messages from our Client(s). 
private FromClientHandler handler;  // needed just for unlinking at in onDestroy(). 
// Since we have only one Client, we store only one Activity's Messenger 
private Messenger subscribedMessenger; 
public void onCreate() { 
    ... 
    handler = new FromClientHandler(this); 
    fromClient = new Messenger(handler); 
} 
public void onDestroy() { 
    // Unlink ourselves from our Handler, so the Garbage Collector can get rid of us. That's a topic in itself. 
    handler.unlink(); 
    .... 
} 
public int onStartCommand(Intent intent, int flags, int startId) { 
    ... 
    int returnValue = START_NOT_STICKY; 
    String action = intent.getAction(); 
    if (ACTION_START.equals(action)) { 
     doActionStart(); 
     returnValue = START_STICKY; 
    } else if (ACTION_STOP.equals(action)) { 
     ... 
     // Our Service is done 
     stopSelf(); 
    } 
    ... 
    return returnValue; 
} 
public IBinder onBind(Intent intent) { 
    // Hand back a way to send messages to us. 
    return fromClient.getBinder(); 
} 
...when we want to send data to the Activity: 
    Message msg = Message.obtain(null, FromServiceHandler.MSG_ACCEL_UPDATE); 
    Bundle bundle = new Bundle(); 
    bundle.putDouble(FromServiceHandler.ACCEL_UPDATE_VALUE, avgAccel); 
    msg.setData(bundle); 
    try { 
     subscribedMessenger.send(msg); 
    } catch (RemoteException e) { 
     // Failed because the Client has unbound. 
     subscribedMessenger = null; 
    }