这更令人怀疑。目前,我的代码工作正常,但我想确保我以正确的方式做到这一点。
我有一项服务,检查活动是否在前台运行。如果是,它会向活动发送广播,因此活动会更新屏幕上的一些内容。
我在服务上创建了IntentFilter
:
com.harkdev.ServerStatus.SERVER_UPDATED
此处服务需要知道活动是否在前台,因此它使用IsActivityRunning()
方法,该方法从ApplicationManager
读取正在运行的任务。这意味着我需要设置GET_TASKS
权限。
由于这两者,SERVICE和ACTIVITY都在同一个包装上,有没有更好的方法来获取这些信息?也许可以尝试避免设置GET_TASKS
权限??
这是我服务中的代码:
if (IsActivityRunning()) {
Intent localIntent = new Intent(SERVER_UPDATED);
SendBroadcast(localIntent, null);
}
IsActivityRunning()
方法:
public bool IsActivityRunning() {
ActivityManager manager = (ActivityManager) GetSystemService(ActivityService);
IList<ActivityManager.RunningTaskInfo> runningTaskInfo = manager.GetRunningTasks(1);
ComponentName componentInfo = runningTaskInfo[0].TopActivity;
if (componentInfo.PackageName == "com.harkdev.ServerStatus")
return true;
return false;
}
这是我活动中的代码:
protected override void OnCreate (Bundle bundle) {
base.OnCreate(bundle);
// Set our view from the "main" layout resource
SetContentView (Resource.Layout.Main);
IntentFilter filter = new IntentFilter(ServerStatusCheckService.SERVER_UPDATED);
_receiver = new ServiceBroadcastReceiver ();
_receiver.Received += Receiver_Received;
RegisterReceiver(_receiver, filter);
}
答案 0 :(得分:3)
首先,你做错了比较字符串的方法:
if (componentInfo.PackageName == "com.harkdev.ServerStatus")
应该是:
if ("com.harkdev.ServerStatus".equals(componentInfo.PackageName))
其次,如果服务和活动在您的应用程序中,那么我认为不需要检查“相同包”。
要将服务中的信息发送到活动,您可以使用ResultReceiver
(API 3 +中提供):
ResultReceiver
,将其放入启动服务的意图中。ResultReceiver
并保留。如果要发送信息,请使用send()
。onDestroy()
中,您可以触发一条命令,通知服务ResultReceiver
无效且应将其删除。Edied
例如:
在您的活动中:
// Global variable.
private ResultReceiver mResultReceiver = new ResultReceiver() {
@Override
protected void onReceiveResult(int resultCode, Bundle resultData) {
// Update the UI here...
}
}
启动服务时:
Intent i = new Intent(this, TheService.class);
// You can use different action names for different commands.
i.setAction("REGISTER_RECEIVER");
i.putExtra("ResultReceiver", mResultReceiver);
i.putExtra("ResultReceiver_ID", hashCode());
startService(i);
在onDestroy()
:
Intent i = new Intent(this, TheService.class);
i.setAction("UNREGISTER_RECEIVER");
i.putExtra("ResultReceiver_ID", hashCode());
startService(i);
在您的服务中:
import android.util.SparseArray;
// ...
private SparseArray<ResultReceiver> mReceiverMap = new SparseArray<ResultReceiver>();
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if ("REGISTER_RECEIVER".equals(intent.getAction())) {
// Extract the ResultReceiver and store it into the map
ResultReceiver receiver = intent.getParcelableExtra("ResultReceiver");
int id = intent.getIntExtra("ResultReceiver_ID", 0);
mReceiverMap.put(id, receiver);
} else if ("UNREGISTER_RECEIVER".equals(intent.getAction())) {
// Extract the ResultReceiver ID and remove it from the map
int id = intent.getIntExtra("ResultReceiver_ID", 0);
mReceiverMap.remove(id);
}
// ...
}