我试图让我的Java Android应用程序给予我管理权限锁定任务模式,但它失败了

58wvjzkj  于 2023-05-15  发布在  Android
关注(0)|答案(1)|浏览(169)

我一直试图做锁定任务模式或锁定到我的应用程序,而不能访问其他应用程序仍然能够禁用该功能。我看过教程和文档,但有些方法是在大约5年前(onActivityResult)制作的,所以不推荐使用。我已经尝试更改为我发现的新方法(registerForActivityResult),但是当我启动我的应用程序并尝试通过点击启用按钮来启用管理员权限时,管理员权限不会弹出,所以我无法检查它。所以,当我试图从其他应用程序锁定我的手机什么也没发生,因为我没有管理员权限.我的代码MainActivity.class如下:

package com.example.myapplication;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityOptions;
import android.app.admin.DevicePolicyManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AppCompatActivity;

import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;

import com.example.myapplication.databinding.ActivityMainBinding;

import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;

import com.example.myapplication.helper.MqttHelper;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallbackExtended;
import org.eclipse.paho.client.mqttv3.MqttMessage;

public class MainActivity extends AppCompatActivity implements View.OnClickListener{

    private Button lock, disable, enable;
    private static final int RESULT_ENABLE = 11;
    private DevicePolicyManager devicePolicyManager;
    private ActivityManager activityManager;
    private ComponentName componentName;

    private AppBarConfiguration appBarConfiguration;
    private ActivityMainBinding binding;
    MqttHelper mqttHelper;
    //ChartHelper mChart;
    //LineChart chart;

    TextView dataReceived;
    private Button btnPublish;

    // Allowlist two apps.
    private static final String KIOSK_PACKAGE = "com.example.myapplication";
    private static final String[] APP_PACKAGES = {KIOSK_PACKAGE};

// ...

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        binding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        //setContentView(R.layout.activity_main);
        devicePolicyManager = (DevicePolicyManager) getSystemService(DEVICE_POLICY_SERVICE);
        activityManager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
        componentName = new ComponentName(this, Controller.class);

        lock = (Button) findViewById(R.id.lock);
        enable = (Button) findViewById(R.id.enable);
        disable = (Button) findViewById(R.id.disable);
        lock.setOnClickListener(this);
        enable.setOnClickListener(this);
        disable.setOnClickListener(this);

       
        
        dataReceived = (TextView) findViewById(R.id.textview_first);
        startMqtt();
    }



    @Override
    protected void onResume() {
        super.onResume();
        boolean isActive = devicePolicyManager.isAdminActive(componentName);
    }

    @Override
    public void onClick(View view) {
        if (view == lock) {
            boolean active = devicePolicyManager.isAdminActive(componentName);
            if(active) {
                devicePolicyManager.lockNow();
            } else {
                Toast.makeText(this, "You need to enable the Admin Device Features", Toast.LENGTH_SHORT).show();
            }
        } else if (view == enable) {
            Intent intent = new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);
            intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, componentName);
            intent.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION,"You Should Enable the app!");
            //someActivityResultLauncher.launch(intent);
            // Caller
            mGetContent.launch(intent);
            // Receiver

            //startActivityForResult(intent, RESULT_ENABLE);
        } else if (view == disable) {
            devicePolicyManager.removeActiveAdmin(componentName);
            disable.setVisibility(View.GONE);
            enable.setVisibility(View.VISIBLE);
        }

    }

    ActivityResultLauncher<Intent> mGetContent = registerForActivityResult(
            new ActivityResultContracts.StartActivityForResult(),
            new ActivityResultCallback<ActivityResult>() {
                @Override
                public void onActivityResult(ActivityResult result) {
                    if (result.getResultCode() == Activity.RESULT_OK) {
                        // Here, no request code
                        Intent data = result.getData();

                        Toast.makeText(MainActivity.this, "enabled", Toast.LENGTH_SHORT).show();
                    }else{
                        Toast.makeText(MainActivity.this, "Failed", Toast.LENGTH_SHORT).show();
                    }
                }
            });

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

                if(resultCode== Activity.RESULT_OK  && requestCode == RESULT_ENABLE){
                    Toast.makeText(MainActivity.this, "enabled", Toast.LENGTH_SHORT).show();
                }else {
                    Toast.makeText(MainActivity.this, "Failed", Toast.LENGTH_SHORT).show();
                }

        super.onActivityResult(requestCode, resultCode, data);
    }

    /*@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        switch (requestCode){
            case RESULT_ENABLE:
                if(resultCode== Activity.RESULT_OK ){
                    //btn_unblock.setText("Dissable");
                    //btn_block.setVisibility(View.VISIBLE);
                    Toast.makeText(MainActivity.this, "enabled", Toast.LENGTH_SHORT).show();
                }else{
                    Toast.makeText(MainActivity.this, "Failed", Toast.LENGTH_SHORT).show();
                }
                break;
        }

        super.onActivityResult(requestCode, resultCode, data);
    }*/

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public boolean onSupportNavigateUp() {
        NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
        return NavigationUI.navigateUp(navController, appBarConfiguration)
                || super.onSupportNavigateUp();
    }


    // MQTT Code

    private void startMqtt(){
        mqttHelper = new MqttHelper(getApplicationContext());
        mqttHelper.mqttAndroidClient.setCallback(new MqttCallbackExtended() {
            @Override
            public void connectComplete(boolean b, String s) {
                Log.w("Debug","Connected");
            }

            @Override
            public void connectionLost(Throwable throwable) {

            }

            @Override
            public void messageArrived(String topic, MqttMessage mqttMessage) throws Exception {
                Log.w("Debug",mqttMessage.toString());
                dataReceived.setText(mqttMessage.toString());
                //mChart.addEntry(Float.valueOf(mqttMessage.toString()));
            }

            @Override
            public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {

            }
        });
    }
}
dgsult0t

dgsult0t1#

我目前正在开发一个企业应用程序,它运行在平板电脑上,也处于锁定任务模式,所以我分享了我为我的案例所做的事情。不是一个超级干净的代码,但它做的工作。
第一个java类:
你需要一个像这样的管理接收器类

import android.app.admin.DeviceAdminReceiver;
public class AppAdminReceiver extends DeviceAdminReceiver {

}

如果你让它空着也没关系。
第二个manifest.xml:

<receiver
        android:name=".AppAdminReceiver"
        android:description="@string/app_name"
        android:exported="true"
        android:label="@string/app_name"
        android:permission="android.permission.BIND_DEVICE_ADMIN">
        <meta-data
            android:name="android.app.device_admin"
            android:resource="@xml/device_admin_receiver" />
        <intent-filter android:priority="1000">
            <action android:name="android.app.action.DEVICE_ADMIN_DISABLED" />
            <action android:name="android.app.action.DEVICE_ADMIN_ENABLED" />
            <action android:name="android.intent.action.DEVICE_ADMIN_ENABLED" />
            <action android:name="android.intent.action.PROFILE_PROVISIONING_COMPLETE" />
            <action android:name="android.intent.action.BOOT_COMPLETED" />
        </intent-filter>
    </receiver>

添加此接收器到您的清单和编辑标签和描述的基础上你想要的。
你应该通过adb将你的应用程序设置为admin,因为我也无法在设置中启用它,所以我目前使用adb命令。
{packageName}:您可以在标记为“applicationId”的gradle文件中找到packageName。
{your管理类}:您的类可能类似于com.example.appName.AppAdminReceiver

// to set as owner/admin
adb shell dpm set-device-owner {packageName}/{your admin class}
// to remove owner/admin
adb shell dpm remove-active-admin {packageName}/{your admin class}

最后一件事任务锁类,使事情变得容易:

import android.app.Activity;
import android.app.ActivityManager;
import android.app.admin.DevicePolicyManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.UserManager;
import android.widget.Toast;

import com.example.isense.R;

public class KioskHandler {
    static ComponentName mAdminComponentName;
    static DevicePolicyManager mDevicePolicyManager;

    public static void startKiosk(Activity context){
       if(mDevicePolicyManager.isLockTaskPermitted(context.getPackageName())){
            ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
            if (am.getLockTaskModeState() == ActivityManager.LOCK_TASK_MODE_NONE) {
                setDefaultCosuPolicies(true);
                context.startLockTask();
              
            }
        }
    }

    public static void stopKiosk(Activity context){
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        if (am.getLockTaskModeState() == ActivityManager.LOCK_TASK_MODE_LOCKED) {
            context.stopLockTask();
            setDefaultCosuPolicies(false);
           
            
        }
    }
    public static boolean initialize(Context context){
        try{
            mAdminComponentName = new ComponentName(context, AppAdminReceiver.class);
            mDevicePolicyManager = (DevicePolicyManager) context.getSystemService(Context.DEVICE_POLICY_SERVICE);
            String[] packages={
                    context.getPackageName(),
                    "com.android.date",
                    "com.android.settings.date",
                    "com.android.bluetooth",
                    "com.bluetooth",
                    "com.Bluetooth",
                    "com.samsung",
                    "com.wifi",
                    "com.android.wifi",
                    "com.android.settings.bluetooth",
                    "com.android.settings.wifi"
            } ;
            mDevicePolicyManager.setLockTaskPackages(mAdminComponentName,packages);
            if(mDevicePolicyManager.isDeviceOwnerApp(context.getPackageName())){
                // App is whitelisted
                setDefaultCosuPolicies(true);
                return true;
            }
            else {
                return false;
            }
        }
        catch (Exception ignored){return false;}

    }

    private static void setDefaultCosuPolicies(boolean active){

        // Set user restrictions
        setUserRestriction(UserManager.DISALLOW_SAFE_BOOT, active);
        setUserRestriction(UserManager.DISALLOW_FACTORY_RESET, active);
        setUserRestriction(UserManager.DISALLOW_ADD_USER, active);
        setUserRestriction(UserManager.DISALLOW_MOUNT_PHYSICAL_MEDIA, active);
        setUserRestriction(UserManager.DISALLOW_USB_FILE_TRANSFER,active);
        // Disable keyguard and status bar
        mDevicePolicyManager.setKeyguardDisabled(mAdminComponentName, active);
        mDevicePolicyManager.setStatusBarDisabled(mAdminComponentName, active);

    }

    private static void setUserRestriction(String restriction, boolean disallow){
        if (disallow) {
            mDevicePolicyManager.addUserRestriction(mAdminComponentName,restriction);
        } else {
            mDevicePolicyManager.clearUserRestriction(mAdminComponentName,restriction);
        }
    }
}

让我来解释一下:
首先u调用initialize并传递它需要的输入。然后你可以很容易地调用stopKiosk或startKiosk来做你的事情。
例如:

KioskHandler.initialize(this);
KioskHandler.startKiosk(this);
// "this" has to be activity

注意:要安装新版本或删除应用程序,您必须使用adb命令删除设备的所有权。

相关问题