I have a camera application that can also record video. (Im developing on samsung S3)
I want to be able to open the gallery on the last recorded video.
I use this code:
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse(file.getAbsolutePath()), "video/3gpp");
startActivity(intent);
The problem with that code is that the video immediately starts, and when it ends
the gallery activity close.
I want to be able to open the video without playing it, exactly like in my samsung S3.
thanks in advance!
To open particular image we can use this .. and its worked .
so please check with your requirement. Hope this will helps you..
import java.io.File;
import android.app.Activity;
import android.content.Intent;
import android.media.MediaScannerConnection;
import android.media.MediaScannerConnection.MediaScannerConnectionClient;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class SDCARD123Activity extends Activity implements MediaScannerConnectionClient{
public String[] allFiles;
private String SCAN_PATH ;
private static final String FILE_TYPE="image/*";
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/Photo/");
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()+"/Photo/"+allFiles[0];
System.out.println(" SCAN_PATH " +SCAN_PATH);
Log.d("SCAN PATH", "Scan Path " + SCAN_PATH);
Button scanBtn = (Button)findViewById(R.id.scanBtn);
scanBtn.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
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);
System.out.println("URI " + uri);
if (uri != null)
{
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(uri);
startActivity(intent);
}
} finally
{
conn.disconnect();
conn = null;
}
}
}
Related
This is my first time for asking question in stackoverflow and to make an android application using camera app.
I tried to use the source code in android development page, but it failed.
Thank you for reading my post.
package com.examplehoon.gnibnumb;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import java.io.File;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
static final int REQUEST_IMAGE_CAPTURE = 1;
String mCurrentPhotoPath;
static final int REQUEST_TAKE_PHOTO = 1;
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = "file:" + image.getAbsolutePath();
return image;
}
private void dispatchTakePictureIntent() {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File
}
// Continue only if the File was successfully created
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
Uri outputFileUri = Uri.fromFile(photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
}
public void startClicked(View view) throws IOException, InterruptedException{
for(int i = 0; i<10; i++){
thd.run();
thd.sleep(5000);
}
}
public class Top implements Runnable{
public void run() {
dispatchTakePictureIntent();
}
}
Top t = new Top();
Thread thd = new Thread(t);
}
On Android, I want to play TextToSpeech output through only one sound channel (think Shoulder Angel). To do this, I am currently using tts.synthesizeToFile(), and then playing back the dynamically-created file using the MediaPlayer. I use mediaPlayer.setVolume(0.0f, 1.0f) to play the audio through only one channel.
My working code is below.
My question is: is there a more direct way of playing TTS output through a single channel?
Using TextToSpeech to synthesize the file is time-consuming, and using MediaPlayer to play it back uses more resources than strictly necessary. I want this to be responsive and to work on low-end devices, so being kind to the CPU is important.
MainActivity.java
package com.example.pantts;
import android.app.Activity;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.speech.tts.TextToSpeech;
import android.os.Bundle;
import android.speech.tts.UtteranceProgressListener;
import android.util.Log;
import java.io.File;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.util.HashMap;
import java.util.Locale;
public class MainActivity extends Activity implements TextToSpeech.OnInitListener {
private TextToSpeech tts;
private String toSpeak = "Hello, right ear!";
private static final String FILE_ID = "file";
private HashMap<String, String> hashMap = new HashMap<String, String>();
private String filename;
private TextToSpeech tts;
private MediaPlayer mediaPlayer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
filename = getFilesDir() + "/" + "tts.wav";
Log.d("LOG", "file: " + filename);
// /data/data/com.example.pantts/files/tts.wav
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
tts = new TextToSpeech(this, this);
tts.setOnUtteranceProgressListener(mProgressListener);
}
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
tts.setLanguage(Locale.UK);
hashMap.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, FILE_ID);
// Using deprecated call for API 20 and earlier
tts.synthesizeToFile(toSpeak, hashMap, filename);
Log.d("LOG", "synthesizeToFile queued");
}
}
private UtteranceProgressListener mProgressListener =
new UtteranceProgressListener() {
#Override
public void onStart(String utteranceId) {
Log.d("LOG", "synthesizeToFile onStart " + utteranceId);
}
#Override
public void onError(String utteranceId) {
Log.d("LOG", "synthesizeToFile onError " + utteranceId);
}
#Override
public void onDone(String utteranceId) {
if (utteranceId.equals(FILE_ID)) { // Thanks to Hoan Nguyen for correcting this
Log.d("LOG", "synthesizeToFile onDone " + utteranceId);
try {
File ttsFile = new File(filename);
FileInputStream inputStream = new FileInputStream(ttsFile);
FileDescriptor fileDescriptor = inputStream.getFD();
mediaPlayer.reset();
mediaPlayer.setDataSource(fileDescriptor);
inputStream.close();
mediaPlayer.prepare();
mediaPlayer.setVolume(0.0f, 1.0f); // right channel only
mediaPlayer.start();
} catch (Exception e) {
e.printStackTrace();
}
}
}
};
}
There is nothing wrong with the synthesize, it is the comparison that is wrong. It should be
if (utteranceId.equals(FILE_ID))
Good day everyone. Please am trying to play videos from a youtube channel. Let me break it down
1:On the first activity you get a list of users in a listview
2:When you click on the user,it loads their videos in another listview.
Everything is working perfectly to this point,But i don't know how to play the video,when that particular video is clicked. Here is my code.
package com.talagbe.videofeeds;
import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListView;
import android.widget.Toast;
public class YoutubeVideos extends Activity {
ListView listv;
YoutubeAdapter yadapter;
ArrayList<Youtube> y_list;
String url;
String Channel;
Context context=null;
ProgressDialog mprogress;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.youtube);
y_list= new ArrayList<Youtube>();
listv = (ListView) findViewById(R.id.list2);
Intent intent = getIntent();
Bundle bundle = intent.getExtras();
Channel = bundle.getString("Channel");
init();
}
public void init(){
Log.d("Chan",Channel);
AsyncHttpClient LoadVideos = new AsyncHttpClient();
LoadVideos.get("https://gdata.youtube.com/feeds/api/users/"+ Channel +"/uploads?v=2&alt=jsonc", new AsyncHttpResponseHandler(){
public void onSuccess(String data){
try {
JSONObject videoObj = new JSONObject(data);
//JSONArray jsonArray = json.getJSONObject("data").getJSONArray("items");
JSONArray videosarray = videoObj.getJSONObject("data").getJSONArray("items");;
for(int i=0; i<videosarray.length();i++){
Youtube yvideos = new Youtube();
JSONObject video = videosarray.getJSONObject(i);
String videourl = video.getJSONObject("player").getString("mobile");
yvideos.setVideoTitle(video.getString("title"));
yvideos.setThumbs(video.getJSONObject("thumbnail").getString("sqDefault"));
//yvideos.setVideourl(videourl);
y_list.add(yvideos);
Log.d("Title",video.getString("title"));
Log.d("Video",videourl);
Log.d("Thumb",video.getJSONObject("thumbnail").getString("sqDefault"));
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
YoutubeAdapter Adapter = new YoutubeAdapter(getApplicationContext(),R.layout.videos,y_list);
listv.setAdapter(Adapter);
}
public void onStart(){
mprogress = ProgressDialog.show(YoutubeVideos.this, "Connecting...", "Retrieveing Videos");
}
public void onFinish(){
mprogress.dismiss();
}
public void onFailure(Throwable error, String content)
{
//Log.e("Error", content);
Toast.makeText(getBaseContext(), "Error Connecting to the internet", Toast.LENGTH_LONG).show();
}
});
}
}
You can make use of "YouTube Android Player API" provided by Google to play YouTube videos.
The YouTube Android Player API enables you to incorporate video
playback functionality into your Android applications. The API defines
methods for loading and playing YouTube videos (and playlists) and for
customizing and controlling the video playback experience.
Here's a sample app that utilizes YouTube Android Player API.
You can follow YouTube API
https://developers.google.com/youtube/android/player/reference/com/google/android/youtube/player/YouTubeIntents
or you can direct intent default YouTube player by calling :
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("vnd.youtube://" + id));
startActivity(intent);
The id is the identifier after the questionmark in the url. For example: youtube.com/watch?v=ID
Another way is:
Intent videoIntent = new Intent(Intent.ACTION_VIEW);
videoIntent.setData(url);
videoIntent.setClassName("com.google.anddroid.youtube", "com.google.android.youtube.WatchActivity");
startActivity(videoIntent);
I am downloading files from server using the DownloadManager class as mentioned here. The image downloaded can be accessed from the Downloads folder on android. When I click the downloaded image from the Downloads, the image is displayed. But if it try to downlaod an apk instead of an image, the downloaded apk cannot be installed from the Downloads folder, a problem parsing the package error appears. Why?
Here is what I am doing (the same as mentioned in the link above):
import android.app.Activity;
import android.app.DownloadManager;
import android.app.DownloadManager.Query;
import android.app.DownloadManager.Request;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
public class DownloadManagerActivity extends Activity {
private long enqueue;
private DownloadManager dm;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
/* long downloadId = intent.getLongExtra(
DownloadManager.EXTRA_DOWNLOAD_ID, 0);*/
Query query = new Query();
query.setFilterById(enqueue);
Cursor c = dm.query(query);
if (c.moveToFirst()) {
int columnIndex = c
.getColumnIndex(DownloadManager.COLUMN_STATUS);
if (DownloadManager.STATUS_SUCCESSFUL == c
.getInt(columnIndex)) {
/* ImageView view = (ImageView) findViewById(R.id.imageView1);
String uriString = c
.getString(c
.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
view.setImageURI(Uri.parse(uriString));*/
}
}
}
}
};
registerReceiver(receiver, new IntentFilter(
DownloadManager.ACTION_DOWNLOAD_COMPLETE));
}
public void onClick(View view) {
dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
Request request = new Request(
Uri.parse("http://xxx.xxx.x.xxx/MyApp.apk"));
enqueue = dm.enqueue(request);
}
public void showDownload(View view) {
Intent i = new Intent();
i.setAction(DownloadManager.ACTION_VIEW_DOWNLOADS);
startActivity(i);
}
}
How can I download files using Android downloader? (The downloader that WebBrowser is using that too).
I tried something like this :
Intent i = new Intent(Intent.ACTION_VIEW , Uri.parse("MyUrl"));
startActivity(i);
Any better way?
Edit
I am using Android 2.2
Here you go.
import android.app.Activity;
import android.app.DownloadManager;
import android.app.DownloadManager.Query;
import android.app.DownloadManager.Request;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
public class DownloadManagerActivity extends Activity {
private long enqueue;
private DownloadManager dm;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
long downloadId = intent.getLongExtra(
DownloadManager.EXTRA_DOWNLOAD_ID, 0);
Query query = new Query();
query.setFilterById(enqueue);
Cursor c = dm.query(query);
if (c.moveToFirst()) {
int columnIndex = c
.getColumnIndex(DownloadManager.COLUMN_STATUS);
if (DownloadManager.STATUS_SUCCESSFUL == c
.getInt(columnIndex)) {
ImageView view = (ImageView) findViewById(R.id.imageView1);
String uriString = c
.getString(c
.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
view.setImageURI(Uri.parse(uriString));
}
}
}
}
};
registerReceiver(receiver, new IntentFilter(
DownloadManager.ACTION_DOWNLOAD_COMPLETE));
}
public void onClick(View view) {
dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
Request request = new Request(
Uri.parse("url for file to download"));
enqueue = dm.enqueue(request);
}
public void showDownload(View view) {
Intent i = new Intent();
i.setAction(DownloadManager.ACTION_VIEW_DOWNLOADS);
startActivity(i);
}
}
Don't forget to add android.permission.internet in manifest.
If you want to download it onto the user's SD card from an URL, you can just open it in the phone's default internet browser.
String url = "https://appharbor.com/assets/images/stackoverflow-logo.png";
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
(Code from this question)
The android browser will then start and the file (in this case an image) will be downloaded.
You need to use HttpUrlConnection to do this on Android 2.2 and below. There is a very detailed tutorial on the internet that shows you how to do this (with a progress dialog box too).
Remember you must use an AsyncTask or a Thread to ensure that you do not block the UI thread during the actual download!
Yes, you cant perform network operation in the main thread. You can look up to this repository to download file.