Display PDF in fragments within app android - android

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

Related

Set GIF image to Custom ImageView

I have custom ImageView for animated GIF image. i want to show GIF image, I tried but in this case it is contain url in Async instead I want to show GIF image from raw folder without using Glide. Anyone have any idea how to show image? Please guyz help to solve this problem!!!
I tried this for set raw file
new GifStaticData() {
#Override
protected void onPostExecute(Resource drawable) {
super.onPostExecute(drawable);
gifImageView.setImageResource(R.raw.earth_tilt_animation);
// Log.d(TAG, "GIF width is " + gifImageView.getGifWidth());
// Log.d(TAG, "GIF height is " + gifImageView.getGifHeight());
}
}.execute(R.raw.earth_tilt_animation);
GifStaticData.java
public class GifStaticData extends AsyncTask<Resource, Void, Resource> {
private static final String TAG = "GifDataDownloader";
#Override protected Resource doInBackground(final Resource... params) {
final Resource gifUrl = params[0];
if (gifUrl == null)
return null;
try {
// return ByteArrayHttpClient.get(gifUrl);
return gifUrl;
} catch (OutOfMemoryError e) {
Log.e(TAG, "GifDecode OOM: " + gifUrl, e);
return null;
}
}
}
GifImageView.java
public class GifImageView extends ImageView implements Runnable {
private static final String TAG = "GifDecoderView";
private GifDecoder gifDecoder;
private Bitmap tmpBitmap;
private final Handler handler = new Handler(Looper.getMainLooper());
private boolean animating;
private boolean shouldClear;
private Thread animationThread;
private OnFrameAvailable frameCallback = null;
private long framesDisplayDuration = -1L;
private OnAnimationStop animationStopCallback = null;
private final Runnable updateResults = new Runnable() {
#Override
public void run() {
if (tmpBitmap != null && !tmpBitmap.isRecycled()) {
setImageBitmap(tmpBitmap);
}
}
};
private final Runnable cleanupRunnable = new Runnable() {
#Override
public void run() {
tmpBitmap = null;
gifDecoder = null;
animationThread = null;
shouldClear = false;
}
};
public GifImageView(final Context context, final AttributeSet attrs) {
super(context, attrs);
}
public GifImageView(final Context context) {
super(context);
}
public void setBytes(final byte[] bytes) {
gifDecoder = new GifDecoder();
try {
gifDecoder.read(bytes);
gifDecoder.advance();
} catch (final OutOfMemoryError e) {
gifDecoder = null;
Log.e(TAG, e.getMessage(), e);
return;
}
if (canStart()) {
animationThread = new Thread(this);
animationThread.start();
}
}
public long getFramesDisplayDuration() {
return framesDisplayDuration;
}
/**
* Sets custom display duration in milliseconds for the all frames. Should be called before {#link
* #startAnimation()}
*
* #param framesDisplayDuration Duration in milliseconds. Default value = -1, this property will
* be ignored and default delay from gif file will be used.
*/
public void setFramesDisplayDuration(long framesDisplayDuration) {
this.framesDisplayDuration = framesDisplayDuration;
}
public void startAnimation() {
animating = true;
if (canStart()) {
animationThread = new Thread(this);
animationThread.start();
}
}
public boolean isAnimating() {
return animating;
}
public void stopAnimation() {
animating = false;
if (animationThread != null) {
animationThread.interrupt();
animationThread = null;
}
}
public void clear() {
animating = false;
shouldClear = true;
stopAnimation();
handler.post(cleanupRunnable);
}
private boolean canStart() {
return animating && gifDecoder != null && animationThread == null;
}
public int getGifWidth() {
return gifDecoder.getWidth();
}
public int getGifHeight() {
return gifDecoder.getHeight();
}
#Override public void run() {
if (shouldClear) {
handler.post(cleanupRunnable);
return;
}
final int n = gifDecoder.getFrameCount();
do {
for (int i = 0; i < n; i++) {
if (!animating) {
break;
}
//milliseconds spent on frame decode
long frameDecodeTime = 0;
try {
long before = System.nanoTime();
tmpBitmap = gifDecoder.getNextFrame();
frameDecodeTime = (System.nanoTime() - before) / 1000000;
if (frameCallback != null) {
tmpBitmap = frameCallback.onFrameAvailable(tmpBitmap);
}
if (!animating) {
break;
}
handler.post(updateResults);
} catch (final ArrayIndexOutOfBoundsException | IllegalArgumentException e) {
Log.w(TAG, e);
}
if (!animating) {
break;
}
gifDecoder.advance();
try {
int delay = gifDecoder.getNextDelay();
// Sleep for frame duration minus time already spent on frame decode
// Actually we need next frame decode duration here,
// but I use previous frame time to make code more readable
delay -= frameDecodeTime;
if (delay > 0) {
Thread.sleep(framesDisplayDuration > 0 ? framesDisplayDuration : delay);
}
} catch (final Exception e) {
// suppress any exception
// it can be InterruptedException or IllegalArgumentException
}
}
} while (animating);
if (animationStopCallback != null) {
animationStopCallback.onAnimationStop();
}
}
public OnFrameAvailable getOnFrameAvailable() {
return frameCallback;
}
public void setOnFrameAvailable(OnFrameAvailable frameProcessor) {
this.frameCallback = frameProcessor;
}
public interface OnFrameAvailable {
Bitmap onFrameAvailable(Bitmap bitmap);
}
public OnAnimationStop getOnAnimationStop() {
return animationStopCallback;
}
public void setOnAnimationStop(OnAnimationStop animationStop) {
this.animationStopCallback = animationStop;
}
public interface OnAnimationStop {
void onAnimationStop();
}
#Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
clear();
}
}
I had to play and pause the Gif image Glide - Cannot stop gif onClick- Getting TransitionDrawable instead of Animate/GifDrawable
The idea is to get drawable from view,checking if it is an instance of Gifdrawable and playing and pausing it.(Hoping the gif image is already playing)
Add this In OnClick of GifImageView
Drawable drawable = ((ImageView) v).getDrawable();
if (drawable instanceof GifDrawable) {
GifDrawable animatable = (GifDrawable) drawable;
if (animatable.isRunning()) {
animatable.stop();
} else {
animatable.start();
}
}
I found the solution of above problem using GifMovieView!!!
GifMovieViewer.java
public class GifMovieViewer extends Activity {
private Button btnStart;
private GifMovieView gif1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gif_movie_viewer);
gif1 = (GifMovieView) findViewById(R.id.gif1);
btnStart = (Button) findViewById(R.id.btnStart);
btnStart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
gif1.setMovieResource(R.drawable.earth_tilt_animation);
//for pause
// gif1.setPaused(gif1.isPaused());
}
});
}
public void onGifClick(View v) {
GifMovieView gif = (GifMovieView) v;
gif.setPaused(!gif.isPaused());
}
}

How to implement paho MQTT client in android that has to be accessed in multiple activities

I am having an app that has multiple activities and uses MQTT.
I am using the paho client in gradle dependencies as follows
compile 'org.eclipse.paho:org.eclipse.paho.android.service:1.0.3-SNAPSHOT'
compile 'org.eclipse.paho:org.eclipse.paho.client.mqttv3:1.0.3-SNAPSHOT'
I would be using username and password to connect to the broker and some activities would be using diffrent user name and password.
currently I am handling the connect,subscribeand publish tasks in each activity as in the code that I will include below. As the activities get more and more I am having issues. Please suggest me how I can port the code to a service or singleton so that it can be reused and become efficient.
Here is one of the activities
package net.kindows.chitchat;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.pixplicity.easyprefs.library.Prefs;
import net.kindows.SplashScreen;
import net.kindows.common.ApplicationLoader;
import net.kindows.common.utils;
import net.kindows.intlPhone.IntlPhoneInput;
import org.eclipse.paho.android.service.MqttAndroidClient;
import org.eclipse.paho.client.mqttv3.IMqttActionListener;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.IMqttToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import butterknife.Bind;
import butterknife.ButterKnife;
import de.keyboardsurfer.android.widget.crouton.Crouton;
import static net.kindows.common.ApplicationLoader._toast;
public class LoginActivity extends AppCompatActivity implements MqttCallback {
private static final String TAG = "LoginActivity";
private static final int REQUEST_SIGNUP = 0;
private static final int REQUEST_PAS_RESET = 1;
private static final Integer LOGGED_OUT = 0;
private static final Integer LOGGING_IN = 1;
private static final Integer WAITING_FOR_SING_IN_ACK = 2;
private static final Integer LOGGED_IN = 3;
private static final Integer VERIFICATION_FAILED = 4;
#Bind(R.id.input_password)
EditText _passwordText;
#Bind(R.id.btn_login)
Button _loginButton;
#Bind(R.id.link_signup)
TextView _signupLink;
#Bind(R.id.my_phone_input)
IntlPhoneInput _phoneInputView;
String sUserName = null;
String sPassword = null;
String sDestination = null;
String sMessage = null;
private Integer state;
private Handler han = new Handler();
private MqttConnectOptions connOpt;
private ProgressDialog _progressDialog;
/*
MQTT mqtt = null;
FutureConnection connection = null;*/
private boolean isMinimized = false;
private String clientId;
private Handler loginAgain = new Handler();
private Handler timeout;
private MqttAndroidClient client;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
ButterKnife.bind(this);
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
//connect();
_loginButton.setEnabled(false);
// _phoneInputView.setNumber(ApplicationLoader.getSim1number(LoginActivity.this));
_phoneInputView.setOnValidityChange(new IntlPhoneInput.IntlPhoneInputListener() {
#Override
public void done(View view, boolean isValid) {
if (isValid) {
_loginButton.setEnabled(true);
} else _loginButton.setEnabled(false);
}
});
_loginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!ApplicationLoader.isConnected(LoginActivity.this, true)) {
} else login();
}
});
_signupLink.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Start the Signup activity
Prefs.putInt(getString(R.string.key_reset_pass), 2);
Intent intent = new Intent(getApplicationContext(), SignUpActivity.class);
startActivityForResult(intent, REQUEST_SIGNUP);
}
});
state = LOGGED_OUT;
connOpt = new MqttConnectOptions();
connOpt.setCleanSession(true);
connOpt.setKeepAliveInterval(30);
connOpt.setCleanSession(true);
clientId = ApplicationLoader.getClientId(LoginActivity.this);
client = new MqttAndroidClient(this, "tcp://104.131.50.64:1883", clientId, MqttAndroidClient.Ack.AUTO_ACK);//this,"tcp://104.131.50.64:1883", "app1", null);
}
#Override
protected void onStop() {
super.onStop();
isMinimized = true;
// super.onDestroy();
try {
client.close();
} catch (Exception e) {
// client.unregisterResources();
e.printStackTrace();
}
Crouton.cancelAllCroutons();
loginAgain.removeCallbacks(null);
han.removeCallbacks(null);
}
#Override
protected void onStart() {
super.onStart();
// Do not go to splash screen if came from signup activity
if (isMinimized && Prefs.getBoolean(getString(R.string.show_splash), true)) {
isMinimized = false;
han.removeCallbacks(null);
startActivity(new Intent(this, SplashScreen.class));
finish();
}
Prefs.putBoolean(getString(R.string.show_splash), true);
if (utils.getLoginState_login()) {
han.removeCallbacks(null);
utils._startActivity(this, MainActivity.class);
finish();
}
}
#Override
protected void onResume() {
super.onResume();
if (utils.getLoginState_login()) {
han.removeCallbacks(null);
utils._startActivity(this, MainActivity.class);
finish();
}
ApplicationLoader.isConnected(this, true);
}
public void login() {
Log.d(TAG, getString(R.string.login));
_toast(getString(R.string.logging_in), LoginActivity.this);
try {
client.close();
} catch (Exception e) {
e.printStackTrace();
}
try {
client.close();
} catch (Exception e) {
e.printStackTrace();
}
// Disable login button for 5 secs
final boolean lastLoginState = _loginButton.isEnabled();
_loginButton.setEnabled(false);
loginAgain.postDelayed(new Runnable() {
#Override
public void run() {
_loginButton.setEnabled(lastLoginState);
}
}, 5000);
_progressDialog = new ProgressDialog(LoginActivity.this,
R.style.AppTheme_Dark_Dialog);
// String phone = _phoneText.getText().toString();
String password = _passwordText.getText().toString();
String numb = _phoneInputView.getNumber().replace("+", "");
connectMQTT(numb, password);
_progressDialog.setIndeterminate(true);
_progressDialog.setMessage("Authenticating...");
_progressDialog.show();
han.postDelayed(
new Runnable() {
public void run() { // On complete call either onLoginSuccess or onLoginFailed
//onLoginSuccess();
onLoginFailed();
_progressDialog.dismiss();
}
}, ApplicationLoader.timeOUT);
}
private void publish2MQQT(MqttAndroidClient client1, String topic, String msg) throws MqttException {
if (client1 != null) {
MqttMessage msg2 = new MqttMessage();
msg2.setPayload(msg.getBytes());
client1.publish(topic, msg2, this, new IMqttActionListener() {
#Override
public void onSuccess(IMqttToken asyncActionToken) {
// _sendErrorLog("on sucess of publish");
}
#Override
public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
// _sendErrorLog("on fail of publish e= " + exception.getMessage());
_progressDialog.dismiss();
_toast((exception != null ? exception.getMessage() : ""), LoginActivity.this);
}
});
// Log.e("mqtt ", "published " + msg);
}
}
private void _sendErrorLog(String s) {
Log.e("LOG", s);
}
private void connectMQTT(final String user, final String pass) {
Log.e("connectMQTT", "1");
try {
connOpt.setUserName(user);
connOpt.setPassword(pass.toCharArray());
_sendErrorLog("on connteing with " + user + " " + pass);
client.connect(connOpt, this, new IMqttActionListener() {
#Override
public void onSuccess(IMqttToken asyncActionToken) {
_sendErrorLog("on success of connect");
try {
client.subscribe("astr/app/iremote/" + user.replace("+", ""), 0, this, new IMqttActionListener() {
#Override
public void onSuccess(IMqttToken asyncActionToken) {
_sendErrorLog("on sucess of subscribe");
// TODO: Implement your own authentication logic here.
JsonObject msg = new JsonObject();
msg.addProperty("u", user);
msg.addProperty("P", pass);
sUserName = user;
sPassword = pass;
sDestination = "astr/admin/signin";
sMessage = msg.toString();
state = LOGGING_IN;
try {
Log.e("register", "publishing signin message");
if (client == null) {
Log.e("register", "publishing register message client is null");
}
publish2MQQT(client, sDestination, sMessage);
state = WAITING_FOR_SING_IN_ACK;
} catch (MqttException e) {
e.printStackTrace();
Log.e("register", "got exception in publish " + e.toString());
_progressDialog.dismiss();
_toast(e.getMessage(), LoginActivity.this);
}
}
#Override
public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
_sendErrorLog("on failure of subscribe " + exception.getMessage());
_progressDialog.dismiss();
_toast((exception != null ? exception.getMessage() : ""), LoginActivity.this);
}
});
// client.subscribe("astr/app/iremote/" + _num_2b_verified.replace("+", ""));
} catch (MqttException | NullPointerException e) {
e.printStackTrace();
}
}
#Override
public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
_sendErrorLog("on failure of connect" + exception.getMessage());
han.removeCallbacks(null);
try {
_progressDialog.dismiss();
} catch (Exception e) {
e.printStackTrace();
}
_toast((exception != null ? exception.getMessage() : ""), LoginActivity.this);
}
});
client.setCallback(this);
} catch (MqttException e) {
e.printStackTrace();
Log.e("connectMQTT", "got exception :: " + e.toString());
}
}
#Override
public void connectionLost(Throwable throwable) {
Log.e("connection", "lost");
//connectMQTT();
}
#Override
protected void onDestroy() {
super.onDestroy();
try {
client.close();
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void messageArrived(String s, MqttMessage mqttMessage) throws Exception {
String msgRecived = new String(mqttMessage.getPayload());
/* Log.e("message arrived", "-------------------------------------------------");
Log.e("message arrived", "| Topic:" + s);*/
Log.e("message arrived", "| Message: " + msgRecived);
/*Log.e("message arrived" , "-------------------------------------------------");*/
if (state.equals(WAITING_FOR_SING_IN_ACK)) {
han.removeCallbacks(null);
JsonParser jp = new JsonParser();
JsonObject reply = (JsonObject) jp.parse(msgRecived);
if (reply.get("s").getAsInt() == 200) {
_toast(getString(R.string.logged_in), LoginActivity.this);
_progressDialog.dismiss();
_phoneInputView.setVisibility(View.GONE);
_passwordText.setVisibility(View.VISIBLE);
_loginButton.setText(R.string.logged_in);
_loginButton.setEnabled(true);
state = LOGGED_IN;
utils.storeLoginState(true, sUserName, sPassword);
try {
client.close();
} catch (Exception e) {
e.printStackTrace();
}
state = LOGGED_IN;
han.removeCallbacks(null);
try {
client.close();
} catch (Exception e) {
e.printStackTrace();
}
startActivity(new Intent(this, MainActivity.class));
//finish();
} else {
state = VERIFICATION_FAILED;
utils.storeLoginState(false, "", "");
onLoginFailed();
}
}
}
#Override
public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_SIGNUP) {
if (resultCode == RESULT_OK) {
// TODO: Implement successful signup logic here
// By default we just finish the Activity and log them in automatically
this.finish();
}
}
}
#Override
public void onBackPressed() {
// Disable going back to the MainActivity
moveTaskToBack(true);
}
public void onLoginFailed() {
// ApplicationLoader._toast("Login failed",LoginActivity.this);
_toast(getString(R.string.log_in_failed), LoginActivity.this);
_passwordText.setVisibility(View.VISIBLE);
_phoneInputView.setVisibility(View.VISIBLE);
_loginButton.setEnabled(false);
// Enable Login after 5000 ms with editing the number
loginAgain.postDelayed(new Runnable() {
#Override
public void run() {
_loginButton.setEnabled(_phoneInputView.isValid());
}
}, 5000);
}
#Override
public void onPause() {
super.onPause();
//disconnect();
}
public void resetPass(View view) {
// Start the Signup activity
Prefs.putInt(getString(R.string.key_reset_pass), 1);
Intent intent = new Intent(getApplicationContext(), SignUpActivity.class);
startActivityForResult(intent, REQUEST_PAS_RESET);
}
}
I believe the best option for you would be to implement those same functionalities in a Fragment. I won't read through your whole source code because it's enormous and I ain't got time for that, but I'll give you some ideas and directions and you can migrate it yourself.
Step 1: Create a MQTTFragment:
public class MQTTFragment extends Fragment implements MqttCallback {
public static final String TAG = "MQTTFragment.tag";
#Override
public void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// avoid this frag getting destroyed during rotation
setRetainInstance(true);
}
// DO NOT #Override onCreateView, this fragment have no views
// Put here ALL the code related to MQTT,
// any functionality you want to be able to call from Activity, make public, all the rest is private
// this fragment should also remember the current state of the connection
// this fragment can also have interface and listener pattern in case to past result back to activity.
... your mqtt code
}
Step 2: Every activity u want to use MQTT functionality includes the MQTTFragment
public class MyActivity extends AppCompatActivity {
private MQTTFragment mqttFragment;
// during onCreate you get or create the fragment
#Override public void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(savedInstanceState == null) {
mqttFragment = new MQTTFragment();
getSupportFragmentManager()
.beginTransaction()
.add(mqttFragment, MQTTFragment.TAG)
.commit();
} else {
mqttFragment =
(MQTTFragment) getSupportFragmentManager()
.findFragmentByTag(MQTTFragment.TAG);
}
}
// now on this activity you can call anything MQTT related functionality from the Fragment
}

How to wait for an activity to finish in asynctask

I know that the purpose of the AsyncTask is to run asynchronously with other tasks of the app and finish in the background, but apparently I need to do this, I need to start an activity from AsyncTask and since I cant extend an activity in this class I can not use startactivityforresult, so how can I wait till my activity finishes?
Here is my code:
public class ListSpdFiles extends AsyncTask<Void, Void, String[]> {
public AsyncResponse delegate = null;
private static final String TAG = "ListSpdFiles: ";
Context applicationContext;
ContentResolver spdappliationcontext;
public final CountDownLatch setSignal= new CountDownLatch(1);
private final ReentrantLock lock = new ReentrantLock();
String username = "";
/**
* Status code returned by the SPD on operation success.
*/
private static final int SUCCESS = 4;
private boolean createbutt;
private boolean deletebutt;
private String initiator;
private String path;
private String pass;
private String url;
private SecureApp pcas;
private boolean isConnected = false; // connected to PCAS service?
private String CurrentURL = null;
private PcasConnection pcasConnection = new PcasConnection() {
#Override
public void onPcasServiceConnected() {
Log.d(TAG, "pcasServiceConnected");
latch.countDown();
}
#Override
public void onPcasServiceDisconnected() {
Log.d(TAG, "pcasServiceDisconnected");
}
};
private CountDownLatch latch = new CountDownLatch(1);
public ListSpdFiles(boolean createbutt, boolean deletebutt, String url, String pass, Context context, String initiator, String path, AsyncResponse asyncResponse) {
this.initiator = initiator;
this.path = path;
this.pass= pass;
this.url= url;
this.createbutt= createbutt;
this.deletebutt=deletebutt;
applicationContext = context.getApplicationContext();
spdappliationcontext = context.getContentResolver();
delegate = asyncResponse;
}
private void init() {
Log.d(TAG, "starting task");
pcas = new AndroidNode(applicationContext, pcasConnection);
isConnected = pcas.connect();
}
private void term() {
Log.d(TAG, "terminating task");
if (pcas != null) {
pcas.disconnect();
pcas = null;
isConnected = false;
}
}
#Override
protected void onPreExecute() {
super.onPreExecute();
init();
}
#Override
protected String[] doInBackground(Void... params) {
CurrentURL = getLastAccessedBrowserPage();
// check if connected to PCAS Service
if (!isConnected) {
Log.v(TAG, "not connected, terminating task");
return null;
}
// wait until connection with SPD is up
try {
if (!latch.await(20, TimeUnit.SECONDS)) {
Log.v(TAG, "unable to connected within allotted time, terminating task");
return null;
}
} catch (InterruptedException e) {
Log.v(TAG, "interrupted while waiting for connection in lsdir task");
return null;
}
// perform operation (this is where the actual operation is called)
try {
return lsdir();
} catch (DeadServiceException e) {
Log.i(TAG, "service boom", e);
return null;
} catch (DeadDeviceException e) {
Log.i(TAG, "device boom", e);
return null;
}
}
#Override
protected void onPostExecute(String[] listOfFiles) {
super.onPostExecute(listOfFiles);
if (listOfFiles == null) {
Log.i(TAG, "task concluded with null list of files");
} else {
Log.i(TAG, "task concluded with the following list of files: "
+ Arrays.toString(listOfFiles));
}
term();
delegate.processFinish(username);
}
#Override
protected void onCancelled(String[] listOfFiles) {
super.onCancelled(listOfFiles);
Log.i(TAG, "lsdir was canceled");
term();
}
/**
* Returns an array of strings containing the files available at the given path, or
* {#code null} on failure.
*/
private String[] lsdir() throws DeadDeviceException, DeadServiceException {
Result<List<String>> result = pcas.lsdir(initiator, path); // the lsdir call to the
boolean crtbut = createbutt;
boolean dlbut= deletebutt;
ArrayList<String> mylist = new ArrayList<String>();
final Global globalVariable = (Global) applicationContext;
if (crtbut==false && dlbut == false){
if ( globalVariable.getPasswordButt()==false ) {
final boolean isusername = globalVariable.getIsUsername();
if (isusername == true) {
Log.i(TAG, "current url: " + CurrentURL);
if (Arrays.toString(result.getValue().toArray(new String[0])).contains(CurrentURL)) {
String sharareh = Arrays.toString(result.getValue().toArray(new String[0]));
String[] items = sharareh.split(", ");
for (String item : items) {
String trimmed;
if (item.startsWith("[" + CurrentURL + ".")) {
trimmed = item.replace("[" + CurrentURL + ".", "");
if (trimmed.endsWith(".txt]")) {
trimmed = trimmed.replace(".txt]", "");
mylist.add(trimmed.replace(".txt]", ""));
} else if (trimmed.endsWith(".txt")) {
trimmed = trimmed.replace(".txt", "");
mylist.add(trimmed.replace(".txt", ""));
}
Log.i(TAG, "list of files sharareh: " + trimmed);
} else if (item.startsWith(CurrentURL + ".")) {
trimmed = item.replace(CurrentURL + ".", "");
if (trimmed.endsWith(".txt]")) {
trimmed = trimmed.replace(".txt]", "");
mylist.add(trimmed.replace(".txt]", ""));
} else if (trimmed.endsWith(".txt")) {
trimmed = trimmed.replace(".txt", "");
mylist.add(trimmed.replace(".txt", ""));
}
Log.i(TAG, "list of files sharareh: " + trimmed);
}
}
}
globalVariable.setPopupdone(false);
Intent i = new Intent(applicationContext, PopUp.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.putExtra("EXTRA_SESSION_ID", mylist);
applicationContext.startActivity(i);
username = globalVariable.getUsername();
}
else if (isusername == false)
Log.i(TAG, "Wrong Input Type For Username.");
}
if (result.getState() != SUCCESS) {
Log.v(TAG, "operation failed");
return null;
}
if (result.getValue() == null) {
Log.v(TAG, "operation succeeded but operation returned null list");
return null;
}
return result.getValue().toArray(new String[0]);
}
//}
if (result.getState() != SUCCESS) {
Log.v(TAG, "operation failed");
return null;
}
if (result.getValue() == null) {
Log.v(TAG, "operation succeeded but operation returned null list");
return null;
}
return result.getValue().toArray(new String[0]);
}
public String getLastAccessedBrowserPage() {
String Domain = null;
Cursor webLinksCursor = spdappliationcontext.query(Browser.BOOKMARKS_URI, Browser.HISTORY_PROJECTION, null, null, Browser.BookmarkColumns.DATE + " DESC");
int row_count = webLinksCursor.getCount();
int title_column_index = webLinksCursor.getColumnIndexOrThrow(Browser.BookmarkColumns.TITLE);
int url_column_index = webLinksCursor.getColumnIndexOrThrow(Browser.BookmarkColumns.URL);
if ((title_column_index > -1) && (url_column_index > -1) && (row_count > 0)) {
webLinksCursor.moveToFirst();
while (webLinksCursor.isAfterLast() == false) {
if (webLinksCursor.getInt(Browser.HISTORY_PROJECTION_BOOKMARK_INDEX) != 1) {
if (!webLinksCursor.isNull(url_column_index)) {
Log.i("History", "Last page browsed " + webLinksCursor.getString(url_column_index));
try {
Domain = getDomainName(webLinksCursor.getString(url_column_index));
Log.i("Domain", "Last page browsed " + Domain);
return Domain;
} catch (URISyntaxException e) {
e.printStackTrace();
}
break;
}
}
webLinksCursor.moveToNext();
}
}
webLinksCursor.close();
return null;
}
public String getDomainName(String url) throws URISyntaxException {
URI uri = new URI(url);
String domain = uri.getHost();
return domain.startsWith("www.") ? domain.substring(4) : domain;
}}
My Activity class:
public class PopUp extends Activity {
private static final String TAG = "PopUp";
ArrayList<String> value = null;
ArrayList<String> usernames;
#Override
protected void onCreate(Bundle savedInstanceState) {
final Global globalVariable = (Global) getApplicationContext();
globalVariable.setUsername("");
Bundle extras = getIntent().getExtras();
if (extras != null) {
value = extras.getStringArrayList("EXTRA_SESSION_ID");
}
usernames = value;
super.onCreate(savedInstanceState);
setContentView(R.layout.popupactivity);
final Button btnOpenPopup = (Button) findViewById(R.id.openpopup);
btnOpenPopup.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View arg0) {
LayoutInflater layoutInflater = (LayoutInflater) getBaseContext().getSystemService(LAYOUT_INFLATER_SERVICE);
View popupView = layoutInflater.inflate(R.layout.popup, null);
final PopupWindow popupWindow = new PopupWindow(popupView, LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
Button btnSelect = (Button) popupView.findViewById(R.id.select);
Spinner popupSpinner = (Spinner) popupView.findViewById(R.id.popupspinner);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(PopUp.this, android.R.layout.simple_spinner_item, usernames);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
popupSpinner.setAdapter(adapter);
popupSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
globalVariable.setUsername(usernames.get(arg2));
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
btnSelect.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View v) {
globalVariable.setPopupdone(true);
popupWindow.dismiss();
finish();
}
}
);
popupWindow.showAsDropDown(btnOpenPopup, 50, -30);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.poupup_menu, menu);
return true;
}}

Loading many asset effectively into android project

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

POI's billboard are not shown

I'm using the ARexampleLocationBased tutorial ,the POIS ar correctly shown but the annottations are not shown ,,the program works correct but the billoboards image down the POI's are not visible
package pfg.proyecto.com.proyecto;
import android.view.View;
import com.metaio.sdk.ARELActivity;
public class ARELViewActivity extends ARELActivity
{
#Override
protected int getGUILayout()
{
return R.layout.activity_main;
}
public void onButtonClick(View v)
{
finish();
}
}
and this is the main activity code
package pfg.proyecto.com.proyecto;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextPaint;
import android.util.Log;
import android.view.View;
import com.metaio.cloud.plugin.util.MetaioCloudUtils;
import com.metaio.sdk.ARELInterpreterAndroidJava;
import com.metaio.sdk.ARViewActivity;
import com.metaio.sdk.MetaioDebug;
import com.metaio.sdk.jni.AnnotatedGeometriesGroupCallback;
import com.metaio.sdk.jni.EGEOMETRY_FOCUS_STATE;
import com.metaio.sdk.jni.IAnnotatedGeometriesGroup;
import com.metaio.sdk.jni.IGeometry;
import com.metaio.sdk.jni.IMetaioSDKCallback;
import com.metaio.sdk.jni.IRadar;
import com.metaio.sdk.jni.ImageStruct;
import com.metaio.sdk.jni.LLACoordinate;
import com.metaio.sdk.jni.Rotation;
import com.metaio.sdk.jni.SensorValues;
import com.metaio.sdk.jni.Vector3d;
import com.metaio.tools.io.AssetsManager;
import java.io.File;
import java.io.IOException;
import java.util.concurrent.locks.Lock;
public class MainActivity extends ARViewActivity
{
private IAnnotatedGeometriesGroup mAnnotatedGeometriesGroup;
private MyAnnotatedGeometriesGroupCallback mAnnotatedGeometriesGroupCallback;
/**
* Geometries
*/
private IGeometry mLondonGeo;
private IGeometry mMunichGeo;
private IGeometry mRomeGeo;
private IGeometry mTokyoGeo;
private IGeometry mParisGeo;
private IRadar mRadar;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
// Set GPS tracking configuration
boolean result = metaioSDK.setTrackingConfiguration("GPS", false);
new LoadAssets().execute(0);
MetaioDebug.log("Tracking data loaded: " + result);
}
#Override
protected void onDestroy()
{
// Break circular reference of Java objects
if (mAnnotatedGeometriesGroup != null)
{
mAnnotatedGeometriesGroup.registerCallback(null);
}
if (mAnnotatedGeometriesGroupCallback != null)
{
mAnnotatedGeometriesGroupCallback.delete();
mAnnotatedGeometriesGroupCallback = null;
}
super.onDestroy();
}
#Override
public void onDrawFrame()
{
if (metaioSDK != null && mSensors != null)
{
SensorValues sensorValues = mSensors.getSensorValues();
float heading = 0.0f;
if (sensorValues.hasAttitude())
{
float m[] = new float[9];
sensorValues.getAttitude().getRotationMatrix(m);
Vector3d v = new Vector3d(m[6], m[7], m[8]);
v.normalize();
heading = (float)(-Math.atan2(v.getY(), v.getX()) - Math.PI / 2.0);
}
IGeometry geos[] = new IGeometry[] {mLondonGeo, mParisGeo, mRomeGeo, mTokyoGeo,};
Rotation rot = new Rotation((float)(Math.PI / 2.0), 0.0f, -heading);
for (IGeometry geo : geos)
{
if (geo != null)
{
geo.setRotation(rot);
}
}
}
super.onDrawFrame();
}
public void onButtonClick(View v)
{
finish();
}
#Override
protected int getGUILayout()
{
return R.layout.activity_main;
}
#Override
protected IMetaioSDKCallback getMetaioSDKCallbackHandler()
{
return null;
}
#Override
protected void loadContents()
{
mAnnotatedGeometriesGroup = metaioSDK.createAnnotatedGeometriesGroup();
mAnnotatedGeometriesGroupCallback = new MyAnnotatedGeometriesGroupCallback();
mAnnotatedGeometriesGroup.registerCallback(mAnnotatedGeometriesGroupCallback);
// Clamp geometries' Z position to range [5000;200000] no matter how close or far they are
// away.
// This influences minimum and maximum scaling of the geometries (easier for development).
metaioSDK.setLLAObjectRenderingLimits(5, 200);
// Set render frustum accordingly
metaioSDK.setRendererClippingPlaneLimits(10, 220000);
// let's create LLA objects for known cities
LLACoordinate munich = new LLACoordinate(48.142573, 11.550321, 0, 0);
LLACoordinate london = new LLACoordinate(51.50661, -0.130463, 0, 0);
LLACoordinate tokyo = new LLACoordinate(35.657464, 139.773865, 0, 0);
LLACoordinate rome = new LLACoordinate(41.90177, 12.45987, 0, 0);
LLACoordinate paris = new LLACoordinate(48.85658, 2.348671, 0, 0);
LLACoordinate parque = new LLACoordinate(36.465985, -6.201081, 0, 0);
// Load some POIs. Each of them has the same shape at its geoposition. We pass a string
// (const char*) to IAnnotatedGeometriesGroup::addGeometry so that we can use it as POI
// title
// in the callback, in order to create an annotation image with the title on it.
mLondonGeo = createPOIGeometry(london);
mAnnotatedGeometriesGroup.addGeometry(mLondonGeo, "London");
mParisGeo = createPOIGeometry(paris);
mAnnotatedGeometriesGroup.addGeometry(mParisGeo, "Paris");
mRomeGeo = createPOIGeometry(rome);
mAnnotatedGeometriesGroup.addGeometry(mRomeGeo, "Rome");
mTokyoGeo = createPOIGeometry(tokyo);
mAnnotatedGeometriesGroup.addGeometry(mTokyoGeo, "Tokyo");
File metaioManModel =
AssetsManager.getAssetPathAsFile(getApplicationContext(),
"metaioman.md2");
if (metaioManModel != null)
{
mMunichGeo = metaioSDK.createGeometry(metaioManModel);
if (mMunichGeo != null)
{
mMunichGeo.setTranslationLLA(munich);
mMunichGeo.setLLALimitsEnabled(true);
mMunichGeo.setScale(500);
}
else
{
MetaioDebug.log(Log.ERROR, "Error loading geometry: " + metaioManModel);
}
}
// create radar
mRadar = metaioSDK.createRadar();
mRadar.setBackgroundTexture(AssetsManager.getAssetPathAsFile(getApplicationContext(),
"radar.png"));
mRadar.setObjectsDefaultTexture(AssetsManager.getAssetPathAsFile(getApplicationContext(),
"yellow.png"));
mRadar.setRelativeToScreen(IGeometry.ANCHOR_TL);
// add geometries to the radar
mRadar.add(mLondonGeo);
mRadar.add(mMunichGeo);
mRadar.add(mTokyoGeo);
mRadar.add(mParisGeo);
mRadar.add(mRomeGeo);
}
private IGeometry createPOIGeometry(LLACoordinate lla)
{
final File path =
AssetsManager.getAssetPathAsFile(getApplicationContext(),
"ExamplePOI.obj");
if (path != null)
{
IGeometry geo = metaioSDK.createGeometry(path);
geo.setTranslationLLA(lla);
geo.setLLALimitsEnabled(true);
geo.setScale(100);
return geo;
}
else
{
MetaioDebug.log(Log.ERROR, "Missing files for POI geometry");
return null;
}
}
#Override
protected void onGeometryTouched(final IGeometry geometry)
{
MetaioDebug.log("Geometry selected: " + geometry);
mSurfaceView.queueEvent(new Runnable()
{
#Override
public void run()
{
mRadar.setObjectsDefaultTexture(AssetsManager.getAssetPathAsFile(getApplicationContext(),
"yellow.png"));
mRadar.setObjectTexture(geometry, AssetsManager.getAssetPathAsFile(getApplicationContext(),
"red.png"));
mAnnotatedGeometriesGroup.setSelectedGeometry(geometry);
}
});
}
final class MyAnnotatedGeometriesGroupCallback extends AnnotatedGeometriesGroupCallback
{
Bitmap mAnnotationBackground, mEmptyStarImage, mFullStarImage;
int mAnnotationBackgroundIndex;
ImageStruct texture;
String[] textureHash = new String[1];
TextPaint mPaint;
Lock geometryLock;
Bitmap inOutCachedBitmaps[] = new Bitmap[] {mAnnotationBackground, mEmptyStarImage, mFullStarImage};
int inOutCachedAnnotationBackgroundIndex[] = new int[] {mAnnotationBackgroundIndex};
public MyAnnotatedGeometriesGroupCallback()
{
mPaint = new TextPaint();
mPaint.setFilterBitmap(true); // enable dithering
mPaint.setAntiAlias(true); // enable anti-aliasing
}
#Override
public IGeometry loadUpdatedAnnotation(IGeometry geometry, Object userData, IGeometry existingAnnotation)
{
if (userData == null)
{
return null;
}
if (existingAnnotation != null)
{
// We don't update the annotation if e.g. distance has changed
return existingAnnotation;
}
String title = (String)userData; // as passed to addGeometry
LLACoordinate location = geometry.getTranslationLLA();
float distance = (float)MetaioCloudUtils.getDistanceBetweenTwoCoordinates(location, mSensors.getLocation());
Bitmap thumbnail = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
try
{
texture =
ARELInterpreterAndroidJava.getAnnotationImageForPOI(title, title, distance, "5", thumbnail,
null,
metaioSDK.getRenderSize(), MainActivity.this,
mPaint, inOutCachedBitmaps, inOutCachedAnnotationBackgroundIndex, textureHash);
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
if (thumbnail != null)
thumbnail.recycle();
thumbnail = null;
}
mAnnotationBackground = inOutCachedBitmaps[0];
mEmptyStarImage = inOutCachedBitmaps[1];
mFullStarImage = inOutCachedBitmaps[2];
mAnnotationBackgroundIndex = inOutCachedAnnotationBackgroundIndex[0];
IGeometry resultGeometry = null;
if (texture != null)
{
if (geometryLock != null)
{
geometryLock.lock();
}
try
{
// Use texture "hash" to ensure that SDK loads new texture if texture changed
resultGeometry = metaioSDK.createGeometryFromImage(textureHash[0], texture, true, false);
}
finally
{
if (geometryLock != null)
{
geometryLock.unlock();
}
}
}
return resultGeometry;
}
#Override
public void onFocusStateChanged(IGeometry geometry, Object userData, EGEOMETRY_FOCUS_STATE oldState,
EGEOMETRY_FOCUS_STATE newState)
{
MetaioDebug.log("onFocusStateChanged for " + (String)userData + ", " + oldState + "->" + newState);
}
}
public class LoadAssets extends AsyncTask<Integer, Integer, Boolean> {
#Override
protected Boolean doInBackground(Integer... params) {
try
{
// Extract all assets and overwrite existing files if debug build
AssetsManager.extractAllAssets(getApplicationContext(), BuildConfig.DEBUG);
}
catch (IOException e)
{
MetaioDebug.log(Log.ERROR, "Error extracting assets: " + e.getMessage());
MetaioDebug.printStackTrace(Log.ERROR, e);
return false;
}
return true;
}
}
}
Somebody knows what is wrong?
if you use skd 5.3 or later you must copy assets/junaio folder of tutorial(example_SDK) into your assets folder so your poi shown.
i've just found it i am working on that right know. my poi.obj rotates...

Categories

Resources