在 java 个文件之间使用静态方法

using static methods between java files

我知道已经有人问过类似的其他问题,但我仍然无法解决这个问题。

我在android工作室有两个活动,一个是homePage.java,另一个是newMessagePage.java。我正在尝试在 newMessagePage.java activity 中使用 getPermissiontoReadSMS 方法。由于它在 homePage.java activity 中,我得到了 "non-static method cannot be referenced from a static context error." 其他帖子中的一些建议包括添加该方法的实例。我对此还很陌生,不确定如何去做。感谢任何帮助。

homePage.java

public class homePage extends AppCompatActivity {

    private ListView mDrawerList;
    private DrawerLayout mDrawerLayout;
    private ArrayAdapter<String> mAdapter;
    private boolean firstResume = false;

    ArrayList<String> smsMessagesList = new ArrayList<>();
    ListView messages;
    ArrayAdapter arrayAdapter;
    private static homePage inst;

    private static final int READ_SMS_PERMISSIONS_REQUEST = 1;



    public static homePage instance() {
        return inst;
    }

    public void getPermissionToReadSMS() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_SMS)
                != PackageManager.PERMISSION_GRANTED) {
            if (shouldShowRequestPermissionRationale(
                    Manifest.permission.READ_SMS)) {
                Toast.makeText(this, "Please allow permission", Toast.LENGTH_SHORT).show();
            }
            requestPermissions(new String[]{Manifest.permission.READ_SMS}, READ_SMS_PERMISSIONS_REQUEST);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           @NonNull String permissions[],
                                           @NonNull int[] grantResults) {

        if(requestCode == READ_SMS_PERMISSIONS_REQUEST) {
            if(grantResults.length == 1 &&
                    grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                Toast.makeText(this, "Read SMS permission granted", Toast.LENGTH_SHORT).show();
                refreshSmsInbox();
            }else {
                Toast.makeText(this, "Read SMS permission denied", Toast.LENGTH_SHORT).show();
            }
        }else {
            super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }

    public void refreshSmsInbox() {
        ContentResolver contentResolver = getContentResolver();
        Cursor smsInboxCursor = contentResolver.query(Uri.parse("content://sms/inbox"), null, null, null, null);
        int indexBody = smsInboxCursor.getColumnIndex("body");
        int indexAddress = smsInboxCursor.getColumnIndex("address");

        if(indexBody < 0 || !smsInboxCursor.moveToFirst()) return;
        arrayAdapter.clear();
        do {
            String str = "SMS from: " + smsInboxCursor.getString(indexAddress) +
                    "\n" + smsInboxCursor.getString(indexBody) + "\n";
            arrayAdapter.add(str);
        } while(smsInboxCursor.moveToNext());

        }


    private void addDrawerItems() {
    //side drawer things
        String[] osArray = { "Sent", "Patients", "Folders", "Trash", "Settings" };
        mAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, osArray);
        mDrawerList.setAdapter(mAdapter);

        mDrawerList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                if(position == 4) {

                    Intent settingsIntent = new Intent(homePage.this, settingsPage.class);
                    startActivity(settingsIntent);
                }
            }
        });
    }

    private void FABListener() {
    //FAB button functions
        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                Intent newMessage = new Intent(homePage.this, newMessagePage.class);
                startActivity(newMessage);
            }
        });
    }

@Override
protected void onStart() {
    super.onStart();
    inst = this;
}

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home_page);

        mDrawerList = (ListView)findViewById(R.id.navList);
        mDrawerLayout = (DrawerLayout)findViewById(R.id.drawer_layout);

        messages = (ListView) findViewById(R.id.messages);
        arrayAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, smsMessagesList);
        messages.setAdapter(arrayAdapter);

        if(ContextCompat.checkSelfPermission(this,Manifest.permission.READ_SMS) != PackageManager.PERMISSION_GRANTED) {
            getPermissionToReadSMS();
        }else {
            refreshSmsInbox();
        }

        addDrawerItems();
        FABListener();
    }


    @Override
    protected void onResume() {
        super.onResume();

        if(firstResume) {
            mDrawerLayout.openDrawer(Gravity.START);
        }
        firstResume = false;
    }
}

newMessagePage.java

public class newMessagePage extends AppCompatActivity {

SmsManager smsManager = SmsManager.getDefault();
EditText input;

public void onSendClick(View view) {

    if (ContextCompat.checkSelfPermission(this, Manifest.permission.SEND_SMS)
            != PackageManager.PERMISSION_GRANTED) {

        //insert reference to getPermissionToReadSMS method here


    }else {

        smsManager.sendTextMessage("07747689961", null, input.getText().toString(), null, null);
        Toast.makeText(this, "Message sent!", Toast.LENGTH_SHORT).show();
    }
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_new_message_page);

    input = (EditText) findViewById(R.id.input);
}

}

试试这个:

public static void getPermissionToReadSMS(AppCompatActivity context) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        if (context.checkSelfPermission(this, Manifest.permission.READ_SMS)
                != PackageManager.PERMISSION_GRANTED) {
            if (shouldShowRequestPermissionRationale(
                    Manifest.permission.READ_SMS)) {
                Toast.makeText(this, "Please allow permission", Toast.LENGTH_SHORT).show();
            }
            context.requestPermissions(new String[]{Manifest.permission.READ_SMS}, READ_SMS_PERMISSIONS_REQUEST);
        }
    }
}

不要这样做!静态方法和变量是例外而不是规则。在 Android 中,它们可能会导致特别严重的错误,尤其是您在这里所做的事情。尝试访问当前未激活并显示在屏幕上的 activity 的方法将导致您的应用程序出现严重问题。它很可能会崩溃。除了静态方法,您还需要了解 Activity lifecycle 并使用它,以免意外泄漏内存和其他资源。

为了在活动之间共享方法的功能,您至少有三个选择:

  1. 使用该方法创建一个 class,然后在每个 activity.

  2. 中声明一个 class 的变量
  3. 创建一个扩展 AppCompatActivity 的抽象 class。将方法添加到此 class,然后为每个活动扩展此 class,而不是扩展 AppCompatActivity。

  4. 用方法创建一个"utility class"并使其静态化。

第一个选项通常是最受欢迎的,因为它提供了最大的灵活性。您可以根据需要声明任意数量的变量以提供不同的功能。

第二个选项没问题,但它会将您锁定在一个非常有限的继承层次结构中,因为您只能扩展一个 class。

第三个选项只是最后的手段,因为static方法不遵循面向对象的原则。