如何安全地从服务发送数据到运行中的活动
如何安全地从服务发送数据到运行中的活动
假设我在一个服务中有一个名为"test"的字符串,我想将其发送给我的正在运行的主活动。
如何安全地发送这些数据?
我正在寻找最简单的例子,其中数据不能被其他应用程序看到。
当我查看意图时,它说:
广播是任何应用程序都可以接收的消息。系统会传递各种广播以进行系统事件,例如系统启动或设备开始充电。您可以通过将Intent传递给sendBroadcast()或sendOrderedBroadcast()来将广播传递给其他应用程序。
然而,我只想将它发送给我的应用程序,因为它包含私有数据。
在我的服务中,我尝试了以下代码:
Intent intent = new Intent(this, MainActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP); intent.putExtra(getString(R.string.notification_intent), "6"); startActivity(intent);
其中MainActivity.class是应该接收意图的类,但以这种方式,我得到了以下提示:
从Activity外部调用startActivity()要求使用FLAG_ACTIVITY_NEW_TASK标志。这真的是你想要的吗?
如何安全地从服务发送数据到活动?
问题的出现原因是需要在Android服务和正在运行的活动之间安全地发送数据。解决方法是使用意图(intents)或将活动绑定到服务。
使用意图的方法如下:
1. 从服务发送消息:
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); }
2. 在活动中注册接收消息:
LocalBroadcastManager.getInstance(getActivity()).registerReceiver( mMessageReceiver, new IntentFilter("GPSLocationUpdates"));
3. 在活动中创建自定义消息接收器:
private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() { 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"); ... }
将活动绑定到服务的方法如下:
1. 在服务中创建Binder类:
public class LocalService extends Service { // Binder given to clients private final IBinder binder = new LocalBinder(); ... public class LocalBinder extends Binder { LocalService getService() { // Return this instance of LocalService so clients can call public methods return LocalService.this; } } public IBinder onBind(Intent intent) { return binder; } }
2. 在活动中绑定服务:
protected void onStart() { super.onStart(); // Bind to LocalService Intent intent = new Intent(this, LocalService.class); bindService(intent, connection, Context.BIND_AUTO_CREATE); ... }
3. 创建ServiceConnection回调:
private ServiceConnection connection = new ServiceConnection() { public void onServiceConnected(ComponentName className, IBinder service) { // We've bound to LocalService, cast the IBinder and get LocalService instance LocalBinder binder = (LocalBinder) service; mService = binder.getService(); mBound = true; } ... }
这些方法都是安全的,可以根据实际需求选择使用。同时,还可以使用广播来发送和接收数据。Android提供了三种发送广播的方式:sendOrderedBroadcast方法、sendBroadcast方法和LocalBroadcastManager.sendBroadcast方法。其中,LocalBroadcastManager.sendBroadcast方法可以在同一个应用程序中发送广播,不需要担心安全问题。
此外,可以使用权限来限制广播的发送和接收。通过在发送广播时指定权限参数,只有在清单文件中请求了相应权限的接收器才能接收广播。
使用意图或将活动绑定到服务是安全地从服务发送数据到正在运行的活动的常见方法。