Android 如何从服务调用方法?
我可以调用我的功能,点击一个按钮,没有类似的问题,它的工作,也擦拭数据Android 如何从服务调用方法?,android,Android,我可以调用我的功能,点击一个按钮,没有类似的问题,它的工作,也擦拭数据 public class MainActivity extends Activity implements OnCheckedChangeListener { DevicePolicyManager devicePolicyManager; public void resetdevice(View view) { Toast.makeText(context, "resetttt", Toast.LENGTH_LON
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);
问题是,当从“我的服务”调用它时,它只显示toast,不执行代码的其余部分。如果您足够好地使用事件总线,则在代码中实现事件总线,并且当您想调用方法时,只要从服务中触发事件,就会在您实现的任何地方调用您的方法 或
当您想从服务中调用您的方法时,请尝试使用广播接收器并发送广播。您不能像这样直接从服务中调用活动方法。请使用广播或绑定对象。签出一个ex尝试以下操作:
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所说的方法进行操作。您可能需要检查。您可以使用它来通知您的
活动
它需要使用Messenger和处理程序从您的活动
调用重置设备
。您是否检查了是否引发了任何异常?我认为这一行导致了问题-静态设备Policymanager设备Policymanager;您不需要初始化DevicePolicyManager
来使用wipeData
方法吗?我对此不太熟悉。请在代码中显示您有devicePolicyManager=
的位置。您应该发布一个.DevicePolicyManager localDPM=(DevicePolicyManager)context.getSystemService(context.DEVICE\u POLICY\u SERVICE);您需要执行类似于上述代码的操作来初始化设备策略管理器。