[英]How to call a method from a service?
我可以单击一个按钮来调用我的函数,而不会出现这样的问题,它可以正常工作,并且还可以擦除数据。
public class MainActivity extends Activity implements OnCheckedChangeListener {
DevicePolicyManager devicePolicyManager;
public void resetdevice(View view) {
Toast.makeText(context, "resetttt", Toast.LENGTH_LONG).show();
// We reset the device - this will erase entire /data partition!
Log.d(TAG,
"RESETing device now - all user data will be ERASED to factory settings");
devicePolicyManager.wipeData(ACTIVATION_REQUEST);
}
但是,为了从另一个服务调用此方法,我需要做一些更改。
public class MainActivity extends Activity implements OnCheckedChangeListener {
static DevicePolicyManager devicePolicyManager;
和我的方法
public static void resetdevice(Context context) {
Toast.makeText(context, "resetttt", Toast.LENGTH_LONG).show();
// We reset the device - this will erase entire /data partition!
Log.d(TAG,
"RESETing device now - all user data will be ERASED to factory settings");
devicePolicyManager.wipeData(ACTIVATION_REQUEST);
}
这就是我的称呼
MainActivity.resetdevice(context);
问题是,当从我的服务中调用它时,它仅显示吐司,而不执行其余代码。
如果您足够擅长使用事件总线,而不是在代码中实现事件总线,那么当您要调用方法时,只要服务中的fire事件就会在您已实现的位置调用方法。
要么
要从服务调用方法时,请尝试使用广播接收器并发送广泛的广播。
您不能通过这样的服务直接调用活动方法。 请使用广播或绑定对象。 在这里结帐
尝试这个:
public static void resetdevice(Context context) {
DevicePolicyManager devicePolicyManager= (DevicePolicyManager) context
.getSystemService(Context.DEVICE_POLICY_SERVICE);
Toast.makeText(context, "resetttt", Toast.LENGTH_LONG).show();
// We reset the device - this will erase entire /data partition!
Log.d(TAG,
"RESETing device now - all user data will be ERASED to factory settings");
devicePolicyManager.wipeData(ACTIVATION_REQUEST);
}
但是我确实建议按照@jack所说的方式做。
您可能需要检查“ 绑定服务” 。 您可以使用它来通知您的Activity
,它需要使用Messenger and Handlers
从您的Activity
调用resetDevice
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.