我是java的新手,想知道如何在后台运行与服务一起运行的活动。因此,当活动关闭并重新打开时,它将继续服务。我不知道如何解释它。
假设3个服务,每个服务每小时执行一次。
服务1 ... 1小时......服务2 ... 1小时......服务3.完成。
每次执行时,都会在活动中设置textview。但是,当活动关闭时,不会创建文本视图。
我找到的唯一方法是使用如下例所示的变量
服务1:
public int service_one_done = 1;
服务2:
public int service_two_done = 1;
服务3:
public int service_three_done = 1;
活动onCreate:
if (service_one_done == 1) { textview_example1.setVisibility(View.VISIBLE)
} if (service_two_done == 1) { textview_example2.setVisibility(View.VISIBLE)
} if (service_three_done == 1) { textview_example3.setVisibility(View.VISIBLE)
}
我想知道是否有更好的方法来做到这一点
答案 0 :(得分:0)
在我的服务类中,我写了这个
private static void sendMessageToActivity(Location l, String msg) {
Intent intent = new Intent("GPSLocationUpdates");
// You can also include some extra data.
intent.putExtra("Status", msg);
Bundle b = new Bundle();
b.putParcelable("Location", l);
intent.putExtra("Location", b);
LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
}
在活动方面,我们必须收到此广播消息
LocalBroadcastManager.getInstance(getActivity()).registerReceiver(
mMessageReceiver, new IntentFilter("GPSLocationUpdates"));
通过这种方式,您可以向活动发送消息。这里的mMessageReceiver是你将要执行的任何你想要的类......
在我的代码中我做了这个....
private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// Get extra data included in the Intent
String message = intent.getStringExtra("Status");
Bundle b = intent.getBundleExtra("Location");
lastKnownLoc = (Location) b.getParcelable("Location");
if (lastKnownLoc != null) {
tvLatitude.setText(String.valueOf(lastKnownLoc.getLatitude()));
tvLongitude
.setText(String.valueOf(lastKnownLoc.getLongitude()));
tvAccuracy.setText(String.valueOf(lastKnownLoc.getAccuracy()));
tvTimestamp.setText((new Date(lastKnownLoc.getTime())
.toString()));
tvProvider.setText(lastKnownLoc.getProvider());
}
tvStatus.setText(message);
// Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
}
};
参考here