如何从单独的类

时间:2015-12-10 22:39:42

标签: java android

所以我一直在玩Android M风格的权限,只要我在MainActivity中做所有事情,我就有一个有效的演示。我觉得它看起来很麻烦,并希望将其分成多个文件,因此它看起来更清洁,更容易维护。

问题是将权限检查移动到自己的文件中,我现在遇到麻烦,我的权限检查器回到MainActivity并启动demo()方法。我需要回调主要活动的地方演示方法是在PermissionsChecker.java的第73行和第114行

注意:我在Android权限上关注了this tutorial 我找到了this question以及这些问题here& here。我意识到这是危险的接近最后两个的重复,他们让我接近,但我还没有完全得到它。如果有人可以为我分解一点,我仍然是Java和Android的新手。

的AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest package="me.johnweland.androidrtp"
          xmlns:android="http://schemas.android.com/apk/res/android">

    <!-- // Permissions -->
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
    <uses-permission android:name="android.permission.RECORD_AUDIO" />
    <uses-permission android:name="android.permission.CAMERA" />

    <!-- // Features -->
    <uses-feature android:name="android.hardware.camera" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>

                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
    </application>

</manifest>

MainActivity.java

package me.johnweland.androidrtp;

import android.Manifest;
import android.annotation.TargetApi;
import android.content.pm.PackageManager;
import android.os.Build;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;

import java.util.HashMap;
import java.util.Map;

public class MainActivity extends AppCompatActivity {
    final private int REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        if (Build.VERSION.SDK_INT >= 23) {
            // Marshmallow+
            PermissionChecker permissions = PermissionChecker.getInstance(this);
            permissions.permissionsCheck();
        } else {
            // Pre-Marshmallow
            demo();
        }

    }

    @TargetApi(Build.VERSION_CODES.M)
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        switch (requestCode) {
            case REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS:
            {
                Map<String, Integer> perms = new HashMap<String, Integer>();
                // Initial
                perms.put(Manifest.permission.RECORD_AUDIO, PackageManager.PERMISSION_GRANTED);
                perms.put(Manifest.permission.CAMERA, PackageManager.PERMISSION_GRANTED);
                // Fill with results
                for (int i = 0; i < permissions.length; i++)
                    perms.put(permissions[i], grantResults[i]);
                // Check for RECORD_AUDIO
                if (perms.get(Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED
                        && perms.get(Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
                    // All Permissions Granted
                    demo();
                }
                else {
                    // Permission Denied
                    Toast.makeText(this, R.string.permission_denied_message, Toast.LENGTH_SHORT).show();
                }
            }
            break;
            default:
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }

    protected void demo() {
        Toast.makeText(this, "Demo toast", Toast.LENGTH_LONG).show();
    }
}

PermissionsChecker.java

package me.johnweland.androidrtp;

import android.Manifest;
import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.os.Build;


import java.util.ArrayList;

import java.util.List;


/**
 * Created by jweland on 12/11/2015.
 */
public class PermissionChecker {
    private static final String TAG = PermissionChecker.class.getSimpleName();
    final private int REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS = 0;

    private MainActivity mainActivity;
    private static PermissionChecker instance = null;
    private PermissionChecker(MainActivity activity) {
        mainActivity = activity;
    }

    static public PermissionChecker getInstance(MainActivity activity) {
        if (instance == null) {
            instance = new PermissionChecker(activity);
            return instance;
        } else {
            return instance;
        }
    }

    @TargetApi(Build.VERSION_CODES.M)
    protected void permissionsCheck(){
        List<String> permissionsNeeded = new ArrayList<String>();

        final List<String> permissionsList = new ArrayList<String>();
        // Add permission check for any permission that is not NORMAL_PERMISSIONS
        if(!addPermission(permissionsList, Manifest.permission.RECORD_AUDIO))
            permissionsNeeded.add(mainActivity.getString(R.string.permission_microphone));
        if(!addPermission(permissionsList, Manifest.permission.CAMERA))
            permissionsNeeded.add(mainActivity.getString(R.string.permission_camera));

        if(permissionsList.size() > 0) {
            if(permissionsNeeded.size() > 0) {
                // Need Rationale
                String message = mainActivity.getString(R.string.permission_grant_message) + permissionsNeeded.get(0);
                for (int i = 1; i < permissionsNeeded.size(); i++)
                    message = message + "\n" +permissionsNeeded.get(i);
                showMessageOKCancel(message,
                        new DialogInterface.OnClickListener() {
                            @TargetApi(Build.VERSION_CODES.M)
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                mainActivity.requestPermissions(permissionsList.toArray(new String[permissionsList.size()]),
                                        REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS);
                            }
                        });
                return;
            }
                mainActivity.requestPermissions(permissionsList.toArray(new String[permissionsList.size()]),
                        REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS);
            return;
        }
        mainActivity.demo();
    }

    private void showMessageOKCancel(String message, DialogInterface.OnClickListener okListener) {
        new AlertDialog.Builder(mainActivity)
                .setMessage(message)
                .setPositiveButton(R.string.dialog_ok_button_text, okListener)
                .setNegativeButton(R.string.dialog_cancel_button_text, null)
                .create()
                .show();
    }

    @TargetApi(Build.VERSION_CODES.M)
    private boolean addPermission(List<String> permissionsList, String permission) {
        if (mainActivity.checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) {
            permissionsList.add(permission);
            // Check for Rationale Option
            if (!mainActivity.shouldShowRequestPermissionRationale(permission))
                return false;
        }
        return true;
    }
}

最初在第73和114行的最后一个代码块中,我尝试过“MainActivity.demo();”的效果。其中“demo();”是我想要的方法。

1 个答案:

答案 0 :(得分:2)

您可以让您的课程要求您将活动作为参数,将其保存在变量上并随时调用它(假设您的类和活动在同一个线程上运行)。

public class MyActivity extends AppCompatActivity
{
    public void myFunction() {/* ... */}
}

public class MyClass
{
    MyActivity activity;

    //This could be the constructor
    public void someFunction(MyActivity gActivity)
    {
        activity = gActivity;
    }

    public void anotherFunction()
    {
        //From activity you can get everything you want like context
        //resources and anything else
        activity.myFunction();
    }
}

你能做到的另一种方法是创建一个界面来保存一个函数(在你的活动上)并将该界面作为参数传递给你的类并随时调用它,但是这稍微复杂一点,在我看来,第一种方法更好。