权限:呼叫需要权限,用户可能会拒绝

时间:2018-10-22 17:55:52

标签: android android-permissions user-permissions

在Android Studio下进行编译时,我收到了本文标题中指定的警告。我尝试使用以下代码获取GPS更新:

from PyQt5 import QtCore, QtGui, QtWidgets


class CustomView(QtWidgets.QTableView):
    def __init__(self, parent=None):
        super(CustomView, self).__init__(parent)
        self.verticalHeader().hide()
        self.horizontalHeader().hide()
        self.setShowGrid(False)
        self.horizontalHeader().setSectionResizeMode(QtWidgets.QHeaderView.ResizeToContents)
        self.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectRows)
        self.setSelectionMode(QtWidgets.QAbstractItemView.SingleSelection)

    def adjustWidth(self):
        w = sum([self.horizontalHeader().sectionSize(i) for i in range(self.horizontalHeader().count())])
        self.setFixedWidth(w)
        self.parentWidget().setFixedWidth(w)

    def showEvent(self, e):
        if self.isVisible():
            self.adjustWidth()
        super(CustomView, self).showEvent(e)

class MultiComboBox(QtWidgets.QComboBox):
    def setModel(self, model):
        super(MultiComboBox, self).setModel(model)
        view = CustomView(self)
        self.setView(view)

    def paintEvent(self, e):
        painter = QtWidgets.QStylePainter(self)
        painter.setPen(self.palette().color(QtGui.QPalette.Text))
        opt = QtWidgets.QStyleOptionComboBox()
        self.initStyleOption(opt)
        if self.model():
            p = self.rootModelIndex()
            t = ""
            for c in range(self.model().columnCount(p)):
                t += " " + self.model().index(self.currentIndex(), c).data()
            opt.currentText = t
            fm = QtGui.QFontMetrics(self.font())
            self.setMinimumWidth(fm.width(t))
        painter.drawComplexControl(QtWidgets.QStyle.CC_ComboBox, opt)
        painter.drawControl(QtWidgets.QStyle.CE_ComboBoxLabel, opt)

奇怪的是,我的应用程序仍然可以正常运行,而没有任何运行时请求权限。我 did 但是在清单中请求了许可。

    try {
        LocMgr = (LocationManager)getSystemService( LOCATION_SERVICE );
        LocMgr.requestLocationUpdates( K.GPS_PROVIDER, 0, 0, this );
        //LocMgr.addNmeaListener( this );   // NMEA
    }
    catch(Exception e) {
        UI.warningBox( this, "GPS appears to be either absent or disabled" );
    }

我不是很不高兴,但是我期待失败或至少是安全异常。

为什么Android Studio如此(出乎意料)如此宽容?

顺便说一下,我模块的gradle脚本包括

    uses-permission  android:name="android.permission.ACCESS_FINE_LOCATION"
    uses-permission  android:name="android.permission.ACCESS_COARSE_LOCATION"

2 个答案:

答案 0 :(得分:1)

您使用哪个版本的android来运行您的应用?在棉花糖(api级别23)之前,您可以访问很多服务,例如LocationService,而无需实际征求用户许可。

您甚至可以在未经许可的情况下使用wifi和蓝牙。那时是权限的狂野西部。从那时起,这种情况发生了变化,并且由于您的最高级别的api可能会询问您的权限(您未处理),因此才得到警告

如果您有权使用Google服务,也应该使用fusedlocationprovider,否则locationservice不会提供有效结果,除非创建服务以对其进行连续轮询。

答案 1 :(得分:0)

您的应用未在运行时中请求权限,因为您未添加代码。此外,运行时权限已添加到最新的Android(我想是从Android M开始的)上。

因此,在以前的Android版本中,您的应用程序可以正常运行,因为您只需要向清单添加权限即可。

在新版本上,您还必须在运行时另外请求权限。.权限不足并不总是会导致崩溃。.它们只能在日志等上产生警告。

无论如何,要摆脱该警告,必须在运行时请求权限。在下面,您可以找到一个小示例:

public class MainActivity extends AppCompatActivity implements LocationListener {

    private final static int LOCATION_PERMISSION_CODE = 1;

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

        ....

        try {
            LocMgr = (LocationManager) getSystemService(LOCATION_SERVICE);

            if (ActivityCompat.checkSelfPermission(this, permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED 
                  && ActivityCompat.checkSelfPermission(this, permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                // Missing both permissions. User didn't accept them yet. Request
                ActivityCompat.requestPermissions(this, new String[] {permission.ACCESS_FINE_LOCATION, permission.ACCESS_COARSE_LOCATION}, LOCATION_PERMISSION_CODE);
            } else {
                // Have permissions. Don't need to request. Just request location
                LocMgr.requestLocationUpdates( K.GPS_PROVIDER, 0, 0, this );
            }
        } catch(Exception e) {
            UI.warningBox( this, "GPS appears to be either absent or disabled" );
        }

        ....
    }

    @Override
    public void onRequestPermissionsResult(final int requestCode,
            @NonNull final String[] permissions,
            @NonNull final int[] grantResults) {
        if(requestCode == LOCATION_PERMISSION_CODE) {
            if(grantResults.length > 1
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED /* ACCESS_FINE_LOCATION */
                    && grantResults[1] == PackageManager.PERMISSION_GRANTED /* ACCESS_COARSE_LOCATION */) {
                // User accepted both permissions. request location updates
                LocMgr.requestLocationUpdates( K.GPS_PROVIDER, 0, 0, this );
            }
        }
    }
}