Android要求多种权限

时间:2017-06-06 12:26:57

标签: java android permissions

我有一个应用需要首先获得两个权限,阅读联系人并在extrernal存储中写入文件。问题是,当应用程序第一次打开时崩溃并要求权限,当我重新打开它时,一切都很好,应用程序运行顺利。 MainActivity.java

public class MainActivity extends AppCompatActivity implements
        LoaderManager.LoaderCallbacks<Cursor>,
        AdapterView.OnItemClickListener,
        GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener
        {


    /**
     * Global variables
     */
    private static final int PERMISSIONS_REQUEST_READ_CONTACTS = 100;
    private ListView mContactsList; //the listview to display contacts
    private LinearLayout contactLayout; //the listview item layout for each contact
    private SimpleCursorAdapter mCursorAdapter; // An adapter that binds the result Cursor to the ListView
    private boolean bigmode = false; //flag indicating whether we are currently using the normal or big contact layout
    public GoogleApiClient mApiClient; //client to the google play services activity detection
    private int activityDetectionInterval = 3000; //how often to request an activity detection in milliseconds

    /*
     * Defines an array that contains column names to move from
     * the Cursor to the ListView (we really just want the name).
     */


    private final static String[] FROM_COLUMNS = {
            ContactsContract.Contacts.DISPLAY_NAME
    };

    /*
     * Defines an array that contains column names to retrieve from the
     * contacts DB when we query it (we really just want the name).
     */

    private static final String[] PROJECTION =
            {
                    ContactsContract.Contacts._ID,
                    ContactsContract.Contacts.DISPLAY_NAME
            };


    /*
     * Defines an array that contains resource ids for the listview item layout views
     * that get the Cursor column contents.
     */

    private final static int[] TO_IDS = {
            R.id.label
    };

    /**
     * Methods
     */

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

       /* showContacts(); // Ask permission to read contacts
        showlogs(); // Ask permission to create file where we write the logs*/

        setContentView(R.layout.activity_main);

        // set up the action toolbar

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        // set up the listview by retrieving contacts

        mContactsList = (ListView) findViewById(R.id.listView);
        //setup an adapter to populate the listview
        mCursorAdapter = new SimpleCursorAdapter(
                this,
                R.layout.contacts_list_item,
                null,
                FROM_COLUMNS, TO_IDS,
                0);

            // Sets the adapter for the ListView
        mContactsList.setAdapter(mCursorAdapter);
        // set up the listener for the listview - it will be handled by code in this activity
        mContactsList.setOnItemClickListener(this);
        //call the cursor loader
        getLoaderManager().initLoader(0, null, this);
        // set up the "zoom" button

        final FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        // set up the click action - toggle between big and normal layouts
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                toggleDisplaySize();
            }
        });

        // set up the client for google play services so we can request activity detection later
        Log.i("START", "Start");
        writefile("START");
        mApiClient = new GoogleApiClient.Builder(this)
                .addApi(ActivityRecognition.API)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .build();
        mApiClient.connect();

                mContactsList.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                Log.i("Scroll", "Scroll list"); // When user scrolled the list
                writefile("SCROLL");
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {

            }
        });}


    @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);
    }

    /**
     * when the application is ready to be brought to the front, we must assess whether to use
     * the big or normal layouts
     */
    @Override
    public void onResume() {
        super.onResume();

        //check the shared preference value set by the activity detection service

        SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
        if (sp.getBoolean("isWalking", false)) {
            bigmode = false;
        } else {
            bigmode = true;
        }
        //set the appropriate layout for the listview
        toggleDisplaySize();

    }

    @Override
    public Loader<Cursor> onCreateLoader(int i, Bundle bundle) {
        // Starts the query and returns the result cursor

        // we only want the "name" column and also we want it sorted alphabetically
        return new CursorLoader(
                this,
                ContactsContract.Contacts.CONTENT_URI,
                PROJECTION,
                null,
                null,
                "DISPLAY_NAME ASC"
        );
    }

    @Override
    public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
        // Put the result Cursor in the adapter for the ListView
        //Log.i("CursorLoaderFinished", "retrieved "+ cursor.getCount()+" contacts");
        mCursorAdapter.swapCursor(cursor);
    }

    @Override
    public void onLoaderReset(Loader<Cursor> loader) {
        // Delete the reference to the existing Cursor
        mCursorAdapter.swapCursor(null);
    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
        // show a toast with the contact name
        Log.i("onItemClick", "Click");
        writefile("CLICK "+String.valueOf(((TextView) view.findViewById(R.id.label)).getText()));
        Log.i("Name", String.valueOf(((TextView) view.findViewById(R.id.label)).getText()));
        //writefile(String.valueOf(((TextView) view.findViewById(R.id.label)).getText()));
        Toast.makeText(this, ((TextView) view.findViewById(R.id.label)).getText(), Toast.LENGTH_SHORT).show();
    }

    /**
     * the google play services client is ready, now we can start requesting activity
     * detection updates from it
     */
    @Override
    public void onConnected(@Nullable Bundle bundle) {
        //create an intent pointing to the background service which will update our current activity
        Intent intent = new Intent(this, ActivityRecognizedService.class);
        PendingIntent pendingIntent = PendingIntent.getService(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        //request updates
        ActivityRecognition.ActivityRecognitionApi.requestActivityUpdates(mApiClient, activityDetectionInterval, pendingIntent);

    }

    @Override
    public void onConnectionSuspended(int i) {

    }

    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

    }

    /**
     * this method selects and sets the appropriate listview layout according to whether we should
     * be in big or normal mode (either from a zoom button click, or because the service has detected
     * that we are currently walking
     */
    public void toggleDisplaySize() {

        int layoutid;
        if (!bigmode) {
            Log.i("ZOOM", "1");//ZOOM IN
            writefile("ZOOM_1");
            layoutid = R.layout.contacts_list_item_big;
            bigmode = true;
        } else {
            Log.i("ZOOM", "0");//ZOOM OUT
            writefile("ZOOM_0");
            layoutid = R.layout.contacts_list_item;
            bigmode = false;
        }

        mCursorAdapter = new SimpleCursorAdapter(
                getApplicationContext(),
                layoutid,
                null,
                FROM_COLUMNS, TO_IDS,
                0);
        mContactsList.setAdapter(mCursorAdapter);
        getLoaderManager().initLoader(0, null, MainActivity.this);

    }


/*
    private void showContacts() {
        // Check the SDK version and whether the permission is already granted or not. To get te contacts
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && checkSelfPermission(Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED) {
            requestPermissions(new String[]{Manifest.permission.READ_CONTACTS}, PERMISSIONS_REQUEST_READ_CONTACTS);
            ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
        }
    }

    private void showlogs() {
        //Check the SDK version and whether the permission is already granted or not. To be able to create and write in file
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
            }
        }

    }*/
public void askpermissions(){
    int PERMISSION_ALL = 1;
    String[] PERMISSIONS = {Manifest.permission.READ_CONTACTS, Manifest.permission.WRITE_EXTERNAL_STORAGE};

    if(!hasPermissions(this, PERMISSIONS)){
        ActivityCompat.requestPermissions(this, PERMISSIONS, PERMISSION_ALL);
    }

}

public static boolean hasPermissions(Context context, String... permissions) {
    if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && context != null && permissions != null) {
        for (String permission : permissions) {
            if (ActivityCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }
    }
    return true;
}

    public void writefile(String te){
        //Write in file the logs
        te =gettime()+' '+te+'\n';
        File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), "Logs");
        if (! file.exists()){
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        FileWriter fileWriter = null;
        try {
            fileWriter = new FileWriter(file,true);
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            fileWriter.write(te);
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            fileWriter.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            fileWriter.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


public String gettime(){
    String timeStamp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new java.util.Date());
    return timeStamp;


}

}

我通过askpermissions()请求许可;函数......我的代码有什么可能是错的???

1 个答案:

答案 0 :(得分:-1)

像这样编辑你的代码

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

   /* showContacts(); // Ask permission to read contacts
    showlogs(); // Ask permission to create file where we write the logs*/

    setContentView(R.layout.activity_main);

    // set up the action toolbar

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    // set up the listview by retrieving contacts

    mContactsList = (ListView) findViewById(R.id.listView);
    //setup an adapter to populate the listview
    mCursorAdapter = new SimpleCursorAdapter(
            this,
            R.layout.contacts_list_item,
            null,
            FROM_COLUMNS, TO_IDS,
            0);

        // Sets the adapter for the ListView
    mContactsList.setAdapter(mCursorAdapter);
    // set up the listener for the listview - it will be handled by code in this activity
    mContactsList.setOnItemClickListener(this);
    //call the cursor loader
    getLoaderManager().initLoader(0, null, this);
    // set up the "zoom" button

    final FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    // set up the click action - toggle between big and normal layouts
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            toggleDisplaySize();
        }
    });

    // set up the client for google play services so we can request activity detection later

askpermissions();
    }


void permissionGranted()
{ Log.i("START", "Start");
    writefile("START");
    mApiClient = new GoogleApiClient.Builder(this)
            .addApi(ActivityRecognition.API)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .build();
    mApiClient.connect();

            mContactsList.setOnScrollListener(new AbsListView.OnScrollListener() {
        @Override
        public void onScrollStateChanged(AbsListView view, int scrollState) 
    {
                Log.i("Scroll", "Scroll list"); // When user scrolled the list
                writefile("SCROLL");
        }

        @Override
        public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {

        }
    });}

public static boolean hasPermissions(Context context, String... permissions) {
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && context != null && permissions != null) {
    for (String permission : permissions) {
        if (ActivityCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED) {
            return false;
        }else{
permissionGranted();}
    }
}
return true;
}

public void askpermissions(){
int PERMISSION_ALL = 1;
String[] PERMISSIONS = {Manifest.permission.READ_CONTACTS, Manifest.permission.WRITE_EXTERNAL_STORAGE};

if(!hasPermissions(this, PERMISSIONS)){
    ActivityCompat.requestPermissions(this, PERMISSIONS, PERMISSION_ALL);
}else 
permissionGranted();
}