based on VR View sample code tutorial, how to get panorama image from url or database ?
Since the sample tutorial is load default image load assets manager and i want to know how to load it from internet/URL image link.
here my first activity
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail_kuliner);
//INITIALIZE VIEWS
nama_kul = (TextView) findViewById(R.id.nameDetail_kul);
lokasi_kul = (TextView) findViewById(R.id.lokasi_kul);
desclong_kul = (TextView) findViewById(R.id.desclong_kul);
image_kul = (ImageView) findViewById(R.id.imageDetail_kul);
//RECEIVE DATA
Intent intent=this.getIntent();
String name_kul=intent.getExtras().getString("NAME_KEY");
String lokas_kul=intent.getExtras().getString("LOKASI_KEY");
final String descshor_kul=intent.getExtras().getString("DESCSHORT_KEY");
String desclon_kul=intent.getExtras().getString("DESCLONG_KEY");
final String images_kul=intent.getExtras().getString("IMAGE_KEY");
//BIND DATA
nama_kul.setText(name_kul);
lokasi_kul.setText(lokas_kul);
desclong_kul.setText(desclon_kul);
Glide.with(this).load(images_kul).into(image_kul);
//Intent to 2nd activity
detail2ButtonStart = (ImageButton) findViewById(R.id.detail2_but);
detail2ButtonStart.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
Intent intent = new Intent(detail_kuliner.this, detail2_kuliner.class);
intent.putExtra("DESCSHORT2_KEY",descshor_kul);
intent.putExtra("IMAGE2_KEY",images_kul);
//open activity
startActivity(intent);
}
});
and this is my second activity
public class detail2_kuliner extends AppCompatActivity {
private static final String TAG = detail2_kuliner.class.getSimpleName();
private VrPanoramaView panoWidgetView;
public boolean loadImageSuccessful;
private Uri fileUri;
private Options panoOptions = new Options();
private ImageLoaderTask backgroundImageLoaderTask;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail2_kuliner);
panoWidgetView = (VrPanoramaView) findViewById(R.id.pano_view);
panoWidgetView.setEventListener(new ActivityEventListener());
handleIntent(getIntent());
}
#Override
protected void onNewIntent(Intent intent) {
Log.i(TAG, this.hashCode() + ".onNewIntent()");
setIntent(intent);
handleIntent(intent);
}
private void handleIntent(Intent intent) {
if (Intent.ACTION_VIEW.equals(intent.getAction())) {
Log.i(TAG, "ACTION_VIEW Intent recieved");
fileUri = intent.getData();
if (fileUri == null) {
Log.w(TAG, "No data uri specified. Use \"-d /path/filename\".");
} else {
Log.i(TAG, "Using file " + fileUri.toString());
}
panoOptions.inputType = intent.getIntExtra("inputType", Options.TYPE_MONO);
Log.i(TAG, "Options.inputType = " + panoOptions.inputType);
} else {
Log.i(TAG, "Intent is not ACTION_VIEW. Using default pano image.");
fileUri = null;
panoOptions.inputType = Options.TYPE_MONO;
}
if (backgroundImageLoaderTask != null) {
backgroundImageLoaderTask.cancel(true);
}
backgroundImageLoaderTask = new ImageLoaderTask();
backgroundImageLoaderTask.execute(Pair.create(fileUri, panoOptions));
}
#Override
protected void onPause() {
panoWidgetView.pauseRendering();
super.onPause();
}
#Override
protected void onResume() {
super.onResume();
panoWidgetView.resumeRendering();
}
#Override
protected void onDestroy() {
panoWidgetView.shutdown();
if (backgroundImageLoaderTask != null) {
backgroundImageLoaderTask.cancel(true);
}
super.onDestroy();
}
class ImageLoaderTask extends AsyncTask<Pair<Uri, Options>, Void, Boolean> {
#Override
protected Boolean doInBackground(Pair<Uri, Options>... fileInformation) {
Options panoOptions = null;
InputStream istr = null;
if (fileInformation == null || fileInformation.length < 1
|| fileInformation[0] == null || fileInformation[0].first == null) {
AssetManager assetManager = getAssets();
try {
istr = new URL("http://SOME URL IMAGE").openStream(); //How to get SOME URL IMAGE from intent sent at first activity
panoOptions = new Options();
panoOptions.inputType = Options.TYPE_STEREO_OVER_UNDER;
} catch (IOException e) {
Log.e(TAG, "Could not decode default bitmap: " + e);
return false;
}
} else {
try {
istr = new FileInputStream(new File(fileInformation[0].first.getPath()));
panoOptions = fileInformation[0].second;
} catch (IOException e) {
Log.e(TAG, "Could not load file: " + e);
return false;
}
}
panoWidgetView.loadImageFromBitmap(BitmapFactory.decodeStream(istr), panoOptions);
try {
istr.close();
} catch (IOException e) {
Log.e(TAG, "Could not close input stream: " + e);
}
return true;
}
}
}
so i want to adding the VR View to second activity with the data that came with the intent, the data is from the database that sent by json format, based on this tutorial VR View for android can i put the data with the intent from first activity to second activity (SOME URL IMAGE)?
thank you for the help
You can use Picasso, Glide or imageloader: example below:
Picasso.with(mContext)
.load("yoururl")
.config(Bitmap.Config.RGB_565)
.error(R.drawable.blank)
.centerInside()
.into(imageView);
Actually You can't get live from server, first you need to download from serve into your project and then use it from where you save that image in sdcard or internal folder.thanks..
Related
Hello I am facing Strange Problem I am making an gallery App which download images using volley and showing them to Viewpager called SlideActivity everything is working properly. Problem:- when I try to Download & share 1st image from viewpager nothing happens but when swipe and go to 2nd image share and download is working for 2nd image and when i swipe back to 1st image now share and download works? This is what i have done till now want some advice on this issue.Thank you in Advance!
SlideActivity.Java
public class TrendingSlideActivity extends AppCompatActivity {
private static final String URL = "API";
private ViewPager viewPager;
private Context context = TrendingSlideActivity.this;
private TrendingViewPagerAdapter adapter;
private int position;
private int currentImage;
private List<Trending> data;
private ImageView shareIcon, shareImage, downloadImage;
private int mAdCounter = 0;
#SuppressLint("ClickableViewAccessibility")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.trending_slide_activity);
viewPager = findViewById(R.id.viewPager);
ProgressBar progressBar = findViewById(R.id.progress);
shareIcon = findViewById(R.id.shareviewpager);
downloadImage = findViewById(R.id.iv_download_slide);
//final String fileName = getIntent().getStringExtra("filename");
position = getIntent().getIntExtra("pos", 0);
progressBar.setVisibility(View.VISIBLE);
StringRequest request = new StringRequest(URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("CODE", response);
GsonBuilder gsonBuilder = new GsonBuilder();
Gson gson = gsonBuilder.create();
TrendingData users = gson.fromJson(response, TrendingData.class);
data = users.getData();
adapter = new TrendingViewPagerAdapter(context, data);
viewPager.setAdapter(adapter);
viewPager.setOffscreenPageLimit(1);
viewPager.setCurrentItem(position);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(TrendingSlideActivity.this, "Something went wrong", Toast.LENGTH_SHORT).show();
}
});
RequestQueue queue = Volley.newRequestQueue(this);
queue.add(request);
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int i, float v, int i1) {
}
#Override
public void onPageSelected(int i) {
currentImage = viewPager.getCurrentItem();
final String fileName1 = data.get(currentImage).getFileName();
Toast.makeText(TrendingSlideActivity.this, "===========" + fileName1, Toast.LENGTH_SHORT).show();
final String url2 = "API" + fileName1;
new LoadImage(TrendingSlideActivity.this).execute(url2);
shareIcon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onShareItem(shareImage);
}
});
downloadImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
saveImageToGallery(shareImage);
}
});
}
#Override
public void onPageScrollStateChanged(int i) {
}
});
}
private static class LoadImage extends AsyncTask<String, Integer, Drawable> {
private WeakReference<TrendingSlideActivity> activityWeakReference;
LoadImage(TrendingSlideActivity context) {
activityWeakReference = new WeakReference<>(context);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Drawable doInBackground(String... strings) {
Bitmap bmp = null;
try {
HttpURLConnection connection = (HttpURLConnection) new URL(strings[0]).openConnection();
connection.connect();
InputStream input = connection.getInputStream();
bmp = BitmapFactory.decodeStream(input);
} catch (IOException e) {
e.printStackTrace();
}
return new BitmapDrawable(bmp);
}
#Override
protected void onPostExecute(Drawable result) {
TrendingSlideActivity activity = activityWeakReference.get();
if (activity == null) return;
activity.shareImage = new ImageView(activity);
//Add image to ImageView
activity.shareImage.setImageDrawable(result);
}
}
public void onShareItem(View v) {
// Get access to bitmap image from view
// Get access to the URI for the bitmap
Uri bmpUri = getLocalBitmapUri((ImageView) v);
if (bmpUri != null) {
// Construct a ShareIntent with link to image
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_STREAM, bmpUri);
shareIntent.setType("image/*");
// Launch sharing dialog for image
context.startActivity(Intent.createChooser(shareIntent, "Share TrendingData"));
} else {
// ...sharing failed, handle error
}
}
public Uri getLocalBitmapUri(ImageView imageView) {
// Extract Bitmap from ImageView drawable
Drawable drawable = imageView.getDrawable();
Bitmap bmp;
if (drawable instanceof BitmapDrawable) {
bmp = ((BitmapDrawable) imageView.getDrawable()).getBitmap();
} else {
return null;
}
// Store image to default external storage directory
Uri bmpUri = null;
try {
// Use methods on Context to access package-specific directories on external storage.
// This way, you don't need to request external read/write permission.
File file = new File(context.getExternalFilesDir(Environment.DIRECTORY_PICTURES), "share_image_" + System.currentTimeMillis() + ".png");
FileOutputStream out = new FileOutputStream(file);
bmp.compress(Bitmap.CompressFormat.PNG, 90, out);
out.close();
// **Warning:** This will fail for API >= 24, use a FileProvider as shown below instead.
bmpUri = Uri.fromFile(file);
} catch (IOException e) {
e.printStackTrace();
}
return bmpUri;
}
public boolean isStoragePermissionGranted() {
String TAG = "Storage Permission";
if (Build.VERSION.SDK_INT >= 23) {
if (this.checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_GRANTED) {
Log.i(TAG, "Permission is granted");
return true;
} else {
Log.i(TAG, "Permission is revoked");
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
return false;
}
} else { //permission is automatically granted on sdk<23 upon installation
Log.i(TAG, "Permission is granted");
return true;
}
}
public void saveImageToGallery(ImageView iv) {
// //to get the image from the ImageView (say iv)
// BitmapDrawable draw = (BitmapDrawable) iv.getDrawable();
// Bitmap bitmap = draw.getBitmap();
if (iv != null) {
Drawable drawable = iv.getDrawable();
Bitmap bmp = null;
if (drawable instanceof BitmapDrawable) {
bmp = ((BitmapDrawable) iv.getDrawable()).getBitmap();
} else {
}
FileOutputStream outStream = null;
String sdCard = Environment.getExternalStorageDirectory().toString();
if (isStoragePermissionGranted()) {
File dir = new File(sdCard, "/GalleryApp");
if (!dir.exists()) {
dir.mkdirs();
}
try {
String fileName = String.format("%d.jpg", System.currentTimeMillis());
File outFile = new File(dir, fileName);
outStream = new FileOutputStream(outFile);
assert bmp != null;
bmp.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
outStream.flush();
outStream.close();
Toast.makeText(TrendingSlideActivity.this, "Saved", Toast.LENGTH_SHORT).show();
Log.i("TAAAAAAAAAAAAG", "onPictureTaken - wrote to " + outFile.getAbsolutePath());
String filePath = outFile.getPath();
MediaScannerConnection.scanFile(this,
new String[]{filePath}, null,
new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
Log.i("ExternalStorage", "Scanned " + path + ":");
Log.i("ExternalStorage", "-> uri=" + uri);
}
});
} catch (IOException e) {
e.printStackTrace();
}
}
}else {
Toast.makeText(TrendingSlideActivity.this,"Please Wait Image is Loading...",Toast.LENGTH_SHORT).show();
}
}
}
UPDATED ANSWER:
Reason why it isn't working is that you're setting image view inside onPageSelected() , and that method is not called for the first page, it's activated just after swiping.
Solution for this is move the entire code from onPageSelected() into function selectImage(int position) and call that function inside onPageSelected() as
selectImage(i).
This would be an improved version for code above, and will do the same as before, but now it's possible to set default state for the first view by calling
selectImage(0) after viewPager.setCurrentItem(position)
I have created an application where one can view images. The problem I am facing is that when I use ".nomedia" in folder it hides images from gallery and images are also hidden in my application. I need a method with help of which images can remain hidden from gallery but shown in my application. I am accessing images using path of folder.
Code:
public class SdActivity extends Activity implements
MediaScannerConnectionClient {
public String[] allFiles;
private String SCAN_PATH;
private static final String FILE_TYPE = "*/*";
private MediaScannerConnection conn;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
File folder = new File("/sdcard/DCIM");
allFiles = folder.list();
// uriAllFiles= new Uri[allFiles.length];
for (int i = 0; i < allFiles.length; i++) {
Log.d("all file path" + i, allFiles[i] + allFiles.length);
}
// Uri uri= Uri.fromFile(new
// File(Environment.getExternalStorageDirectory().toString()+"/yourfoldername/"+allFiles[0]));
SCAN_PATH = Environment.getExternalStorageDirectory().toString()
+ "/yourfoldername/" + allFiles[0];
Log.d("SCAN PATH", "Scan Path " + SCAN_PATH);
Button scanBtn = (Button) findViewById(R.id.buttonLoadPicture);
scanBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
startScan();
}
});
}
private void startScan() {
Log.d("Connected", "success" + conn);
if (conn != null) {
conn.disconnect();
}
conn = new MediaScannerConnection(this, this);
conn.connect();
}
#Override
public void onMediaScannerConnected() {
Log.d("onMediaScannerConnected", "success" + conn);
conn.scanFile(SCAN_PATH, FILE_TYPE);
}
#Override
public void onScanCompleted(String path, Uri uri) {
try {
Log.d("onScanCompleted", uri + "success" + conn);
if (uri != null) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(uri);
startActivity(intent);
}
} finally {
conn.disconnect();
conn = null;
}
}
}
My application should take pictures in background at a specific time of the day. I am going to use AlarmManager but I am wondering whether the class which implements the behavior of my application (i.e., taking a picture) should extend Service or BroadcastReceiver. What do you think?
You should use IntentSerivce with AlaramManger and define the BroadcastReceiver on your activity.
public class DownloadService extends IntentService {
private int result = Activity.RESULT_CANCELED;
public static final String URL = "urlpath";
public static final String FILENAME = "filename";
public static final String FILEPATH = "filepath";
public static final String RESULT = "result";
public static final String NOTIFICATION = "com.vogella.android.service.receiver";
public DownloadService() {
super("DownloadService");
}
// Will be called asynchronously be Android
#Override
protected void onHandleIntent(Intent intent) {
String urlPath = intent.getStringExtra(URL);
String fileName = intent.getStringExtra(FILENAME);
File output = new File(Environment.getExternalStorageDirectory(),
fileName);
if (output.exists()) {
output.delete();
}
InputStream stream = null;
FileOutputStream fos = null;
try {
URL url = new URL(urlPath);
stream = url.openConnection().getInputStream();
InputStreamReader reader = new InputStreamReader(stream);
fos = new FileOutputStream(output.getPath());
int next = -1;
while ((next = reader.read()) != -1) {
fos.write(next);
}
// Successful finished
result = Activity.RESULT_OK;
} catch (Exception e) {
e.printStackTrace();
} finally {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
publishResults(output.getAbsolutePath(), result);
}
private void publishResults(String outputPath, int result) {
Intent intent = new Intent(NOTIFICATION);
intent.putExtra(FILEPATH, outputPath);
intent.putExtra(RESULT, result);
sendBroadcast(intent);
}
}
public class MainActivity extends Activity {
private TextView textView;
private BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Bundle bundle = intent.getExtras();
if (bundle != null) {
String string = bundle.getString(DownloadService.FILEPATH);
int resultCode = bundle.getInt(DownloadService.RESULT);
if (resultCode == RESULT_OK) {
Toast.makeText(MainActivity.this,
"Download complete. Download URI: " + string,
Toast.LENGTH_LONG).show();
textView.setText("Download done");
} else {
Toast.makeText(MainActivity.this, "Download failed",
Toast.LENGTH_LONG).show();
textView.setText("Download failed");
}
}
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.status);
}
#Override
protected void onResume() {
super.onResume();
registerReceiver(receiver, new IntentFilter(DownloadService.NOTIFICATION));
}
#Override
protected void onPause() {
super.onPause();
unregisterReceiver(receiver);
}
public void onClick(View view) {
Intent intent = new Intent(this, DownloadService.class);
PendingIntent pintent = PendingIntent.getService(this, 0, intent, 0);
AlarmManager alarm = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
// Start every 30 seconds
alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), 30*1000, pintent);
}
}
I'm creating a Fake Camera/Gallery app that just automatically return a random image. I tied it to the ACTION_PICK & IMAGE_CAPTURE intent filters.
However for the Gallery (PICK) code, after calling finish, it doesn't seem to be returning to the calling app.
Here's my code:
public class MainActivity extends Activity {
final static int[] photos = { R.drawable.android_1, R.drawable.android_2,
R.drawable.android_3 };
static int lastPhotoIndex = -1;
private final static String TAG = "FakeCameraGallery";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String action = getIntent().getAction();
if (action.contains("PICK")) {
//Act as Gallery
InputStream in = getResources().openRawResource(getNextPhoto());
Bitmap bm = BitmapFactory.decodeStream(in);
Bundle extras = new Bundle();
extras.putParcelable("data", bm);
Intent result = getIntent().putExtras(extras);
if (getParent() == null) {
setResult(Activity.RESULT_OK, result);
} else {
getParent().setResult(Activity.RESULT_OK, result);
}
} else {
//act as Camera
prepareToSnapPicture();
}
finish();
}
private void prepareToSnapPicture() {
checkSdCard();
Intent intent = getIntent();
if (intent.getExtras() != null) {
snapPicture(intent);
setResult(RESULT_OK);
} else {
Log.i(TAG, "Unable to capture photo. Missing Intent Extras.");
setResult(RESULT_CANCELED);
}
}
private void checkSdCard() {
if (!Environment.MEDIA_MOUNTED.equals(Environment
.getExternalStorageState())) {
Toast.makeText(this, "External SD card not mounted",
Toast.LENGTH_LONG).show();
Log.i(TAG, "External SD card not mounted");
}
}
private void snapPicture(Intent intent) {
try {
this.copyFile(getPicturePath(intent));
Toast.makeText(this, "Click!", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
Log.i(TAG, "Can't copy photo");
e.printStackTrace();
}
}
private File getPicturePath(Intent intent) {
Uri uri = (Uri) intent.getExtras().get(MediaStore.EXTRA_OUTPUT);
return new File(uri.getPath());
}
private void copyFile(File destination) throws IOException {
InputStream in = getResources().openRawResource(getNextPhoto());
OutputStream out = new FileOutputStream(destination);
byte[] buffer = new byte[1024];
int length;
if (in != null) {
Log.i(TAG, "Input photo stream is null");
while ((length = in.read(buffer)) > 0) {
out.write(buffer, 0, length);
}
in.close();
}
out.close();
}
private int getNextPhoto() {
if (lastPhotoIndex == photos.length - 1) {
lastPhotoIndex = -1;
}
return photos[++lastPhotoIndex];
}
}
Your code looks fine: are you calling it using startActivityForResult?
I am making an app in whic h i hava to you stream you tube video and show in my app but i am getting error message an error occured during retrieval of video.My code snippet is as follows:
public class Rads extends Activity {
public static final String SCHEME_YOUTUBE_VIDEO = "ytv";
public static final String SCHEME_YOUTUBE_PLAYLIST = "ytpl";
static final String YOUTUBE_VIDEO_INFORMATION_URL = "http://www.youtube.com/get_video_info?&video_id=";
static final String YOUTUBE_PLAYLIST_ATOM_FEED_URL = "http://gdata.youtube.com/feeds/api/playlists/";
protected ProgressBar mProgressBar;
protected TextView mProgressMessage;
protected VideoView mVideoView;
public final static String MSG_INIT = "com.keyes.video.msg.init";
protected String mMsgInit = "Initializing";
public final static String MSG_DETECT = "com.keyes.video.msg.detect";
protected String mMsgDetect = "Detecting Bandwidth";
public final static String MSG_PLAYLIST = "com.keyes.video.msg.playlist";
protected String mMsgPlaylist = "Determining Latest Video in YouTube Playlist";
public final static String MSG_TOKEN = "com.keyes.video.msg.token";
protected String mMsgToken = "Retrieving YouTube Video Token";
public final static String MSG_LO_BAND = "com.keyes.video.msg.loband";
protected String mMsgLowBand = "Buffering Low-bandwidth Video";
public final static String MSG_HI_BAND = "com.keyes.video.msg.hiband";
protected String mMsgHiBand = "Buffering High-bandwidth Video";
public final static String MSG_ERROR_TITLE = "com.keyes.video.msg.error.title";
protected String mMsgErrorTitle = "Communications Error";
public final static String MSG_ERROR_MSG = "com.keyes.video.msg.error.msg";
protected String mMsgError = "An error occurred during the retrieval of the video. This could be due to network issues or YouTube protocols. Please try again later.";
/** Background task on which all of the interaction with YouTube is done */
protected QueryYouTubeTask mQueryYouTubeTask;
protected String mVideoId = null;
#Override
protected void onCreate(Bundle pSavedInstanceState) {
super.onCreate(pSavedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
// create the layout of the view
setupView();
// determine the messages to be displayed as the view loads the video
extractMessages();
// set the flag to keep the screen ON so that the video can play without the screen being turned off
getWindow().setFlags(android.view.WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, android.view.WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
mProgressBar.bringToFront();
mProgressBar.setVisibility(View.VISIBLE);
mProgressMessage.setText(mMsgInit);
// extract the playlist or video id from the intent that started this video
Uri lVideoIdUri = this.getIntent().getData();
if(lVideoIdUri == null){
Log.i(this.getClass().getSimpleName(), "No video ID was specified in the intent. Closing video activity.");
finish();
}
String lVideoSchemeStr = lVideoIdUri.getScheme();
String lVideoIdStr = lVideoIdUri.getEncodedSchemeSpecificPart();
if(lVideoIdStr == null){
Log.i(this.getClass().getSimpleName(), "No video ID was specified in the intent. Closing video activity.");
finish();
}
if(lVideoIdStr.startsWith("//")){
if(lVideoIdStr.length() > 2){
lVideoIdStr = lVideoIdStr.substring(2);
} else {
Log.i(this.getClass().getSimpleName(), "No video ID was specified in the intent. Closing video activity.");
finish();
}
}
///////////////////
// extract either a video id or a playlist id, depending on the uri scheme
YouTubeId lYouTubeId = null;
if(lVideoSchemeStr != null && lVideoSchemeStr.equalsIgnoreCase(SCHEME_YOUTUBE_PLAYLIST)){
lYouTubeId = new PlaylistId(lVideoIdStr);
}
else if(lVideoSchemeStr != null && lVideoSchemeStr.equalsIgnoreCase(SCHEME_YOUTUBE_VIDEO)){
lYouTubeId = new VideoId(lVideoIdStr);
}
if(lYouTubeId == null){
Log.i(this.getClass().getSimpleName(), "Unable to extract video ID from the intent. Closing video activity.");
finish();
}
mQueryYouTubeTask = (QueryYouTubeTask) new QueryYouTubeTask().execute(lYouTubeId);
}
/**
* Determine the messages to display during video load and initialization.
*/
private void extractMessages() {
Intent lInvokingIntent = getIntent();
String lMsgInit = lInvokingIntent.getStringExtra(MSG_INIT);
if(lMsgInit != null){
mMsgInit = lMsgInit;
}
String lMsgDetect = lInvokingIntent.getStringExtra(MSG_DETECT);
if(lMsgDetect != null){
mMsgDetect = lMsgDetect;
}
String lMsgPlaylist = lInvokingIntent.getStringExtra(MSG_PLAYLIST);
if(lMsgPlaylist != null){
mMsgPlaylist = lMsgPlaylist;
}
String lMsgToken = lInvokingIntent.getStringExtra(MSG_TOKEN);
if(lMsgToken != null){
mMsgToken = lMsgToken;
}
String lMsgLoBand = lInvokingIntent.getStringExtra(MSG_LO_BAND);
if(lMsgLoBand != null){
mMsgLowBand = lMsgLoBand;
}
String lMsgHiBand = lInvokingIntent.getStringExtra(MSG_HI_BAND);
if(lMsgHiBand != null){
mMsgHiBand = lMsgHiBand;
}
String lMsgErrTitle = lInvokingIntent.getStringExtra(MSG_ERROR_TITLE);
if(lMsgErrTitle != null){
mMsgErrorTitle = lMsgErrTitle;
}
String lMsgErrMsg = lInvokingIntent.getStringExtra(MSG_ERROR_MSG);
if(lMsgErrMsg != null){
mMsgError = lMsgErrMsg;
}
}
/**
* Create the view in which the video will be rendered.
*/
private void setupView() {
LinearLayout lLinLayout = new LinearLayout(this);
lLinLayout.setId(1);
lLinLayout.setOrientation(LinearLayout.VERTICAL);
lLinLayout.setGravity(Gravity.CENTER);
lLinLayout.setBackgroundColor(Color.BLACK);
LayoutParams lLinLayoutParms = new LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT);
lLinLayout.setLayoutParams(lLinLayoutParms);
this.setContentView(lLinLayout);
RelativeLayout lRelLayout = new RelativeLayout(this);
lRelLayout.setId(2);
lRelLayout.setGravity(Gravity.CENTER);
lRelLayout.setBackgroundColor(Color.BLACK);
android.widget.RelativeLayout.LayoutParams lRelLayoutParms = new android.widget.RelativeLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT);
lRelLayout.setLayoutParams(lRelLayoutParms);
lLinLayout.addView(lRelLayout);
mVideoView = new VideoView(this);
mVideoView.setId(3);
android.widget.RelativeLayout.LayoutParams lVidViewLayoutParams = new android.widget.RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
lVidViewLayoutParams.addRule(RelativeLayout.CENTER_IN_PARENT);
mVideoView.setLayoutParams(lVidViewLayoutParams);
lRelLayout.addView(mVideoView);
mProgressBar = new ProgressBar(this);
mProgressBar.setIndeterminate(true);
mProgressBar.setVisibility(View.VISIBLE);
mProgressBar.setEnabled(true);
mProgressBar.setId(4);
android.widget.RelativeLayout.LayoutParams lProgressBarLayoutParms = new android.widget.RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
lProgressBarLayoutParms.addRule(RelativeLayout.CENTER_IN_PARENT);
mProgressBar.setLayoutParams(lProgressBarLayoutParms);
lRelLayout.addView(mProgressBar);
mProgressMessage = new TextView(this);
mProgressMessage.setId(5);
android.widget.RelativeLayout.LayoutParams lProgressMsgLayoutParms = new android.widget.RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
lProgressMsgLayoutParms.addRule(RelativeLayout.CENTER_HORIZONTAL);
lProgressMsgLayoutParms.addRule(RelativeLayout.BELOW, 4);
mProgressMessage.setLayoutParams(lProgressMsgLayoutParms);
mProgressMessage.setTextColor(Color.LTGRAY);
mProgressMessage.setTextSize(TypedValue.COMPLEX_UNIT_SP, 12);
mProgressMessage.setText("...");
lRelLayout.addView(mProgressMessage);
}
#Override
protected void onDestroy() {
super.onDestroy();
YouTubeUtility.markVideoAsViewed(this, mVideoId);
if(mQueryYouTubeTask != null){
mQueryYouTubeTask.cancel(true);
}
if(mVideoView != null){
mVideoView.stopPlayback();
}
// clear the flag that keeps the screen ON
getWindow().clearFlags(android.view.WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
this.mQueryYouTubeTask = null;
this.mVideoView = null;
}
public void updateProgress(String pProgressMsg){
try {
mProgressMessage.setText(pProgressMsg);
} catch(Exception e) {
Log.e(this.getClass().getSimpleName(), "Error updating video status!", e);
}
}
private class ProgressUpdateInfo {
public String mMsg;
public ProgressUpdateInfo(String pMsg){
mMsg = pMsg;
}
}
/**
* Task to figure out details by calling out to YouTube GData API. We only use public methods that
* don't require authentication.
*
*/
private class QueryYouTubeTask extends AsyncTask<YouTubeId, ProgressUpdateInfo, Uri> {
private boolean mShowedError = false;
#Override
protected Uri doInBackground(YouTubeId... pParams) {
String lUriStr = null;
String lYouTubeFmtQuality = "17"; // 3gpp medium quality, which should be fast enough to view over EDGE connection
String lYouTubeVideoId = null;
if(isCancelled())
return null;
try {
publishProgress(new ProgressUpdateInfo(mMsgDetect));
WifiManager lWifiManager = (WifiManager) Rads.this.getSystemService(Context.WIFI_SERVICE);
TelephonyManager lTelephonyManager = (TelephonyManager) Rads.this.getSystemService(Context.TELEPHONY_SERVICE);
////////////////////////////
// if we have a fast connection (wifi or 3g), then we'll get a high quality YouTube video
if( (lWifiManager.isWifiEnabled() && lWifiManager.getConnectionInfo() != null && lWifiManager.getConnectionInfo().getIpAddress() != 0) ||
( (lTelephonyManager.getNetworkType() == TelephonyManager.NETWORK_TYPE_UMTS ||
/* icky... using literals to make backwards compatible with 1.5 and 1.6 */
lTelephonyManager.getNetworkType() == 9 /*HSUPA*/ ||
lTelephonyManager.getNetworkType() == 10 /*HSPA*/ ||
lTelephonyManager.getNetworkType() == 8 /*HSDPA*/ ||
lTelephonyManager.getNetworkType() == 5 /*EVDO_0*/ ||
lTelephonyManager.getNetworkType() == 6 /*EVDO A*/)
&& lTelephonyManager.getDataState() == TelephonyManager.DATA_CONNECTED)
){
lYouTubeFmtQuality = "18";
}
///////////////////////////////////
// if the intent is to show a playlist, get the latest video id from the playlist, otherwise the video
// id was explicitly declared.
if(pParams[0] instanceof PlaylistId){
publishProgress(new ProgressUpdateInfo(mMsgPlaylist));
lYouTubeVideoId = YouTubeUtility.queryLatestPlaylistVideo((PlaylistId) pParams[0]);
}
else if(pParams[0] instanceof VideoId){
lYouTubeVideoId = pParams[0].getId();
}
mVideoId = lYouTubeVideoId;
publishProgress(new ProgressUpdateInfo(mMsgToken));
if(isCancelled())
return null;
////////////////////////////////////
// calculate the actual URL of the video, encoded with proper YouTube token
lUriStr = YouTubeUtility.calculateYouTubeUrl(lYouTubeFmtQuality, true, lYouTubeVideoId);
if(isCancelled())
return null;
if(lYouTubeFmtQuality.equals("17")){
publishProgress(new ProgressUpdateInfo(mMsgLowBand));
} else {
publishProgress(new ProgressUpdateInfo(mMsgHiBand));
}
} catch(Exception e) {
Log.e(this.getClass().getSimpleName(), "Error occurred while retrieving information from YouTube.", e);
}
if(lUriStr != null){
return Uri.parse(lUriStr);
} else {
return null;
}
}
#Override
protected void onPostExecute(Uri pResult) {
super.onPostExecute(pResult);
try {
if(isCancelled())
return;
if(pResult == null){
throw new RuntimeException("Invalid NULL Url.");
}
mVideoView.setVideoURI(pResult);
if(isCancelled())
return;
// TODO: add listeners for finish of video
mVideoView.setOnCompletionListener(new OnCompletionListener(){
public void onCompletion(MediaPlayer pMp) {
if(isCancelled())
return;
Rads.this.finish();
}
});
if(isCancelled())
return;
final MediaController lMediaController = new MediaController(Rads.this);
mVideoView.setMediaController(lMediaController);
lMediaController.show(0);
//mVideoView.setKeepScreenOn(true);
mVideoView.setOnPreparedListener( new MediaPlayer.OnPreparedListener() {
public void onPrepared(MediaPlayer pMp) {
if(isCancelled())
return;
Rads.this.mProgressBar.setVisibility(View.GONE);
Rads.this.mProgressMessage.setVisibility(View.GONE);
}
});
if(isCancelled())
return;
mVideoView.requestFocus();
mVideoView.start();
} catch(Exception e){
Log.e(this.getClass().getSimpleName(), "Error playing video!", e);
if(!mShowedError){
showErrorAlert();
}
}
}
private void showErrorAlert() {
try {
Builder lBuilder = new AlertDialog.Builder(Rads.this);
lBuilder.setTitle(mMsgErrorTitle);
lBuilder.setCancelable(false);
lBuilder.setMessage(mMsgError);
lBuilder.setPositiveButton("OK", new DialogInterface.OnClickListener(){
public void onClick(DialogInterface pDialog, int pWhich) {
Rads.this.finish();
}
});
AlertDialog lDialog = lBuilder.create();
lDialog.show();
} catch(Exception e){
Log.e(this.getClass().getSimpleName(), "Problem showing error dialog.", e);
}
}
#Override
protected void onProgressUpdate(ProgressUpdateInfo... pValues) {
super.onProgressUpdate(pValues);
Rads.this.updateProgress(pValues[0].mMsg);
}
}
#Override
protected void onStart() {
super.onStart();
}
#Override
protected void onStop() {
super.onStop();
}
}