com.packpublishing.asynchronousandroid.chapter5.UploadArtworkActivity.java Source code

Java tutorial

Introduction

Here is the source code for com.packpublishing.asynchronousandroid.chapter5.UploadArtworkActivity.java

Source

/*
 *  This code is part of "Asynchronous Android Programming".
 *
 *  Copyright (C) 2016 Helder Vasconcelos (heldervasc@bearstouch.com)
 *  Copyright (C) 2016 Packt Publishing
 *
 *  Permission is hereby granted, free of charge, to any person obtaining
 *  a copy of this software and associated documentation files (the
 *  "Software"), to deal in the Software without restriction, including
 *  without limitation the rights to use, copy, modify, merge, publish,
 *  distribute, sublicense, and/or sell copies of the Software, and to
 *  permit persons to whom the Software is furnished to do so, subject to
 *  the following conditions:
 *  
 */
package com.packpublishing.asynchronousandroid.chapter5;

import android.Manifest;
import android.content.ContentUris;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.LoaderManager.LoaderCallbacks;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;

public class UploadArtworkActivity extends FragmentActivity implements LoaderCallbacks<Cursor> {

    public static final int ALBUM_LIST_LOADER = "phone_list".hashCode();
    private AlbumCursorAdapter mAdapter;

    private static final int MY_PERMISSIONS_READ_EXTERNAL_STORAGE = 1;

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

        // Here, thisActivity is the current activity
        if (ContextCompat.checkSelfPermission(UploadArtworkActivity.this,
                Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {

            // Should we show an explanation?
            if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                    Manifest.permission.READ_EXTERNAL_STORAGE)) {

                // Show an expanation to the user *asynchronously* -- don't block
                // this thread waiting for the user's response! After the user
                // sees the explanation, try again to request the permission.

            } else {

                // No explanation needed, we can request the permission.

                ActivityCompat.requestPermissions(this, new String[] { Manifest.permission.READ_EXTERNAL_STORAGE },
                        MY_PERMISSIONS_READ_EXTERNAL_STORAGE);

                // MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
                // app-defined int constant. The callback method gets the
                // result of the request.
            }
        } else {
            initAlbumList();
        }
    }

    void initAlbumList() {
        GridView grid = (GridView) findViewById(R.id.album_grid);
        mAdapter = new AlbumCursorAdapter(getApplicationContext(), getSupportLoaderManager());
        grid.setAdapter(mAdapter);

        grid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Cursor cursor = (Cursor) mAdapter.getItem(position);
                int albumId = cursor.getInt(cursor.getColumnIndex(MediaStore.Audio.Albums._ID));
                Uri sArtworkUri = Uri.parse("content://media/external/audio/albumart");
                Uri albumArtUri = ContentUris.withAppendedId(sArtworkUri, albumId);
                Intent intent = new Intent(UploadArtworkActivity.this, UploadArtworkIntentService.class);
                intent.setData(albumArtUri);
                startService(intent);
            }
        });
        getSupportLoaderManager().initLoader(ALBUM_LIST_LOADER, null, UploadArtworkActivity.this);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
        switch (requestCode) {
        case MY_PERMISSIONS_READ_EXTERNAL_STORAGE: {
            // If request is cancelled, the result arrays are empty.
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                // permission was granted, yay! Do the
                // contacts-related task you need to do.
                initAlbumList();
            } else {

                // permission denied, boo! Disable the
                // functionality that depends on this permission.
            }
            return;
        }
        // other 'case' lines to check for other
        // permissions this app might request
        }
    }

    @Override
    public Loader<Cursor> onCreateLoader(int id, Bundle args) {
        String[] columns = new String[] { MediaStore.Audio.Albums._ID, MediaStore.Audio.Albums.ARTIST,
                MediaStore.Audio.Albums.ALBUM, MediaStore.Audio.Albums.ALBUM_ART };
        return new CursorLoader(this, MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI, columns, // projection
                null, // selection
                null, // selectionArgs
                null // sortOrder
        );
    }

    @Override
    public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
        // Swap the new cursor in.  (The framework will take care of closing the
        // old cursor once we return.)
        mAdapter.changeCursor(data);
    }

    @Override
    public void onLoaderReset(Loader<Cursor> loader) {
        // This is called when the last Cursor provided to onLoadFinished()
        // above is about to be closed.  We need to make sure we are no
        // longer using it.
        mAdapter.changeCursor(null);
    }

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

        if (isFinishing()) {
            getSupportLoaderManager().destroyLoader(ALBUM_LIST_LOADER);
            mAdapter.destroyLoaders();
        }
    }
}