I have 231 sound files ( duration ~ 0.2 Sec each) of size 5.7 MB total to load into my android project. I am trying load them when the application starts using for loop like
for (int i = 0; i < 231; i++){
...
loadSoundAsset(i); //method to load the sound files
i++;
...
}
Yet the above method is taking too long to load the sound files. What should be done to load effectively many asset files into android project?
I create sample code for you. How to get faster? (I test it for assets files about 180 sounds files.)
MainActivity
public class MainActivity extends Activity implements TaskListener {
MultiLoader loader = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TextView view = new TextView(this);
view.setText("Loader");
setContentView(view);
}
#Override
public void onAttachedToWindow() {
super.onAttachedToWindow();
loader = new MultiLoader(this, this);
loader.load("sound");
}
#Override
public void onTaskEnd() {
Vector<byte[]> soundDatas = loader.getData();
Log.e("MainActivity", "TaskEnd");
}
#Override
protected void onDestroy() {
loader.clear();
super.onDestroy();
}
}
MultiLoader
package com.fastload;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Vector;
import java.util.regex.Pattern;
import android.content.Context;
import android.util.Log;
public class MultiLoader {
private int threadCount = 0;
private String[] mFiles;
private Vector<byte[]> fileContents = new Vector<byte[]>();
private Thread[] mQueue = null;
private Context mContext;
private TaskListener listener;
public MultiLoader(Context mContext, TaskListener listener) {
super();
this.mContext = mContext;
this.listener = listener;
}
public Vector<byte[]> getData(){
return fileContents;
}
public void reQueue(int index){
boolean status = true;
mQueue[index] = null;
for(Thread item : mQueue){
status &= (item == null);
}
if(status){
listener.onTaskEnd();
}
}
public void load(final String path){
initialize(path);
if(mFiles == null || (mFiles != null && mFiles.length < 1))
return;
mQueue = new Thread[threadCount];
for(int i = 0; i < threadCount; ++i){
int len = mFiles.length;
int piece = len / threadCount;
final int startIndex = i * piece;
final int endIndex = (i == threadCount - 1) ? len - startIndex - 1 : startIndex + piece;
MyTask task = new MyTask("MyTask##"+i, i, new EndListener(){
#Override
public void onEnd(int index, String name) {
Log.e("ThreadEND", "name = "+name);
reQueue(index);
}
}) {
#Override
public void execute() {
for(int index = startIndex; index < endIndex; ++index){
File file = new File(mFiles[index]);
InputStream is = null;
ByteArrayOutputStream os = null;
byte[] data = null;
try {
is = mContext.getAssets().open(path + File.separator + file.getName());
os = new ByteArrayOutputStream();
int count = 0;
byte[] buffer = new byte[1024];
while((count = is.read(buffer)) > 0){
os.write(buffer, 0, count);
}
os.flush();
data = os.toByteArray();
debug(getName(), index, path + File.separator + file.getName());
} catch (Exception e) {
e.printStackTrace();
} finally{
if(is != null){
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(os != null){
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
if(data != null){
add(data);
}
}
}
};
mQueue[i] = task;
task.start();
}
}
private void debug(String who, int index, String name){
Log.e("MULTI LOADER DEBUG", "who = "+who+" , name = "+name+", index = "+index);
}
private void initialize(String path){
threadCount = getNumCores() * 2;
try {
mFiles = mContext.getAssets().list(path);
} catch (IOException e) {
e.printStackTrace();
}
}
private void add(byte[] data){
synchronized (fileContents) {
fileContents.add(data);
}
}
private void remove(byte[] data){
synchronized (fileContents) {
fileContents.remove(data);
}
}
public void clear(){
synchronized (fileContents) {
fileContents.clear();
}
}
private int getNumCores() {
class CpuFilter implements FileFilter {
#Override
public boolean accept(File pathname) {
if(Pattern.matches("cpu[0-9]+", pathname.getName())) {
return true;
}
return false;
}
}
try {
File dir = new File("/sys/devices/system/cpu/");
File[] files = dir.listFiles(new CpuFilter());
return files.length;
} catch(Exception e) {
return 1;
}
}
private abstract class MyTask extends Thread{
private EndListener listener;
private int index;
private MyTask() { }
public MyTask(String threadName, int index, EndListener listener) {
super(threadName);
this.index = index;
this.listener = listener;
}
public abstract void execute();
#Override
public void run() {
execute();
end();
}
public void end(){
listener.onEnd(index, getName());
}
public int getIndex(){
return index;
}
}
public interface TaskListener{
public void onTaskEnd();
}
public interface EndListener{
public void onEnd(int index, String name);
}
}
Related
I am facing issue in highlighting the text as the google reads it. Every device is having its own speed of reading the text due to which highlighting text along with sound cause problem and seems inconsistent in some devices.
I have tried Progressive Textview class to highlight the sentence as google start it reading. In this class, I need to define run task value in floats so as to start the highlighting speed. Bellow is the custom class code:
public class ProgressTextView extends AppCompatTextView {
private SpannableTask spannableTask;
private ProgressListener progressListener;
private boolean changeColor = false;
public ProgressTextView(Context context) {
super(context);
init(null);
}
public ProgressTextView(Context context, #Nullable AttributeSet attrs) {
super(context, attrs);
init(getContext().obtainStyledAttributes(attrs, R.styleable.ProgressTextView));
}
public ProgressTextView(Context context, #Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(getContext().obtainStyledAttributes(attrs, R.styleable.ProgressTextView, defStyleAttr, 0));
}
private void init(#Nullable TypedArray typedArray) {
this.spannableTask = new SpannableTask(this, getText().toString());
this.spannableTask.setDefaultTextColor(this.getTextColors().getDefaultColor());
int textColor = typedArray.getColor(R.styleable.ProgressTextView_highlightTextColor, 0);
if (textColor != 0) {
this.spannableTask.setHighlightTextColor(textColor);
}
}
public void addProgressListener(ProgressListener progressListener) {
this.progressListener = progressListener;
}
public SpannableTask getSpannableTask() {
return this.spannableTask;
}
public SpannableTask getSpannableTask(String text) {
this.spannableTask = new SpannableTask(this, text);
this.spannableTask.setHighlightTextColor(getResources().getColor(R.color.yellow));
this.spannableTask.setHighlightBackgroundTextColor(getResources().getColor(R.color.black));
this.spannableTask.setDefaultTextColor(getResources().getColor(R.color.text_color));
return this.spannableTask;
}
public class SpannableTask implements Runnable {
private Handler handler = new Handler();
private SpannableString spannableString;
private String text;
private ProgressTextView spannableTextView;
private int second;
private int defaultTextColor = R.color.text_color;
private int highlightTextColor = Color.YELLOW;
private int backgroundTextColor = Color.BLACK;
public SpannableTask(ProgressTextView spannableTextView, String text) {
this.text = text;
this.spannableString = new SpannableString(text);
this.spannableTextView = spannableTextView;
initTextView(defaultTextColor,backgroundTextColor, text.length());
}
public void runTask(float second) {
this.second = ((int) (second * 1000) / text.length());
new Thread(this).run();
}
public void runTask(int second) {
this.second = second / text.length();
new Thread(this).run();
}
#Override
public void run() {
for (int i = 0; i <= text.length(); i++) {
final int value = i;
handler.postDelayed(new Runnable() {
#Override
public void run() {
changeColor = true;
initTextView(highlightTextColor,backgroundTextColor, value);
if (value == text.length() && progressListener != null) {
cancel();
progressListener.complete();
}
}
}, second * i);
}
}
private void initTextView(int color,int backgroundcolor, int length) {
if(!changeColor){
this.spannableString.setSpan(new BackgroundColorSpan(Color.WHITE), 0, length, 0);
this.spannableString.setSpan( new ForegroundColorSpan(getResources().getColor(R.color.text_color)), 0,length, 0);
SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder();
spannableStringBuilder.append(spannableString);
this.spannableTextView.setText(spannableString);
}else{
this.spannableString.setSpan(new BackgroundColorSpan(color), 0, length, 0);
this.spannableString.setSpan( new ForegroundColorSpan(backgroundcolor), 0,length, 0);
SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder();
spannableStringBuilder.append(spannableString);
this.spannableTextView.setText(spannableString);
}
}
public void cancel() {
changeColor =false;
initTextView(defaultTextColor,backgroundTextColor, text.length());
handler.removeCallbacksAndMessages(null);
}
public void setDefaultTextColor(int defaultTextColor) {
this.defaultTextColor = defaultTextColor;
initTextView(defaultTextColor,backgroundTextColor, text.length());
}
public void setHighlightTextColor(int highlightTextColor) {
this.highlightTextColor = highlightTextColor;
}
public void setHighlightBackgroundTextColor(int backgroundTextColor) {
this.backgroundTextColor = backgroundTextColor;
}
}
}
And in my main voice Activity, I am using GTS to read the dynamic text
private ProgressTextView.SpannableTask target = null;
private boolean isSpeech=false;
TextToSpeech textToSpeech;
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_voice);
new RetrieveFeedTask().execute("");
}
public static class RetrieveFeedTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
try {
String apiUrl= "https://maps.googleapis.com/maps/api/geocode/json?latlng="+mCurrentLocation.getLatitude()+","+mCurrentLocation.getLongitude()+"&key=YOUR KEY";
URL url = new URL(apiUrl);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
StringBuilder stringBuilder = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line).append("\n");
}
bufferedReader.close();
return stringBuilder.toString();
}
finally{
urlConnection.disconnect();
}
}
catch(Exception e) {
return null;
}
}
protected void onPreExecute() {
}
protected void onPostExecute(String response) {
if(response != null) {
try {
AddressList addressList=new Gson().fromJson(response,AddressList.class);
List<Results> mList= addressList.getResults();
List<AddressComponent> mAddressList= mList.get(0).getAddressComponents();
StringBuilder sb = new StringBuilder();
for (AddressComponent addressComponent:mAddressList) {
if(addressComponent.getTypes().contains("street_number")){
sb.append(addressComponent.getShortName()).append(" ");
}
else if(addressComponent.getTypes().contains("route")){
sb.append(addressComponent.getShortName()).append(", ");
}
else if(addressComponent.getTypes().contains("locality")){
sb.append(addressComponent.getShortName()).append(", ");
}
else if(addressComponent.getTypes().contains("administrative_area_level_1")){
sb.append(addressComponent.getLongName());
}
}
mTxtAddress.setText(sb.toString());
textSpeech();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
private void textSpeech(){
textToSpeech = new TextToSpeech(this, new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
int result = textToSpeech.setLanguage(Locale.ENGLISH);
if (result == TextToSpeech.LANG_MISSING_DATA ||
result == TextToSpeech.LANG_NOT_SUPPORTED) {
Toast.makeText(getApplicationContext(), "This language is not supported!",
Toast.LENGTH_SHORT);
} else {
textToSpeech.setOnUtteranceCompletedListener(VoiceActivity.this);
textToSpeech.setOnUtteranceProgressListener(new UtteranceProgressListener() {
#Override
public void onStart(String s) {
final String keyword = s;
runOnUiThread(new Runnable() {
#Override
public void run() {
if(mTxtAddress.getText().toString().equalsIgnoreCase(keyword)){
target = mTxtAddress.getSpannableTask(mTxtAddress.getText().toString());
target.runTask(3.5f);
}
}
});
}
#Override
public void onDone(final String keyword) {
runOnUiThread(new Runnable() {
#Override
public void run() {
if(mTxtAddress.getText().toString().equalsIgnoreCase(keyword)){
target.cancel();
}
}
});
}
#Override
public void onError(String s) {
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "Error ", Toast.LENGTH_SHORT).show();
}
});
}
});
speak();
}
}
}
});
}
private void speak() {
mPlayer.stop();
isSpeech=true;
String text = mTxtEmer.getText().toString();
HashMap<String, String> params = new HashMap<String, String>();
params.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID,text);
textToSpeech.speak(text, TextToSpeech.QUEUE_ADD, params);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
params.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, mTxtAddress.getText().toString());
textToSpeech.speak(mTxtAddress.getText().toString(), TextToSpeech.QUEUE_ADD, params);
} else {
params.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, mTxtAddress.getText().toString());
textToSpeech.speak(mTxtAddress.getText().toString(), TextToSpeech.QUEUE_ADD, params);
}
}
I am working on a media player app. I'm using ExoPlayer library. I have a playlist of videos, and I want to download videos simultaneously. I done it by using available demo app of exoplayer library on GitHub. I want to show progress of each downloading in the UI. For this job I get help from DownloadNotificationUtil.buildProgressNotification method.
#Override
protected Notification getForegroundNotification(TaskState[] taskStates) {
float totalPercentage = 0;
int downloadTaskCount = 0;
boolean allDownloadPercentagesUnknown = true;
boolean haveDownloadedBytes = false;
boolean haveDownloadTasks = false;
boolean haveRemoveTasks = false;
Log.e(TAG,"size task state: "+taskStates.length);
for (TaskState taskState : taskStates) {
Log.e(TAG,"taskId= "+taskState.taskId);
if (taskState.state != TaskState.STATE_STARTED
&& taskState.state != TaskState.STATE_COMPLETED) {
continue;
}
if (taskState.action.isRemoveAction) {
haveRemoveTasks = true;
continue;
}
haveDownloadTasks = true;
if (taskState.downloadPercentage != C.PERCENTAGE_UNSET) {
allDownloadPercentagesUnknown = false;
totalPercentage += taskState.downloadPercentage;
}
haveDownloadedBytes |= taskState.downloadedBytes > 0;
downloadTaskCount++;
}
int progress = 0;
boolean indeterminate = true;
if (haveDownloadTasks) {
progress = (int) (totalPercentage / downloadTaskCount);
indeterminate = allDownloadPercentagesUnknown && haveDownloadedBytes;
Log.e(TAG,"notifi "+progress);
}
return DownloadNotificationUtil.buildProgressNotification(
this,
R.drawable.exo_icon_play,
DOWNLOAD_CHANNEL_ID,
null,
null,
taskStates);
}
Now,I can track the progress downloading. But I still have a problem. I can't understand which item is downloading to update it's progress bar in the UI. Is there a Identical id of each download to recognize it? For example Android Download Manager has a download ID for each downloading file. But I don't know , how to handle this problem.
This is MediaDownloadService:
public class MediaDownloadService extends DownloadService {
public static String TAG="MediaDownloadService";
private static final int FOREGROUND_NOTIFICATION_ID = 1;
public MediaDownloadService() {
super(
DOWNLOAD_NOTIFICATION_ID,
DEFAULT_FOREGROUND_NOTIFICATION_UPDATE_INTERVAL,
DOWNLOAD_CHANNEL_ID,
R.string.download_channel_name);
}
#Override
protected DownloadManager getDownloadManager() {
return ((MyApplication) getApplication()).getDownloadManager();
}
#Nullable
#Override
protected Scheduler getScheduler() {
return null;
}
#Override
protected Notification getForegroundNotification(TaskState[] taskStates) {
float totalPercentage = 0;
int downloadTaskCount = 0;
boolean allDownloadPercentagesUnknown = true;
boolean haveDownloadedBytes = false;
boolean haveDownloadTasks = false;
boolean haveRemoveTasks = false;
for (TaskState taskState : taskStates) {
if (taskState.state != TaskState.STATE_STARTED
&& taskState.state != TaskState.STATE_COMPLETED) {
continue;
}
if (taskState.action.isRemoveAction) {
haveRemoveTasks = true;
continue;
}
haveDownloadTasks = true;
if (taskState.downloadPercentage != C.PERCENTAGE_UNSET) {
allDownloadPercentagesUnknown = false;
totalPercentage += taskState.downloadPercentage;
}
haveDownloadedBytes |= taskState.downloadedBytes > 0;
downloadTaskCount++;
}
int progress = 0;
boolean indeterminate = true;
if (haveDownloadTasks) {
progress = (int) (totalPercentage / downloadTaskCount);
indeterminate = allDownloadPercentagesUnknown && haveDownloadedBytes;
Log.e(TAG,"notifi "+progress);
sendIntent(progress);
}
return DownloadNotificationUtil.buildProgressNotification(
this,
R.drawable.exo_icon_play,
DOWNLOAD_CHANNEL_ID,
null,
null,
taskStates);
}
private void sendIntent(int progress){
Intent intent = new Intent(ConstantUtil.MESSAGE_PROGRESS);
intent.putExtra("progress",progress);
LocalBroadcastManager.getInstance(MediaDownloadService.this).sendBroadcast(intent);
}
#Override
protected void onTaskStateChanged(TaskState taskState) {
if (taskState.action.isRemoveAction) {
return;
}
Notification notification = null;
if (taskState.state == TaskState.STATE_COMPLETED) {
Log.e(TAG,"STATE_COMPLETED");
notification =
DownloadNotificationUtil.buildDownloadCompletedNotification(
/* context= */ this,
R.drawable.exo_controls_play,
DOWNLOAD_CHANNEL_ID,
/* contentIntent= */ null,
Util.fromUtf8Bytes(taskState.action.data));
} else if (taskState.state == TaskState.STATE_FAILED) {
Log.e(TAG,"STATE_FAILED");
notification =
DownloadNotificationUtil.buildDownloadFailedNotification(
/* context= */ this,
R.drawable.exo_controls_play,
DOWNLOAD_CHANNEL_ID,
/* contentIntent= */ null,
Util.fromUtf8Bytes(taskState.action.data));
}
int notificationId = FOREGROUND_NOTIFICATION_ID + 1 + taskState.taskId;
NotificationUtil.setNotification(this, notificationId, notification);
}
}
This is DownloadTracker class:
public class DownloadTracker implements DownloadManager.Listener {
/** Listens for changes in the tracked downloads. */
public interface Listener {
/** Called when the tracked downloads changed. */
void onDownloadsChanged();
}
private static final String TAG = "DownloadTracker";
private final Context context;
private final DataSource.Factory dataSourceFactory;
private final TrackNameProvider trackNameProvider;
private final CopyOnWriteArraySet<Listener> listeners;
private Listener onDownloadsChanged;
private final HashMap<Uri, DownloadAction> trackedDownloadStates;
private final ActionFile actionFile;
private final Handler actionFileWriteHandler;
public DownloadTracker(
Context context,
DataSource.Factory dataSourceFactory,
File actionFile,
DownloadAction.Deserializer... deserializers) {
this.context = context.getApplicationContext();
this.dataSourceFactory = dataSourceFactory;
this.actionFile = new ActionFile(actionFile);
trackNameProvider = new DefaultTrackNameProvider(context.getResources());
listeners = new CopyOnWriteArraySet<>();
trackedDownloadStates = new HashMap<>();
HandlerThread actionFileWriteThread = new HandlerThread("DownloadTracker");
actionFileWriteThread.start();
actionFileWriteHandler = new Handler(actionFileWriteThread.getLooper());
loadTrackedActions(
deserializers.length > 0 ? deserializers : DownloadAction.getDefaultDeserializers());
}
public void addListener(Listener listener) {
listeners.add(listener);
}
public void removeListener(Listener listener) {
listeners.remove(listener);
}
public boolean isDownloaded(Uri uri) {
return trackedDownloadStates.containsKey(uri);
}
#SuppressWarnings("unchecked")
public List<StreamKey> getOfflineStreamKeys(Uri uri) {
if (!trackedDownloadStates.containsKey(uri)) {
return Collections.emptyList();
}
return trackedDownloadStates.get(uri).getKeys();
}
public int toggleDownload(Activity activity, String name, Uri uri, String extension) {
if (isDownloaded(uri)) {
Log.e(TAG,"isDownloaded");
DownloadAction removeAction =
getDownloadHelper(uri, extension).getRemoveAction(Util.getUtf8Bytes(name));
startServiceWithAction(removeAction);
return -1;
} else {
StartDownloadDialogHelper helper =
new StartDownloadDialogHelper(activity, getDownloadHelper(uri, extension), name);
helper.prepare();
return helper.getTaskId();
}
}
#Override
public void onInitialized(DownloadManager downloadManager) {
// Do nothing.
}
#Override
public void onTaskStateChanged(DownloadManager downloadManager, TaskState taskState) {
DownloadAction action = taskState.action;
Uri uri = action.uri;
if ((action.isRemoveAction && taskState.state == TaskState.STATE_COMPLETED)
|| (!action.isRemoveAction && taskState.state == TaskState.STATE_FAILED)) {
// A download has been removed, or has failed. Stop tracking it.
if (trackedDownloadStates.remove(uri) != null) {
handleTrackedDownloadStatesChanged();
}
}
}
#Override
public void onIdle(DownloadManager downloadManager) {
// Do nothing.
}
// Internal methods
private void loadTrackedActions(DownloadAction.Deserializer[] deserializers) {
try {
DownloadAction[] allActions = actionFile.load(deserializers);
for (DownloadAction action : allActions) {
trackedDownloadStates.put(action.uri, action);
}
} catch (IOException e) {
Log.e(TAG, "Failed to load tracked actions", e);
}
}
private void handleTrackedDownloadStatesChanged() {
for (Listener listener : listeners) {
listener.onDownloadsChanged();
}
final DownloadAction[] actions = trackedDownloadStates.values().toArray(new DownloadAction[0]);
Log.e(TAG,"actions: "+actions.toString());
actionFileWriteHandler.post(
() -> {
try {
actionFile.store(actions);
} catch (IOException e) {
Log.e(TAG, "Failed to store tracked actions", e);
}
});
}
private void startDownload(DownloadAction action) {
if (trackedDownloadStates.containsKey(action.uri)) {
// This content is already being downloaded. Do nothing.
Log.e(TAG,"download already exsit");
return;
}
trackedDownloadStates.put(action.uri, action);
handleTrackedDownloadStatesChanged();
startServiceWithAction(action);
}
private void startServiceWithAction(DownloadAction action) {
DownloadService.startWithAction(context, MediaDownloadService.class, action, false);
}
private DownloadHelper getDownloadHelper(Uri uri, String extension) {
int type = Util.inferContentType(uri, extension);
switch (type) {
case C.TYPE_DASH:
return new DashDownloadHelper(uri, dataSourceFactory);
case C.TYPE_SS:
return new SsDownloadHelper(uri, dataSourceFactory);
case C.TYPE_HLS:
return new HlsDownloadHelper(uri, dataSourceFactory);
case C.TYPE_OTHER:
return new ProgressiveDownloadHelper(uri);
default:
throw new IllegalStateException("Unsupported type: " + type);
}
}
private final class StartDownloadDialogHelper
implements DownloadHelper.Callback, DialogInterface.OnClickListener {
private final DownloadHelper downloadHelper;
private final String name;
private final AlertDialog.Builder builder;
private final View dialogView;
private final List<TrackKey> trackKeys;
private final ArrayAdapter<String> trackTitles;
private final ListView representationList;
private int taskId;
public StartDownloadDialogHelper(
Activity activity, DownloadHelper downloadHelper, String name) {
this.downloadHelper = downloadHelper;
this.name = name;
builder =
new AlertDialog.Builder(activity)
.setTitle(R.string.exo_download_description)
.setPositiveButton(android.R.string.ok, this)
.setNegativeButton(android.R.string.cancel, null);
// Inflate with the builder's context to ensure the correct style is used.
LayoutInflater dialogInflater = LayoutInflater.from(builder.getContext());
dialogView = dialogInflater.inflate(R.layout.start_download_dialog, null);
trackKeys = new ArrayList<>();
trackTitles =
new ArrayAdapter<>(
builder.getContext(), android.R.layout.simple_list_item_multiple_choice);
representationList = dialogView.findViewById(R.id.representation_list);
representationList.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
representationList.setAdapter(trackTitles);
}
public void prepare() {
downloadHelper.prepare(this);
}
#Override
public void onPrepared(DownloadHelper helper) {
for (int i = 0; i < downloadHelper.getPeriodCount(); i++) {
TrackGroupArray trackGroups = downloadHelper.getTrackGroups(i);
for (int j = 0; j < trackGroups.length; j++) {
TrackGroup trackGroup = trackGroups.get(j);
for (int k = 0; k < trackGroup.length; k++) {
trackKeys.add(new TrackKey(i, j, k));
trackTitles.add(trackNameProvider.getTrackName(trackGroup.getFormat(k)));
}
}
}
if (!trackKeys.isEmpty()) {
builder.setView(dialogView);
}
builder.create().show();
}
#Override
public void onPrepareError(DownloadHelper helper, IOException e) {
Toast.makeText(
context.getApplicationContext(), R.string.download_start_error, Toast.LENGTH_LONG)
.show();
Log.e(TAG, "Failed to start download", e);
}
#Override
public void onClick(DialogInterface dialog, int which) {
ArrayList<TrackKey> selectedTrackKeys = new ArrayList<>();
for (int i = 0; i < representationList.getChildCount(); i++) {
if (representationList.isItemChecked(i)) {
selectedTrackKeys.add(trackKeys.get(i));
}
}
if (!selectedTrackKeys.isEmpty() || trackKeys.isEmpty()) {
// We have selected keys, or we're dealing with single stream content.
DownloadAction downloadAction =
downloadHelper.getDownloadAction(Util.getUtf8Bytes(name), selectedTrackKeys);
taskId=MyApplication.getInstance().getDownloadManager().handleAction(downloadAction);
startDownload(downloadAction);
}
}
}
}
In my Fragment/Activity:
/* this method will be called when user click on download button of each item */
#Override
public void onDownloadClick(LectureList lecture) {
Log.e(TAG,"onClickDownload");
downloadTracker.toggleDownload(this,lecture.getTitle_lecture(),
Uri.parse(lecture.getUrlPath()),lecture.getExtension());
}
And here is my broadcast receiver:
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Log.e(TAG,"onRecive download");
if(intent.getAction().equals(MESSAGE_PROGRESS)){
int progress=intent.getLongExtra("progress",0);
}
}
};
In the getForegroundNotification() method, you will get list of TaskState objects, which has a members downloadPercentage and your download Uri taskState.action.uri which is unique for each download task. Store these variables into a map and broadcast the map.
override fun getForegroundNotification(taskStates: Array<TaskState>): Notification {
var totalPercentage = 0f
var downloadTaskCount = 0
var progressMap : HashMap<Uri, Int> = HashMap()
for (taskState in taskStates) {
if (taskState.state != TaskState.STATE_STARTED && taskState.state != TaskState.STATE_COMPLETED) {
continue
}
if (taskState.action.isRemoveAction) {
continue
}
if (taskState.downloadPercentage != C.PERCENTAGE_UNSET.toFloat()) {
totalPercentage += taskState.downloadPercentage
progressMap.put(taskState.action.uri, taskState.downloadPercentage.toInt())
}
downloadTaskCount++
}
var progress = 0
progress = (totalPercentage / downloadTaskCount).toInt()
broadcastIndividualProgress(progressMap)
return buildProgressNotification(progress)
}
I am trying to send messages through the UDP communication of an android phone a UDP host, according to the buttons on the screen send a specific message, I have a UDP_Service class where I instantiate the datagramsocket and do the corresponding sending:
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
public class UDP_Service {
private int server_port;
DatagramSocket skt;
private InetAddress local;
private String msge;
private String st;
private int msge_lenght;
private byte[] byteMsge;
private byte[] resp;
private int j;
public UDP_Service(){
try {
skt = new DatagramSocket();
} catch (SocketException e) {
e.printStackTrace();
// st = null;
}
}
public void setIP(String ip){
try {
local = InetAddress.getByName(ip);
} catch (UnknownHostException e) {
// st = null;
}
}
public void setPort(int np){
server_port = np;
}
public void setMsge(String msj){
msge = msj;
msge_lenght = msge.length();
byteMsge = msge.getBytes();
resp = new byte[1024];
}
public void Enviar(){
try {
skt = new DatagramSocket();
DatagramPacket pqtEnvio = new DatagramPacket(byteMsge, msge_lenght,
local, server_port);
skt.send(pqtEnvio);
DatagramPacket pqtResp = new DatagramPacket(resp, resp.length);
skt.receive(pqtResp);
st = new String(pqtResp.getData(),0,pqtResp.getLength());
//skt.close();
} catch (Exception e) {
// st = null;
}
}
public void close() {
skt.close();
}
public String getRespuesta(){
return st;
}
public int getCont() {
return j;
}
public void setCont(int x) {
j = x;
}
}
The method "Enviar()" I invoke it from an AsyncTask, however it only works once, I open the application from the phone and press any button and effectively the corresponding message is sent, but when I press another button no longer nothing happens. The onPostExecute () method of the AsyncTask is not running,I can not see the corresponding toast.
Here the AsyncTask
public class MainActivity extends AppCompatActivity {
String msje[];
String resp[];
int port;
UDP_Service UDP_Serv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
UDP_Serv = new UDP_Service();
//UDP_A = new UDP_Async();
msje = new String[9];
resp = new String[8];
}
public void UDP_Client(String mje, int pt, String ip, int c)
{
//UDP_A = new UDP_Async();
UDP_Serv.setMsge(mje);
UDP_Serv.setPort(pt);
UDP_Serv.setIP(ip);
UDP_Serv.setCont(c);
new UDP_Async().execute();
Toast.makeText(MainActivity.this, mje, Toast.LENGTH_SHORT).show();
}
public class UDP_Async extends AsyncTask < Void, Void, Boolean > {
private String st;
private int j;
#Override
protected Boolean doInBackground(Void...params) {
UDP_Serv.Enviar();
st = UDP_Serv.getRespuesta();
j = UDP_Serv.getCont();
//return st;
return true;
}
#Override
protected void onPostExecute(Boolean result) {
//super.onPostExecute(result);
if (result) {
if (!st.equals(null)) {
resp[j] = st;
actualizarUI(j);
}
Toast.makeText(MainActivity.this, "TAREA FINALIZADA!", Toast.LENGTH_SHORT).show();
}
}
}
}
I writed a robotium test that runs a test on a apk file. The test runs on a apk file in a debug mode. the test clicks and inserts data in the app.
The problem is, that sometimes a user hit on a link in a app, and opend a new app/website on the device, and now the root app is not visible.
there is a way to make it visible through the adb?
this is the main class of the test:
package genericTest.test;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Map;
import java.util.Random;
import android.annotation.SuppressLint;
import android.app.KeyguardManager;
import android.content.Context;
import android.os.SystemClock;
import android.test.ActivityInstrumentationTestCase2;
import android.view.View;
import com.robotium.solo.Solo;
#SuppressWarnings("rawtypes")
public class Main extends ActivityInstrumentationTestCase2 {
private FunctonsForViews mFunctonsForViews;
private Random mRand;
private Solo mSolo;
private static final String LAUNCHER_ACTIVITY_FULL_CLASSNAME = "com.hobbyistsoftware.android.vlcremote_us.main";
private final int DELAY = 50;
private final int SCREEN_SIZE = 1280;
private final int ERROR_COUNT_LIMIT = 10;
private final int CLICK_ON_LOOP_LIMIT = 8;
private final int WHAITING_FOR_VIEWS_LIMIT = 10;
private final int LOOP_LIMIT = 10000;
private static Class launcherActivityClass;
private static int error_count = 0;
static {
try {
launcherActivityClass = Class
.forName(LAUNCHER_ACTIVITY_FULL_CLASSNAME);
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}
}
#SuppressLint("NewApi")
#SuppressWarnings("unchecked")
public Main() throws ClassNotFoundException {
super(null, launcherActivityClass);
}
protected void setUp() throws Exception {
setActivityInitialTouchMode(true);
mSolo = new Solo(getInstrumentation(), getActivity());
Context context = getActivity();
KeyguardManager km =
(KeyguardManager) context.getSystemService(Context.KEYGUARD_SERVICE);
if (km.inKeyguardRestrictedInputMode())
{
KeyguardManager.KeyguardLock lock = km.newKeyguardLock("some_tag");
lock.disableKeyguard();
SystemClock.sleep(2000);
}
setActivityInitialTouchMode(true);
}
/*
* runs the test for the app.
*/
public void testMethod()
{
mFunctonsForViews = new FunctonsForViews(mSolo);
mSolo.sleep(DELAY * DELAY);
mRand = new Random();
/*
* the test will take place in the loop, and will be limit in time.
* in every iteration it will get the vies in activity's, and run a test on a random view.
*/
//for(int i=0 ; i<LOOP_LIMIT ; i++)
while(true)
{
mSolo.unlockScreen();
ArrayList Views = mSolo.getViews();
int arraySize = Views.size();
if (arraySize == 0)// now View in activity.
{
whenNoViewsInScreen(Views, arraySize);
}
if (arraySize != 0)
{
int ViewIndexInArray = mRand.nextInt(arraySize + 2);
if (ViewIndexInArray == arraySize)
{
mSolo.scrollDown();
}
else if (ViewIndexInArray == arraySize + 1)
{
if (!mSolo.getCurrentActivity().getClass().toString().split(" ")[1].equals
(LAUNCHER_ACTIVITY_FULL_CLASSNAME))
{
goingBack();
}
}
else
{
View randomView = (View)(Views.get(ViewIndexInArray));
runTestOnOneView(randomView);
}
}
}
}
/*
* performing clicks onScreen()
*/
public void myClickOnScreen()
{
try {
mSolo.unlockScreen();
mSolo.clickOnScreen(mRand.nextInt(SCREEN_SIZE), mRand.nextInt(SCREEN_SIZE));
} catch (Exception e) {
e.printStackTrace();
error_count++;
} catch (Error e2) {
error_count++;
e2.printStackTrace();
}
}
/*
* there is no Views available.
* we will try pressing on screen or the goBack function.
*/
public void whenNoViewsInScreen(ArrayList Views, int arraySize)
{
for (int j = 0; j < WHAITING_FOR_VIEWS_LIMIT; j++)
{
for (int k= 0; k < CLICK_ON_LOOP_LIMIT; k++)
{
myClickOnScreen();
}
Views = mSolo.getViews();
arraySize = Views.size();
if (arraySize != 0)
{
return;
}
mSolo.sleep(DELAY);
Views = mSolo.getViews();
arraySize = Views.size();
if (arraySize != 0)
{
return;
}
}
if (!mSolo.getCurrentActivity().getClass().toString().split(" ")[1].equals
(LAUNCHER_ACTIVITY_FULL_CLASSNAME))
{
goingBack();
}
mSolo.sleep(DELAY);
return;
}
public void runTestOnOneView(View randomView)
{
String rawViewName = randomView.getClass().getName();
String viewName = parseRawViewName(rawViewName);
if (viewName.contains("ActionBarContainer"))
{
return;
}
MyRunnable myRunnable = mFunctonsForViews.getMethodMap().get(viewName);
try{
if (myRunnable != null)
{
myRunnable.run((View)randomView);
}
else // view not in map.
{
boolean inMap = false;
Iterator it = mFunctonsForViews.getMethodMap().entrySet().iterator();
/*
* iterating in case the View is a version of one of View in map
* example:
* View is "CustomEditText", and map contains o view "EditText".
*/
while (it.hasNext())
{
Map.Entry pairs = (Map.Entry)it.next();
if ( viewName.contains((String)pairs.getKey()) )
{
inMap = true;
// next two lines changed
myRunnable = (MyRunnable)(pairs.getValue());
myRunnable.run((View)randomView);
break;
}
}
if (inMap == false)
{
if (viewName.contains("Layout"))
{
return;
}
mSolo.clickOnView((View)randomView);
}
error_count = 0;
}
}catch(Exception exception)
{
exception.printStackTrace();
if(error_count > ERROR_COUNT_LIMIT &&
!(mSolo.getCurrentActivity().getClass().toString().split(" ")[1].equals(LAUNCHER_ACTIVITY_FULL_CLASSNAME)))
{
goingBack();
error_count = 0;
}
return;
}catch(Error error)
{
error.printStackTrace();
error_count ++;
if(error_count > ERROR_COUNT_LIMIT &&
!(mSolo.getCurrentActivity().getClass().toString().split(" ")[1].equals(LAUNCHER_ACTIVITY_FULL_CLASSNAME)))
{
goingBack();
error_count = 0;
}
return;
}
mSolo.sleep(DELAY);
}
/*
* performs a goBack command surrounded with catch/try
*/
public void goingBack()
{
try {
String currentActivity = mSolo.getCurrentActivity().getClass().toString();
mSolo.goBack();
if (mSolo.getCurrentActivity().getClass().toString().equals(currentActivity))
{
for (int i = 0; i< 20; i++)
{
myClickOnScreen();
}
}
} catch (Exception e) {
e.printStackTrace();
} catch (Error e) {
e.printStackTrace();
}
}
/*
* extract the name of View from raw View name.
* example:
* raw View name: android.widget.TextView
* raw View name:TextView
*/
public String parseRawViewName(String rawViewName)
{
if (rawViewName.contains(" "))
{
String [] array = rawViewName.split(" ");
rawViewName = array [0];
}
if (rawViewName.contains(".") || rawViewName.contains("$"))
{
String [] array = rawViewName.split("\\.|$");
rawViewName = array [array.length-1];
}
return rawViewName;
}
public void tearDown() throws Exception {
mSolo.finishOpenedActivities();
}
}
In my app, I have to display PDF file from sdcard in android. The app uses tab functionality so I have used fragments in my app. So how to display pdf file inside fragments?
I have used pdfviewer.jar, but I am not able to display inside fragments, it only works in activity.
And another question is I want to display pdf with multi-zoom and vertical page scrolling to see next/previous pages, not by manually clicking on zoom icon and arrow icon to see next page which is used in pdfviewer.jar.
I am giving the full code below of that changed fragment. I did it 3 years back and that time Sherlock library was used. I think now you have to replace that by appcompat library.
package net.sf.andpdf.pdfviewer;
import java.io.*;
import java.nio.channels.FileChannel;
import android.app.Activity;
import android.content.res.Configuration;
import android.graphics.*;
import android.widget.ImageView;
import android.widget.TextView;
import net.sf.andpdf.nio.ByteBuffer;
import net.sf.andpdf.pdfviewer.gui.TouchImageView;
import net.sf.andpdf.refs.HardReference;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.util.Log;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.sun.pdfview.PDFFile;
import com.sun.pdfview.PDFImage;
import com.sun.pdfview.PDFPage;
import com.sun.pdfview.PDFPaint;
import com.sun.pdfview.decrypt.PDFAuthenticationFailureException;
import com.sun.pdfview.decrypt.PDFPassword;
import com.sun.pdfview.font.PDFFont;
public class PdfViewerFragment extends SherlockFragment {
private static final int STARTPAGE = 1;
private static float STARTZOOM = 1f;
private static final String TAG = "PDFVIEWER";
private static final String FTAG = "PDFVIEWERFRG";
public static final String EXTRA_PDFFILENAME = "net.sf.andpdf.extra.PDFFILENAME";
public static final String EXTRA_SHOWIMAGES = "net.sf.andpdf.extra.SHOWIMAGES";
public static final String EXTRA_ANTIALIAS = "net.sf.andpdf.extra.ANTIALIAS";
public static final String EXTRA_USEFONTSUBSTITUTION = "net.sf.andpdf.extra.USEFONTSUBSTITUTION";
public static final String EXTRA_KEEPCACHES = "net.sf.andpdf.extra.KEEPCACHES";
public static final boolean DEFAULTSHOWIMAGES = true;
public static final boolean DEFAULTANTIALIAS = true;
public static final boolean DEFAULTUSEFONTSUBSTITUTION = false;
public static final boolean DEFAULTKEEPCACHES = true;
private String pdffilename;
private PDFFile mPdfFile;
private int mPage;
private float mZoom;
private File mTmpFile;
private ProgressDialog progress;
private TextView tv_page_no;
String imgFileName;
private ImageView rightArrow;
private ImageView leftArrow;
private PDFPage mPdfPage;
private Thread backgroundThread;
private Activity activity;
TouchImageView tiv;
#Override
public void onAttach(Activity activity) {
Log.i(FTAG, "PDFFragment.onAttatch");
this.activity = activity;
super.onAttach(activity);
}
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Display display = activity.getWindowManager().getDefaultDisplay();
int width = display.getWidth();
int height = display.getHeight();
if(activity.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE )
{
STARTZOOM = (1f*width)/800.0f;
}
else
{
STARTZOOM = (1f*height)/800.0f;
}
Log.i(FTAG, "PDFFragment: onCreate");
}
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
Log.i(FTAG, "PDFFragment: onCreateView");
View docView = inflater.inflate(R.layout.doc_viewer, container, false);
setRetainInstance(true);
boolean showImages = activity.getIntent().getBooleanExtra(PdfViewerFragment.EXTRA_SHOWIMAGES, PdfViewerFragment.DEFAULTSHOWIMAGES);
PDFImage.sShowImages = showImages;
boolean antiAlias = activity.getIntent().getBooleanExtra(PdfViewerFragment.EXTRA_ANTIALIAS, PdfViewerFragment.DEFAULTANTIALIAS);
PDFPaint.s_doAntiAlias = antiAlias;
boolean useFontSubstitution = activity.getIntent().getBooleanExtra(PdfViewerFragment.EXTRA_USEFONTSUBSTITUTION, PdfViewerFragment.DEFAULTUSEFONTSUBSTITUTION);
PDFFont.sUseFontSubstitution= useFontSubstitution;
boolean keepCaches = activity.getIntent().getBooleanExtra(PdfViewerFragment.EXTRA_KEEPCACHES, PdfViewerFragment.DEFAULTKEEPCACHES);
HardReference.sKeepCaches= keepCaches;
Bundle args = getArguments();
if (args != null) {
Log.i(FTAG, "Args Value: "+args.getString(EXTRA_PDFFILENAME));
pdffilename = args.getString(EXTRA_PDFFILENAME);;
} else {
// TODO: open a default document
pdffilename = "/mnt/sdcard/documents/3.pdf";
}
tiv = (TouchImageView) docView.findViewById(R.id.imageView);
leftArrow = (ImageView) docView.findViewById(R.id.leftArrow);
rightArrow = (ImageView) docView.findViewById(R.id.rightArrow);
leftArrow.setVisibility(View.GONE);
rightArrow.setVisibility(View.GONE);
if (pdffilename == null)
{
pdffilename = "No file selected";
}
else if(pdffilename.contains(".pdf"))
{
imgFileName= pdffilename.substring(0, pdffilename.lastIndexOf("."))+"_1.jpg";
mPage = STARTPAGE;
mZoom = STARTZOOM;
progress = ProgressDialog.show(activity, "Loading", "Loading PDF Page", true, true);
leftArrow.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
prevPage();
}
});
rightArrow.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
nextPage();
}
});
tv_page_no = (TextView) docView.findViewById(R.id.navigationText);
tiv.setParent(this);
setContent(null);
}
else if(pdffilename.contains(".jpg") || pdffilename.contains(".jpeg") || pdffilename.contains(".png") || pdffilename.contains(".gif") || pdffilename.contains(".bmp"))
{
imgFileName = pdffilename;
tiv.setImageLocation(imgFileName);
}
else
{
pdffilename = "Invalid file extension";
}
return docView;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
Log.i(FTAG, "PDFFragment: onViewCreated");
super.onViewCreated(view, savedInstanceState);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Log.i(FTAG, "PDFFragment: onActivityCreated");
}
#Override
public void onStart() {
Log.i(FTAG, "PDFFragment.onStart");
super.onStart();
//Bundle args = getArguments();
}
#Override
public void onResume() {
Log.i(FTAG, "PDFFragment.onResume");
super.onResume();
}
#Override
public void onPause() {
Log.i(FTAG, "PDFFragment.onPause");
super.onPause();
}
#Override
public void onSaveInstanceState(Bundle outState) {
Log.i(FTAG, "PDFFragment.onSaveInstanceState");
super.onSaveInstanceState(outState);
}
#Override
public void onStop() {
Log.i(FTAG, "PDFFragment.onStop");
super.onStop();
}
#Override
public void onDestroyView() {
Log.i(FTAG, "PDFFragment.onDestroyView");
super.onDestroyView();
}
#Override
public void onDestroy() {
Log.i(FTAG, "PDFFragment.onDestroy");
super.onDestroy();
if (mTmpFile != null) {
mTmpFile.delete();
mTmpFile = null;
}
}
#Override
public void onDetach() {
Log.i(FTAG, "PDFFragment.onDetach");
super.onDetach();
}
private boolean setContent(String password) {
try {
parsePDF(pdffilename, password);
if(new File(imgFileName).exists())
{
tiv.setImageLocation(imgFileName);
updateTexts(1);
progress.dismiss();
}
else
startRenderThread(mPage, mZoom);
}
catch (PDFAuthenticationFailureException e) {
} catch (Exception e) {
}
return true;
}
public synchronized void startRenderThread(final int page, final float zoom) {
if (backgroundThread != null)
return;
backgroundThread = new Thread(new Runnable() {
public void run() {
try {
if (mPdfFile != null) {
generatePDFPage(page, zoom);
}
} catch (Exception e) {
Log.e(TAG, e.getMessage(), e);
}
backgroundThread = null;
}
});
backgroundThread.start();
}
public void nextPage() {
if (mPdfFile != null) {
if (mPage < mPdfFile.getNumPages()) {
mPage += 1;
imgFileName= pdffilename.substring(0, pdffilename.lastIndexOf("."))+"_"+String.valueOf(mPage)+".jpg";
if(new File(imgFileName).exists())
{
tiv.setImageLocation(imgFileName);
updateTexts(mPage);
progress.dismiss();
}
else
{
progress = ProgressDialog.show(activity, "Loading", "Loading PDF Page " + mPage, true, true);
startRenderThread(mPage, STARTZOOM);
}
}
}
}
public void prevPage() {
if (mPdfFile != null) {
if (mPage > 1) {
mPage -= 1;
imgFileName= pdffilename.substring(0, pdffilename.lastIndexOf("."))+"_"+String.valueOf(mPage)+".jpg";
if(new File(imgFileName).exists())
{
tiv.setImageLocation(imgFileName);
updateTexts(mPage);
progress.dismiss();
}
else
{
progress = ProgressDialog.show(activity, "Loading", "Loading PDF Page " + mPage, true, true);
startRenderThread(mPage, STARTZOOM);
}
}
}
}
protected void updateTexts(int pageNo) {
if (mPdfFile != null) {
tv_page_no.setText("Page "+pageNo+"/"+mPdfFile.getNumPages());
if(mPdfFile.getNumPages() > 1)
{
if(pageNo==1)
leftArrow.setVisibility(View.GONE);
else
leftArrow.setVisibility(View.VISIBLE);
if(pageNo == mPdfFile.getNumPages())
rightArrow.setVisibility(View.GONE);
else
rightArrow.setVisibility(View.VISIBLE);
}
}
}
public void generatePDFPage(final int page, float zoom) throws Exception {
try {
// Only load the page if it's a different page (i.e. not just changing the zoom level)
if (mPdfPage == null || mPdfPage.getPageNumber() != page) {
mPdfPage = mPdfFile.getPage(page, true);
}
float width = mPdfPage.getWidth();
float height = mPdfPage.getHeight();
RectF clip = null;
Bitmap bmp = mPdfPage.getImage((int)(width*zoom), (int)(height*zoom), clip, true, true);
//imgFileName += String.valueOf(page)+".jpg";
FileOutputStream fo = null;
try {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 50, bytes);
File f = new File(imgFileName);
f.createNewFile();
fo = new FileOutputStream(f);
fo.write(bytes.toByteArray());
} catch (IOException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
} catch (Exception ex) {
} finally {
if (fo != null) {
try {
fo.close();
} catch (IOException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}
}
activity.runOnUiThread(new Runnable() {
public void run() {
tiv.setImageLocation(imgFileName);
//tiv.setImageBitmap(BitmapFactory.decodeFile(imgFileName));
updateTexts(page);
if (progress != null)
progress.dismiss();
}
});
} catch (Throwable e) {
Log.e(TAG, e.getMessage(), e);
}
}
public void parsePDF(String filename, String password) throws PDFAuthenticationFailureException {
pdffilename = filename;
try {
File f = new File(filename);
long len = f.length();
if (len == 0) {
}
else {
openFile(f, password);
}
}
catch (PDFAuthenticationFailureException e) {
throw e;
} catch (Throwable e) {
e.printStackTrace();
}
}
/**
* <p>Open a specific pdf file. Creates a DocumentInfo from the file,
* and opens that.</p>
*
* <p><b>Note:</b> Mapping the file locks the file until the PDFFile
* is closed.</p>
*
* #param file the file to open
* #throws IOException
*/
public void openFile(File file, String password) throws IOException {
// first open the file for random access
RandomAccessFile raf = null;
try
{
raf = new RandomAccessFile(file, "r");
// extract a file channel
FileChannel channel = raf.getChannel();
// now memory-map a byte-buffer
ByteBuffer bb = ByteBuffer.NEW(channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size()));
// create a PDFFile from the data
if (password == null)
mPdfFile = new PDFFile(bb);
else
mPdfFile = new PDFFile(bb, new PDFPassword(password));
} catch (Exception ex)
{
} finally {
raf.close();
}
}
}
This is load PDF in fragment use PDFViewer
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_keluarga, container, false);
pdfView = (PDFView) v.findViewById(R.id.keluargaPdf);
pdfView.fromAsset("tiga.pdf").load();
// Inflate the layout for this fragment
return v;
}