How do I get installing apps package name? - android

I have a list of apk files in SDcard. It shows its' name and icon; everything works fine.
This app shows a list of uninstall apk files which are in Sdcrd, when user install any Apk from this list its' package name will save on database so when user goes to another screen that will show only that application which area install from SD card.
How do I get the name of apk file which the user clicks to install from list?
This is my code:
public class SdcardAPkMgr extends ListActivity {
private List<FileInformation> files_list;
private ProgressDialog mLoadDialog;
private Handler handler;
private static final int SCAN_APK_START = 101;
private static final int SCAN_APK_COMLETED = 102;
private boolean mJustCreate = true;
/** Called when the activity is first created. */
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.apk_list);
files_list = new ArrayList<FileInformation>();
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
setupBatchHandler();
if (mJustCreate) {
thread.start();
}
mJustCreate = false;
}
private void setupBatchHandler() {
// TODO Auto-generated method stub
handler = new Handler() {
// #Override
public void handleMessage(Message msg) {
switch (msg.what) {
case SCAN_APK_START: {
mLoadDialog =
ProgressDialog.show(SdcardAPkMgr.this, "",
getString(R.string.scan_apk_info));
mLoadDialog.setCancelable(false);
break;
}
case SCAN_APK_COMLETED: {
ApkListAdapter adapter = new ApkListAdapter(
SdcardAPkMgr.this, files_list);
SdcardAPkMgr.this.setListAdapter(adapter);
mLoadDialog.dismiss();
break;
}
default:
break;
}
super.handleMessage(msg);
}
};
}
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
handler.sendEmptyMessage(SCAN_APK_START);
getAllApkFiles(new File("/sdcard"));
handler.sendEmptyMessage(SCAN_APK_COMLETED);
}
});
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
FileInformation information = files_list.get(position);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(new File(information.getPath())),
"application/" +
"vnd.android.package-archive");
this.startActivity(intent);
}
public Drawable getAPKDrawable(String filePath) {
Drawable dr = null;
if (filePath != null) {
String PATH_PackageParser = "android.content.pm.PackageParser";
String PATH_AssetManager = "android.content.res.AssetManager";
try {
Class pkgParserCls = Class.forName(PATH_PackageParser);
Class[] typeArgs = new Class[1];
typeArgs[0] = String.class;
Constructor pkgParserCt = pkgParserCls.getConstructor(typeArgs);
Object[] valueArgs = new Object[1];
valueArgs[0] = filePath;
Object pkgParser = pkgParserCt.newInstance(valueArgs);
DisplayMetrics metrics = new DisplayMetrics();
metrics.setToDefaults();
// PackageParser.Package mPkgInfo =
// packageParser.parsePackage(new
// File(apkPath), apkPath,
// metrics, 0);
typeArgs = new Class[4];
typeArgs[0] = File.class;
typeArgs[1] = String.class;
typeArgs[2] = DisplayMetrics.class;
typeArgs[3] = Integer.TYPE;
Method pkgParser_parsePackageMtd = pkgParserCls
.getDeclaredMethod("parsePackage",
typeArgs);
valueArgs = new Object[4];
valueArgs[0] = new File(filePath);
valueArgs[1] = filePath;
valueArgs[2] = metrics;
valueArgs[3] = 0;
Object pkgParserPkg = pkgParser_parsePackageMtd.invoke(
pkgParser, valueArgs);
Field appInfoFld =
pkgParserPkg.getClass().getDeclaredField(
"applicationInfo");
ApplicationInfo info = (ApplicationInfo) appInfoFld
.get(pkgParserPkg);
Class assetMagCls = Class.forName(PATH_AssetManager);
Constructor assetMagCt = assetMagCls
.getConstructor((Class[]) null);
Object assetMag = assetMagCt.newInstance((Object[]) null);
typeArgs = new Class[1];
typeArgs[0] = String.class;
Method assetMag_addAssetPathMtd = assetMagCls
.getDeclaredMethod("addAssetPath", typeArgs);
valueArgs = new Object[1];
valueArgs[0] = filePath;
assetMag_addAssetPathMtd.invoke(assetMag, valueArgs);
Resources res = getResources();
typeArgs = new Class[3];
typeArgs[0] = assetMag.getClass();
typeArgs[1] = res.getDisplayMetrics().getClass();
typeArgs[2] = res.getConfiguration().getClass();
Constructor resCt =
Resources.class.getConstructor(typeArgs);
valueArgs = new Object[3];
valueArgs[0] = assetMag;
valueArgs[1] = res.getDisplayMetrics();
valueArgs[2] = res.getConfiguration();
res = (Resources) resCt.newInstance(valueArgs);
CharSequence label = null;
if (info.labelRes != 0) {
label = res.getText(info.labelRes);
}
if (info.icon != 0) {
dr = res.getDrawable(info.icon);
}
} catch (Exception e) {
e.printStackTrace();
}
}
if (dr == null) {
dr = getResources().getDrawable(R.drawable.default_apk_icon);
}
return dr;
}
private void getAllApkFiles(File root) {
File files[] = root.listFiles();
if (files != null)
for (File f : files) {
if (f.isDirectory()) {
getAllApkFiles(f);
} else {
if (f.getName().indexOf(".apk") > 0) {
// this.list.add(f);
String path = f.toString();
String name =
path.substring(path.lastIndexOf("/") + 1,
path.length());
this.files_list.add(new
FileInformation(name, path,
getAPKDrawable(path)));
}
}
}
}
}

APK is actually a zip file so you can just open it and read the package name from AndroidManifest.xml
Be aware the file is not plain and decoded somehow, but it's there

Related

Adding Progress Bar or Progress Dialogue for sending and receiving file

I have implemented a file sharing project. I am able to Send and Receive File but want to add progress bar or progress dialogue but I have no clue where to add progress bar to it.
Receiver Activity
public class ReceiverActivity extends AppCompatActivity {
FileReceiver fileReceiver;
ImageButton ibt;
private final Handler mHandler = new Handler(Looper.getMainLooper()) {
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
/* case FileReceiver.CODE :
tvCode.setText((int)msg.obj + "");
break;
*/
case FileReceiver.LISTENING :
Toast.makeText(ReceiverActivity.this,"Listening...",Toast.LENGTH_SHORT).show();
break;
case FileReceiver.CONNECTED:
Toast.makeText(ReceiverActivity.this,"Connected!",Toast.LENGTH_SHORT).show();
break;
case FileReceiver.RECEIVING_FILE :
Toast.makeText(ReceiverActivity.this,"Receiving File!",Toast.LENGTH_SHORT).show();
break;
case FileReceiver.FILE_RECEIVED :
File file = (File) msg.obj;
Toast.makeText(ReceiverActivity.this,file.getName() + " Received!",Toast.LENGTH_SHORT).show();
Toast.makeText(ReceiverActivity.this,"Stored in " + file.getAbsolutePath(),Toast.LENGTH_SHORT).show();
fileReceiver.close();
break;
case FileReceiver.RECEIVE_ERROR :
Toast.makeText(ReceiverActivity.this,"Error occured : " + (String)msg.obj,Toast.LENGTH_SHORT).show();
fileReceiver.close();
break;
}
}
};
public void getFile(View view) {
fileReceiver = new FileReceiver(this,mHandler);
fileReceiver.getFile();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_receiver);
ibt= (ImageButton) findViewById(R.id.imgbtn);
ibt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(ReceiverActivity.this, Selection_Activity.class);
startActivity(i);
}
});
}
}
Receiver Thread
public class ReceiverThread extends Thread {
private int port;
private Messenger messenger;
private ServerSocket listenerSocket;
private Socket communicationSocket;
private int PKT_SIZE = 60*1024;
ProgressDialog dialog;
public ReceiverThread(int port,Messenger messenger){
//
this.port = port;
this.messenger = messenger;
File folder = new File(Environment.getExternalStorageDirectory() + "/FileSharer/");
folder.mkdirs();
}
#Override
public void run() {
Message message;
try {
listenerSocket = new ServerSocket(port);
message = Message.obtain();
message.what = FileReceiver.CODE;
message.obj = port;
messenger.send(message);
message = Message.obtain();
message.what = FileReceiver.LISTENING;
message.obj = "";
messenger.send(message);
communicationSocket = listenerSocket.accept();
message = Message.obtain();
message.what = FileReceiver.CONNECTED;
message.obj = "";
messenger.send(message);
DataInputStream in = new DataInputStream(communicationSocket.getInputStream());
message = Message.obtain();
message.what = FileReceiver.RECEIVING_FILE;
message.obj = "";
messenger.send(message);
// Read File Name and create Output Stream
String fileName = in.readUTF();
File receiveFile = new File(Environment.getExternalStorageDirectory() + "/FileSharer/" + fileName);
DataOutputStream dout = new DataOutputStream(new FileOutputStream(receiveFile,true));
// Read File Size
long fileSize = in.readLong();
int totalLength = 0;
int length = 0;
byte[] receiveData = new byte[PKT_SIZE];
long startTime = System.currentTimeMillis();
// Get the file data
while( fileSize>0 && ( ( length = in.read( receiveData,0,(int) Math.min(receiveData.length,fileSize) ))!= -1) )
{
dout.write(receiveData, 0, length);
totalLength += length;
fileSize -= length;
}
long stopTime = System.currentTimeMillis();
dout.close();
double time = (stopTime - startTime) / 1000.0;
double speed = (totalLength / time) / 1048576.0;
message = Message.obtain();
message.what = FileReceiver.FILE_RECEIVED;
message.obj = receiveFile;
messenger.send(message);
} catch (Exception e){
e.printStackTrace();
message = Message.obtain();
message.what = FileReceiver.RECEIVE_ERROR;
message.obj = e.toString();
try {
messenger.send(message);
} catch (RemoteException re) {
Log.e("ReceiverThread","Error in sending an error message! Error : " + re.toString());
re.printStackTrace();
}
} finally {
try {
if(communicationSocket!=null)
communicationSocket.close();
if(listenerSocket!=null)
listenerSocket.close();
} catch (IOException ioe) {
Log.e("ReceiverThread","Error in closing sockets. Error : " + ioe.toString());
ioe.printStackTrace();
}
}
}
}
Receiver Service
public class ReceiverService extends Service {
private final String PORT = "PORT";
private final String MESSENGER = "MESSENGER";
private int port;
private Messenger messenger;
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Bundle b = intent.getExtras();
port = (int) b.get(PORT);
messenger = (Messenger) b.get(MESSENGER);
ReceiverThread receiverThread = new ReceiverThread(port,messenger);
receiverThread.start();
return START_REDELIVER_INTENT;
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
File Receiver
public class FileReceiver {
private final boolean mDebug = true;
// private final int MIN_PORT_NUMBER = 1024;
// private final int MAX_PORT_NUMBER = 65536;
private final String PORT = "PORT";
private final String MESSENGER = "MESSENGER";
// Constants start from 2001
public static final int CODE = 2001;
public static final int LISTENING = 2002;
public static final int CONNECTED = 2003;
public static final int RECEIVING_FILE = 2004;
public static final int FILE_RECEIVED = 2005;
public static final int RECEIVE_ERROR = 2006;
private Context context;
private Handler mHandler;
private Intent i;
public FileReceiver(Context context, Handler mHandler) {
this.context = context;
this.mHandler = mHandler;
}
/* private boolean isPortAvailable(int port) {
boolean available;
if (port < MIN_PORT_NUMBER || port > MAX_PORT_NUMBER) {
throw new IllegalArgumentException("Invalid port: " + port);
}
ServerSocket ss = null;
try {
ss = new ServerSocket(port);
ss.setReuseAddress(true);
available = true;
} catch (IOException e) {
available = false;
} finally {
if (ss != null) {
try {
ss.close();
} catch (IOException e) {
}
}
}
return available;
}
*/
private int getRandomPort() {
//int port = 1001;
int port = 40500;
//do{
// port = (int) (MIN_PORT_NUMBER + 1 + Math.floor(Math.random()*(MAX_PORT_NUMBER - MIN_PORT_NUMBER-1)));
if(mDebug)
Log.i("FileReceiver","Trying port : " + port);
// }while(!isPortAvailable(port));
return port;
// return port;
}
public void getFile(){
int port = getRandomPort();
if(mDebug)
Log.i("FileReceiver","Port : " + port);
i = new Intent(context,ReceiverService.class);
i.putExtra(PORT,port);
i.putExtra(MESSENGER,new Messenger(mHandler));
context.startService(i);
}
public void close() {
context.stopService(i);
}
}
You can add a simple ProgressDialog box from your activity.
Something like :
// global variable
ProgressDialog mProgressDialog;
...
...
// inside onCreate
mProgressDialog = new ProgressDialog(ReceiveActivity.this);
mProgressDialog.setCancelable(true);
mProgressDialog.setMessage("Downloading file ..");
...
...
// before file downloads
mProgressDialog.show();
...
...
// when file is downloaded
mProgressDialog.dismiss();
Edit :
In case of the given questions, this can be done as :
// assuming mProgressDialog is already initialised and configured.
case FileReceiver.CONNECTED:
Toast.makeText(ReceiverActivity.this,"Connected!",Toast.LENGTH_SHORT).show();
/******** Show the dialog box *********/
mProgressDialog.show(); // make sure that the file receiving starts immediately
// after the receiver is connected and that it do not
// require any action (like button click) after is connected
break;
case FileReceiver.RECEIVING_FILE :
Toast.makeText(ReceiverActivity.this,"Receiving File!",Toast.LENGTH_SHORT).show();
/******** Dismiss the dialog box *********/
mProgressDialog.dismiss();
break;
case FileReceiver.FILE_RECEIVED :
File file = (File) msg.obj;
Toast.makeText(ReceiverActivity.this,file.getName() + " Received!",Toast.LENGTH_SHORT).show();
Toast.makeText(ReceiverActivity.this,"Stored in " + file.getAbsolutePath(),Toast.LENGTH_SHORT).show();
fileReceiver.close();
/******** Dismiss the dialog box *********/
mProgressDialog.dismiss();
break;
You can also have a dialog box with progress percentage. Have a look into the ProgressDialog documentation.
There are methods like setProgressStyle(int style) with values like STYLE_HORIZONTAL. And then there are incrementProgressBy(int diff) that can be used to get a horizontal bar there.

LocalBroadcastManager sends data more than once

I have a fragment where when a User inputs a link and hits the button, a service is initiated which processes the link and grabs image or videos if there are any on the url...
But my problem is that the same is downloaded more than once like 2 to 3 times..
here is the fragment -
public class FragmentTwo extends Fragment {
FloatingActionButton btn;
EditText et1;
String profilname;
ProgressDialog pd;
private ArrayList<Long> mDownloadIds = new ArrayList<>();
public FragmentTwo() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_two,container, false);
getActivity().registerReceiver(onComplete, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
LocalBroadcastManager.getInstance(getActivity())
.registerReceiver(myReceiver, new IntentFilter(Constants.BROADCAST_ACTION));
FloatingActionButton btn = (FloatingActionButton) rootView.findViewById(R.id.button1);
EditText et1 = (EditText) rootView.findViewById(R.id.editText1);
pd = new ProgressDialog(getActivity());
pd.setMessage("Let us Check");
pd.setIndeterminate(true);
pd.setCancelable(false);
pd.setCanceledOnTouchOutside(false);
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
EditText et1 = (EditText)
getView().findViewById(R.id.editText1);
profilname = et1.getText().toString();
((InputMethodManager) getActivity().getSystemService("input_method")) .hideSoftInputFromWindow(et1.getWindowToken(), 0);
profilname.replace("https://www.instagram.com/","https://instagram.com/");
if (profilname.trim().equals("")){
Toast.makeText(getActivity(), "Link is Blank!", 0)
.show();
}
else if(isNetworkAvailable()){
Toast.makeText(getActivity(), profilname, 0)
.show();
DownloaderService.startActionFoo(getActivity(), profilname);
pd.show();
}
else{
Toast.makeText(getActivity(), "Network Error", 0)
.show();
}
}
});
return rootView;
}
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE );
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
private BroadcastReceiver myReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
ContentValues contentValues = intent.getParcelableExtra(Constants.MEDIA_INFO);
String mediaUrl = contentValues.getAsString(Constants.MEDIA_URL);
String mediaName = contentValues.getAsString(Constants.MEDIA_NAME);
pd.dismiss();
download(mediaUrl, mediaName);
EditText et1 = (EditText)
getView().findViewById(R.id.editText1);
et1.setText("");
}
};
private BroadcastReceiver onComplete = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
long enqueueId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
if (mDownloadIds.contains(enqueueId)) {
/* if (mBtnDownload.getVisibility() == View.VISIBLE) {
mBtnDownload.setVisibility(View.GONE);
}*/
getActivity().getLoaderManager().getLoader(0);
}
}
};
public void onDestroy() {
LocalBroadcastManager.getInstance(getActivity()).unregisterReceiver(myReceiver);
getActivity().unregisterReceiver(onComplete);
super.onDestroy();
}
private void download(String url, String fileName) {
File root = Environment.getExternalStorageDirectory();
File myDir = new File(root + "/MCD/");
myDir.mkdirs();
DownloadManager mDownloadManager = (DownloadManager) getActivity().getSystemService(getActivity().DOWNLOAD_SERVICE);
if (!doesRequestExist(mDownloadManager, url)) {
/* boolean allowedOverMetered = mSettings.getBoolean(PREF_KEY_NETWORK, true);*/
int networkType = NETWORK_WIFI | NETWORK_MOBILE;
/* if (allowedOverMetered) {
networkType = NETWORK_WIFI | NETWORK_MOBILE;
}*/
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
request.setTitle(fileName);
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setDestinationInExternalPublicDir(root + "/MCD/", fileName);
request.setAllowedNetworkTypes(networkType);
long id = mDownloadManager.enqueue(request);
mDownloadIds.add(id);
}
}
private boolean doesRequestExist(DownloadManager downloadManager, String url) {
boolean result = false;
DownloadManager.Query query = new DownloadManager.Query();
query.setFilterByStatus(DownloadManager.STATUS_SUCCESSFUL
| DownloadManager.STATUS_PENDING
| DownloadManager.STATUS_RUNNING);
Cursor cursor = downloadManager.query(query);
while (cursor.moveToNext()) {
int uriIndex = cursor.getColumnIndex(DownloadManager.COLUMN_URI);
String uri = cursor.getString(uriIndex);
if (uri.equals(url)) {
result = true;
break;
}
}
cursor.close();
return result;
}
}
here's the Downloader Service -
public class DownloaderService extends IntentService {
private static final String ACTION_FOO = "com.parrotainment.media.downloader.action.FOO";
private static final String EXTRA_URL = "com.parrotainment.media.downloader.extra.URL";
public DownloaderService() {
super("DownloaderService");
}
public static void startActionFoo(Context context, String url) {
Intent intent = new Intent(context, DownloaderService.class);
intent.setAction(ACTION_FOO);
intent.putExtra(EXTRA_URL, url);
context.startService(intent);
}
#Override
protected void onHandleIntent(Intent intent) {
if (intent != null) {
final String action = intent.getAction();
if (ACTION_FOO.equals(action)) {
final String url = intent.getStringExtra(EXTRA_URL);
handleActionFoo(url);
}
}
}
private void handleActionFoo(String urlStr) {
try {
ContentValues mediaInfo = new ContentValues();
Document doc = Jsoup.connect(urlStr).timeout(5000).get();
Document content = Jsoup.parse(doc.toString());
String videoUrl = content.getElementsByAttributeValue("property","og:video")
.attr("content");
String title = content.getElementsByAttributeValue("property","og:title")
.attr("content").replaceAll("[^a-zA-Z0-9\\u4E00-\\u9FA5\\s]","");
if (!videoUrl.isEmpty()) {
String videoName = title + ".mp4";
mediaInfo.put(Constants.MEDIA_NAME, videoName);
mediaInfo.put(Constants.MEDIA_URL, videoUrl);
} else {
String imgUrl = content.getElementsByAttributeValue("property","og:image").attr("content");
String imgName = title + ".jpg";
mediaInfo.put(Constants.MEDIA_NAME, imgName);
mediaInfo.put(Constants.MEDIA_URL, imgUrl);
}
Intent intent = new Intent(Constants.BROADCAST_ACTION);
intent.putExtra(Constants.MEDIA_INFO, mediaInfo);
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
} catch (IOException e) {
e.printStackTrace();
}
}
}
& the Constants -
public final class Constants {
public static final String BROADCAST_ACTION = "com.parrotainment.media.downloader.BROADCAST";
public static final String MEDIA_INFO = "com.parrotainment.media.downloader.MEDIA_INFO";
public static final String MEDIA_NAME = "com.parrotainment.media.downloader.MEDIA_NAME";
public static final String MEDIA_URL = "com.parrotainment.media.downloader.MEDIA_URL";
}
just checking data in your oReceive may help. like this:
if(intent.getAction() != null && intent.getAction().equals("your_constant_item")){
//
}

Activity Memory Leak reported by LeakCanary - WindowManagerGlobal

There is a memory leak reported by LeakCanary in my Android App. I have Googled and studied for days and cannot find any solution. The leaked object is an instance of Activity called "MakeFire". It seems to be related to android.view.WindowManagerGlobal. Can anyone point out how the leak happened, and how to fix it?
Here is the LeakCanary ScreenCap
Here is the source code of the MakeFire Activity
public class MakeFire extends SharedMethod implements StatusBarFragment.OnFragmentInteractionListener,
DayTimeFragment.OnFragmentInteractionListener, BackButtonFragment.OnFragmentInteractionListener {
private Button firePlough;
private Button bowDrill;
private TextView makeFireWithBowDrillTime;
private TextView requirementTextview;
private Button performButton;
private String selectedButton;
private boolean firePloughOn;
private boolean bowDrillOn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_make_fire);
firePlough = (Button) findViewById(R.id.firePlough);
bowDrill = (Button) findViewById(R.id.bowDrill);
makeFireWithBowDrillTime = (TextView) findViewById(R.id.makeFireWithBowDrillTime);
requirementTextview = (TextView) findViewById(R.id.requirementTextview);
performButton = (Button) findViewById(R.id.performButton);
}
#Override
public void onDestroy() {
super.onDestroy();
RefWatcher refWatcher = MyApplication.getRefWatcher(this);
refWatcher.watch(this);
}
#Override
public void onBackPressed() {
Bundle extra = new Bundle();
extra.putString("classToGoBack", getClass().getName());
Intent intent = new Intent(this, InGameMenu.class);
intent.putExtras(extra);
startActivity(intent);
}
#Override
public void onResume() {
super.onResume();
GameData.useImmersiveModeSticky(this);
}
#Override
public void onStop() {
super.onStop();
try {
//save on the latest save file
FileOutputStream latestSavedGame = openFileOutput("latestSavedGame", Context.MODE_PRIVATE);
ObjectOutputStream latestGameData = new ObjectOutputStream(latestSavedGame);
latestGameData.writeObject(GameData.GDI);
latestSavedGame.close();
} catch (Exception e) {
//TODO - delete it before uploading the app
GameData.GDI.showPlainMsg("sharedMethodProblem!", this);
final StringWriter sw = new StringWriter();
final PrintWriter pw = new PrintWriter(sw, true);
e.printStackTrace(pw);
GameData.GDI.showPlainMsg(sw.getBuffer().toString(), this);
}
boolean savedGameIsFine;
try {
FileInputStream latestSavedGame = openFileInput("latestSavedGame");
ObjectInputStream latestGameData = new ObjectInputStream(latestSavedGame);
savedGameIsFine = (latestGameData.readObject() != null);
latestSavedGame.close();
} catch (Exception e) {
savedGameIsFine = false;
}
if (savedGameIsFine) {
try {
//save on the latest save file
FileOutputStream latestSavedGame = openFileOutput("latestSavedGameBackup", Context.MODE_PRIVATE);
ObjectOutputStream latestGameData = new ObjectOutputStream(latestSavedGame);
latestGameData.writeObject(GameData.GDI);
latestSavedGame.close();
} catch (Exception e) {
}
} else {
}
}
#Override
protected void onStart() {
super.onStart();
updateAllViews();
requirementTextview.setVisibility(View.INVISIBLE);
performButton.setVisibility(View.INVISIBLE);
}
//method for updating all amendable views in the page
private void updateAllViews() {
//visibility of fire plough button
if (GameData.GDI.anyThisInventoryAvailable(GameData.FIRE_PLOUGH) &&
GameData.GDI.anyThisInventoryAvailable(GameData.TINDER) &&
(!GameData.GDI.stormOn || GameData.GDI.currentLocation.campfireWindBlock)
) {
firePlough.setCompoundDrawablesWithIntrinsicBounds(0,R.drawable.ic_fireplow_3_f,0,0);
firePlough.setTextColor(ContextCompat.getColor(this, R.color.buttonOnColour));
firePloughOn = true;
}
else {
firePlough.setCompoundDrawablesWithIntrinsicBounds(0,R.drawable.ic_fireplow_3_f_o,0,0);
firePlough.setTextColor(ContextCompat.getColor(this, R.color.buttonOffColour));
firePloughOn = false;
}
//visibility of bow drill button
if (GameData.GDI.bowDrillUnlocked) {
bowDrill.setVisibility(View.VISIBLE);
makeFireWithBowDrillTime.setVisibility(View.VISIBLE);
if (GameData.GDI.anyThisInventoryAvailable(GameData.BOW_DRILL) &&
GameData.GDI.anyThisInventoryAvailable(GameData.TINDER) &&
(!GameData.GDI.stormOn || GameData.GDI.currentLocation.campfireWindBlock)
) {
bowDrill.setCompoundDrawablesWithIntrinsicBounds(0,R.drawable.ic_bow_drill_3_f,0,0);
bowDrill.setTextColor(ContextCompat.getColor(this, R.color.buttonOnColour));
bowDrillOn = true;
}
else {
bowDrill.setCompoundDrawablesWithIntrinsicBounds(0,R.drawable.ic_bow_drill_3_f_o,0,0);
bowDrill.setTextColor(ContextCompat.getColor(this, R.color.buttonOffColour));
bowDrillOn = false;
}
}
updateStatusBarFragment();
updateDayTimeFragment();
}
public void makeFireWithFirePlough(View view) {
if (firePloughOn) {
performButton.setVisibility(View.VISIBLE);
}
else {
performButton.setVisibility(View.INVISIBLE);
}
requirementTextview.setVisibility(View.VISIBLE);
requirementTextview.setText(R.string.makeFireWithFirePloughRqm);
selectedButton = "fire plough";
}
public void makeFireWithBowDrill(View view) {
if (bowDrillOn) {
performButton.setVisibility(View.VISIBLE);
}
else {
performButton.setVisibility(View.INVISIBLE);
}
requirementTextview.setVisibility(View.VISIBLE);
requirementTextview.setText(R.string.makeFireWithBowDrillRqm);
selectedButton = "bow drill";
}
public void perform(View view){
if (!GameData.GDI.stormOn || GameData.GDI.currentLocation.campfireWindBlock){
switch (selectedButton){
case "fire plough":
String msgToShow = "";
String extraInfo = "";
String[] timePassMsg;
Bundle extras = new Bundle();
//timepass method must run before the fireToLast method
timePassMsg = GameData.GDI.timePass(30, 1, 1, 1, this);
if (GameData.GDI.anyThisInventoryInBackpack(GameData.TINDER)) {
GameData.GDI.setInventoryAmount(GameData.TINDER, true, -1);
}
else {
GameData.GDI.setInventoryAmount(GameData.TINDER, false, -1);
}
extras.putString("toolUsed", getString(R.string.usedTinderMsg));
//update tool durability
GameData.GDI.firePloughDurability = GameData.GDI.updateInventoryDurability(GameData.FIRE_PLOUGH, GameData.GDI.firePloughDurability, GameData.FIRE_PLOUGH_MAX_DURABILITY);
//Because in GameCamp.updateInventoryDurability, if the tool broke, it will reset the durability to its maxDurability;
//so if these 2 numbers equal, the tool just broke
if (GameData.GDI.firePloughDurability == GameData.FIRE_PLOUGH_MAX_DURABILITY) {
extraInfo += getString(R.string.firePloughBreakMsg) + "\n\n";
}
GameData.GDI.bowDrillUnlockCounter += 1;
if (Math.random() < 0.75) {
GameData.GDI.currentLocation.fireOn = true;
GameData.GDI.currentLocation.fireToLast += 10;
msgToShow += getString(R.string.success) + "\n";
extras.putString("className", "Fire");
}
else {
msgToShow += getString(R.string.fail) + "\n";
if (!GameData.GDI.bowDrillUnlocked) {
if (GameData.GDI.bowDrillUnlockCounter >= 3) {
extraInfo += getString(R.string.bowDrillUnlockMsg) + "\n\n";
GameData.GDI.bowDrillUnlocked = true;
GameData.GDI.setCraftingAlertIcon(3);
}
}
extras.putString("className", "Make Fire");
}
Intent intent = new Intent(this, LoadingPage.class);
extras.putString("actionName", getString(R.string.makingFireWithFirePlough));
extras.putInt("timeNeeded", 30);
extras.putString("msgToShow", msgToShow);
extras.putString("extraInfo", extraInfo);
extras.putString("timePassMsg", timePassMsg[0]);
extras.putString("deathReason", timePassMsg[1]);
intent.putExtras(extras);
startActivity(intent);
break;
case "bow drill":
String msgToShow1 = "";
String extraInfo1 = "";
String[] timePassMsg1;
Bundle extras1 = new Bundle();
//timepass method must run before the fireToLast method
timePassMsg1 = GameData.GDI.timePass(10, 1, 1, 1, this);
if (GameData.GDI.anyThisInventoryInBackpack(GameData.TINDER)) {
GameData.GDI.setInventoryAmount(GameData.TINDER, true, -1);
}
else {
GameData.GDI.setInventoryAmount(GameData.TINDER, false, -1);
}
extras1.putString("toolUsed", getString(R.string.usedTinderMsg));
//update tool durability
GameData.GDI.bowDrillDurability = GameData.GDI.updateInventoryDurability(GameData.BOW_DRILL, GameData.GDI.bowDrillDurability, GameData.BOW_DRILL_MAX_DURABILITY);
//Because in GameCamp.updateInventoryDurability, if the tool broke, it will reset the durability to its maxDurability;
//so if these 2 numbers equal, the tool just broke
if (GameData.GDI.bowDrillDurability == GameData.BOW_DRILL_MAX_DURABILITY) {
extraInfo1 += getString(R.string.bowDrillBreakMsg) + "\n\n";
}
if (Math.random() < 0.95) {
GameData.GDI.currentLocation.fireOn = true;
GameData.GDI.currentLocation.fireToLast += 10;
msgToShow1 += getString(R.string.success) + "\n";
extras1.putString("className", "Fire");
}
else {
msgToShow1 += getString(R.string.fail) + "\n";
extras1.putString("className", "Make Fire");
}
Intent intent1 = new Intent(this, LoadingPage.class);
extras1.putString("actionName", getString(R.string.makingFireWithBowDrill));
extras1.putString("className", "Fire");
extras1.putInt("timeNeeded", 10);
extras1.putString("msgToShow", msgToShow1);
extras1.putString("extraInfo", extraInfo1);
extras1.putString("timePassMsg", timePassMsg1[0]);
extras1.putString("deathReason", timePassMsg1[1]);
intent1.putExtras(extras1);
startActivity(intent1);
break;
}
}
else {
GameData.GDI.showPlainMsg(getString(R.string.cannotMakeFireInStormMsg), this);
}
}
//fragment method
public void updateStatusBarFragment() {
StatusBarFragment statusBarFragment = (StatusBarFragment)getSupportFragmentManager().findFragmentById(R.id.statusBarFragment);
statusBarFragment.updateStatusBar();
}
public void updateDayTimeFragment() {
DayTimeFragment dayTimeFragment = (DayTimeFragment)getSupportFragmentManager().findFragmentById(R.id.dayTimeFragment);
dayTimeFragment.updateDayTimeView();
}
public void backButton(View view){
Intent intent = new Intent(this, Fire.class);
startActivity(intent);
}
}

Reinstalling app does not bring over all the changes of released app android

I have a project that is re-installing a new version of an old app and I use a custom self installer to install the app. I am seeing some strange behavior with the re-install. When the app downloads the released version of the app, not all of the latest changes come with it. It's installing a release from several days ago. Not sure why this is happening.
I am thinking that I need to completely delete and reinstall the app in my self installer program.
Here is the code for the self installer:
public class AsyncActivity extends Activity {
public static int taskID;
Intent keepInApp;
private boolean messageShowing = false;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
lblUpdating = (TextView)findViewById(R.id.lblUpdating);
taskID = getTaskId();
keepInApp = new Intent(this.getApplicationContext(), ServiceKeepInApp.class);
Bundle bundle = getIntent().getExtras();
if (bundle != null) {
thepackageName = bundle.getString(GlobalVars.keyPackageName);
GlobalVars.KeyPackageName = thepackageName;
urlPath = bundle.getString(GlobalVars.keyFTPPath);
GlobalVars.KeyFTPPath = urlPath;
downloadPath = bundle.getString(GlobalVars.keyDownloadLocation);
GlobalVars.deviceDownloadPath = downloadPath;
user = bundle.getString(GlobalVars.keyFTPUser);
GlobalVars.FTPUser = user;
pw = bundle.getString(GlobalVars.keyFTPPassword);
GlobalVars.FTPPassword = pw;
apkName = bundle.getString(GlobalVars.keyFileName);
GlobalVars.APKName = apkName;
serverVersion = bundle.getString(GlobalVars.keyServerVersion);
GlobalVars.ServerVersion = serverVersion;
if (bundle.getString(GlobalVars.keyScreenText) != null) {
lblUpdating.setText(Html.fromHtml(bundle.getString(GlobalVars.keyScreenText)));
}
if (bundle.getString(GlobalVars.keyFont) != null) {
if (!bundle.getString(GlobalVars.keyFont).equalsIgnoreCase("")) {
Typeface typeFace = Typeface.createFromAsset(getAssets(), "fonts/" + bundle.getString(GlobalVars.keyFont));
lblUpdating.setTypeface(typeFace);
}
}
if (StringUtils.isBlank(urlPath) || StringUtils.isBlank(downloadPath) || StringUtils.isBlank(user) || StringUtils.isBlank(pw)
|| StringUtils.isBlank(apkName) || StringUtils.isBlank(thepackageName)) {
stopService(keepInApp);
finish();
android.os.Process.killProcess(android.os.Process.myPid());
} else {
startService(keepInApp);
}
}
try {
int position = urlPath.lastIndexOf(".");
ftpServerName = urlPath.substring(0, position + 4); // +4 so we get .com
ftpUpdatePath = urlPath.substring(position + 4); // +4 so we don't get .copm
boolean downloadAPK = true;
try {
File apk = new File(downloadPath, apkName);
if (apk != null) {
try {
PackageManager pm = getPackageManager();
PackageInfo pi = pm.getPackageArchiveInfo(downloadPath + apkName, 0);
pi.applicationInfo.sourceDir = downloadPath + apkName;
pi.applicationInfo.publicSourceDir = downloadPath + apkName;
if (Double.valueOf(pi.versionName).equals(Double.valueOf(serverVersion))) {
downloadAPK = false;
InstallApplication(thepackageName, apkName, downloadPath);
}
} catch (Exception e) {
e.printStackTrace();
}
}
} catch (Exception e) {
downloadAPK = false;
ProgressTask task = (ProgressTask)new ProgressTask(this);
task.execute(user, pw, ftpServerName, ftpUpdatePath, downloadPath, apkName, thepackageName);
e.printStackTrace();
}
if (downloadAPK) {
ProgressTask task = (ProgressTask)new ProgressTask(this);
task.execute(user, pw, ftpServerName, ftpUpdatePath, downloadPath, apkName, thepackageName);
}
} catch (Exception e) {
stopService(keepInApp);
finish();
android.os.Process.killProcess(android.os.Process.myPid());
e.printStackTrace();
}
}
public void InstallApplication(String packageName, String apkName, String installPath) {
setIsMessageShowing(true);
Uri packageURI = Uri.parse(packageName);
// Intent intent = new Intent(android.content.Intent.ACTION_VIEW, packageURI);
Intent intent = new Intent(android.content.Intent.ACTION_VIEW, packageURI);
/*
* Right here, we should be able to change the relative file-pathing to
* wherever we choose to download the apk to.
*/
intent.setDataAndType(Uri.fromFile(new File(installPath.toString() + apkName.toString())), "application/vnd.android.package-archive");
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
And for the service:
public class ServiceKeepInApp extends Service {
private boolean sendHandler = false;
Handler taskHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
ActivityManager activityManager = (ActivityManager)getSystemService(Service.ACTIVITY_SERVICE);
if (activityManager.getRecentTasks(2, 0).get(0).id != AsyncActivity.taskID) {
Intent intent = new Intent(Intent.ACTION_MAIN);
Context mycon = getApplicationContext();
PackageManager manager = mycon.getApplicationContext().getPackageManager();
intent = manager.getLaunchIntentForPackage(mycon.getPackageName());
intent.addCategory(Intent.CATEGORY_LAUNCHER);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("keyFTPPath", GlobalVars.FTPPath);
intent.putExtra("keyDownloadLocation", GlobalVars.deviceDownloadPath);
intent.putExtra("keyFTPUser", GlobalVars.FTPUser);
intent.putExtra("keyFTPPassword", GlobalVars.FTPPassword);
intent.putExtra("keyFileName", GlobalVars.APKName);
intent.putExtra("keyPackageName", GlobalVars.KeyPackageName);
intent.putExtra(GlobalVars.keyServerVersion, GlobalVars.ServerVersion);
mycon.startActivity(intent);
}
if (sendHandler) {
taskHandler.sendEmptyMessageDelayed(0, 1000);
}
}
};
#Override
public void onCreate() {
Log.v("Service", "created");
super.onCreate();
sendHandler = true;
taskHandler.sendEmptyMessage(0);
}
and for the AsyncTask that downloads the software:
class ProgressTask extends AsyncTask<String, Void, Boolean> {
List<Message> titles;
private FTPClient mFTPClient = null;
ProgressTask(Context asyncActivity) {
context = asyncActivity;
}
/** progress dialog to show user that the backup is processing. */
/** application context. */
private Context context;
protected Boolean doInBackground(final String... args) {
Boolean status = null;
try {
status = ftpConnect(args[2], args[0], args[1], 21);
if (status) {
File destinationPath = new File(args[4]);
if (!destinationPath.exists()) {
destinationPath.mkdirs();
}
File fromFile = new File(args[3] + args[5]);
File toFile = new File(args[4] + "/" + args[5]);
if (toFile.exists()) {
toFile.delete();
}
status = ftpDownload(fromFile.toString(), toFile.toString());
mFTPClient.logout();
mFTPClient.disconnect();
InstallApplication(args[6], args[5], args[4]);
}
return status;
} catch (Exception e) {
e.printStackTrace();
return status;
}
}
Why would a previous version of the software stay on the app after reinstall? Could I delete the old package with code like:
public void unInstallApp(String packageName) {
Uri packageURI = Uri.parse(packageName.toString());
Intent uninstallIntent = new Intent(Intent.ACTION_DELETE, packageURI);
context.startActivity(uninstallIntent);
}
File was not being overwritten, so this is why the release version didn't update.

An error occured during retrieval of video in you tube

I am making an app in whic h i hava to you stream you tube video and show in my app but i am getting error message an error occured during retrieval of video.My code snippet is as follows:
public class Rads extends Activity {
public static final String SCHEME_YOUTUBE_VIDEO = "ytv";
public static final String SCHEME_YOUTUBE_PLAYLIST = "ytpl";
static final String YOUTUBE_VIDEO_INFORMATION_URL = "http://www.youtube.com/get_video_info?&video_id=";
static final String YOUTUBE_PLAYLIST_ATOM_FEED_URL = "http://gdata.youtube.com/feeds/api/playlists/";
protected ProgressBar mProgressBar;
protected TextView mProgressMessage;
protected VideoView mVideoView;
public final static String MSG_INIT = "com.keyes.video.msg.init";
protected String mMsgInit = "Initializing";
public final static String MSG_DETECT = "com.keyes.video.msg.detect";
protected String mMsgDetect = "Detecting Bandwidth";
public final static String MSG_PLAYLIST = "com.keyes.video.msg.playlist";
protected String mMsgPlaylist = "Determining Latest Video in YouTube Playlist";
public final static String MSG_TOKEN = "com.keyes.video.msg.token";
protected String mMsgToken = "Retrieving YouTube Video Token";
public final static String MSG_LO_BAND = "com.keyes.video.msg.loband";
protected String mMsgLowBand = "Buffering Low-bandwidth Video";
public final static String MSG_HI_BAND = "com.keyes.video.msg.hiband";
protected String mMsgHiBand = "Buffering High-bandwidth Video";
public final static String MSG_ERROR_TITLE = "com.keyes.video.msg.error.title";
protected String mMsgErrorTitle = "Communications Error";
public final static String MSG_ERROR_MSG = "com.keyes.video.msg.error.msg";
protected String mMsgError = "An error occurred during the retrieval of the video. This could be due to network issues or YouTube protocols. Please try again later.";
/** Background task on which all of the interaction with YouTube is done */
protected QueryYouTubeTask mQueryYouTubeTask;
protected String mVideoId = null;
#Override
protected void onCreate(Bundle pSavedInstanceState) {
super.onCreate(pSavedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
// create the layout of the view
setupView();
// determine the messages to be displayed as the view loads the video
extractMessages();
// set the flag to keep the screen ON so that the video can play without the screen being turned off
getWindow().setFlags(android.view.WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, android.view.WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
mProgressBar.bringToFront();
mProgressBar.setVisibility(View.VISIBLE);
mProgressMessage.setText(mMsgInit);
// extract the playlist or video id from the intent that started this video
Uri lVideoIdUri = this.getIntent().getData();
if(lVideoIdUri == null){
Log.i(this.getClass().getSimpleName(), "No video ID was specified in the intent. Closing video activity.");
finish();
}
String lVideoSchemeStr = lVideoIdUri.getScheme();
String lVideoIdStr = lVideoIdUri.getEncodedSchemeSpecificPart();
if(lVideoIdStr == null){
Log.i(this.getClass().getSimpleName(), "No video ID was specified in the intent. Closing video activity.");
finish();
}
if(lVideoIdStr.startsWith("//")){
if(lVideoIdStr.length() > 2){
lVideoIdStr = lVideoIdStr.substring(2);
} else {
Log.i(this.getClass().getSimpleName(), "No video ID was specified in the intent. Closing video activity.");
finish();
}
}
///////////////////
// extract either a video id or a playlist id, depending on the uri scheme
YouTubeId lYouTubeId = null;
if(lVideoSchemeStr != null && lVideoSchemeStr.equalsIgnoreCase(SCHEME_YOUTUBE_PLAYLIST)){
lYouTubeId = new PlaylistId(lVideoIdStr);
}
else if(lVideoSchemeStr != null && lVideoSchemeStr.equalsIgnoreCase(SCHEME_YOUTUBE_VIDEO)){
lYouTubeId = new VideoId(lVideoIdStr);
}
if(lYouTubeId == null){
Log.i(this.getClass().getSimpleName(), "Unable to extract video ID from the intent. Closing video activity.");
finish();
}
mQueryYouTubeTask = (QueryYouTubeTask) new QueryYouTubeTask().execute(lYouTubeId);
}
/**
* Determine the messages to display during video load and initialization.
*/
private void extractMessages() {
Intent lInvokingIntent = getIntent();
String lMsgInit = lInvokingIntent.getStringExtra(MSG_INIT);
if(lMsgInit != null){
mMsgInit = lMsgInit;
}
String lMsgDetect = lInvokingIntent.getStringExtra(MSG_DETECT);
if(lMsgDetect != null){
mMsgDetect = lMsgDetect;
}
String lMsgPlaylist = lInvokingIntent.getStringExtra(MSG_PLAYLIST);
if(lMsgPlaylist != null){
mMsgPlaylist = lMsgPlaylist;
}
String lMsgToken = lInvokingIntent.getStringExtra(MSG_TOKEN);
if(lMsgToken != null){
mMsgToken = lMsgToken;
}
String lMsgLoBand = lInvokingIntent.getStringExtra(MSG_LO_BAND);
if(lMsgLoBand != null){
mMsgLowBand = lMsgLoBand;
}
String lMsgHiBand = lInvokingIntent.getStringExtra(MSG_HI_BAND);
if(lMsgHiBand != null){
mMsgHiBand = lMsgHiBand;
}
String lMsgErrTitle = lInvokingIntent.getStringExtra(MSG_ERROR_TITLE);
if(lMsgErrTitle != null){
mMsgErrorTitle = lMsgErrTitle;
}
String lMsgErrMsg = lInvokingIntent.getStringExtra(MSG_ERROR_MSG);
if(lMsgErrMsg != null){
mMsgError = lMsgErrMsg;
}
}
/**
* Create the view in which the video will be rendered.
*/
private void setupView() {
LinearLayout lLinLayout = new LinearLayout(this);
lLinLayout.setId(1);
lLinLayout.setOrientation(LinearLayout.VERTICAL);
lLinLayout.setGravity(Gravity.CENTER);
lLinLayout.setBackgroundColor(Color.BLACK);
LayoutParams lLinLayoutParms = new LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT);
lLinLayout.setLayoutParams(lLinLayoutParms);
this.setContentView(lLinLayout);
RelativeLayout lRelLayout = new RelativeLayout(this);
lRelLayout.setId(2);
lRelLayout.setGravity(Gravity.CENTER);
lRelLayout.setBackgroundColor(Color.BLACK);
android.widget.RelativeLayout.LayoutParams lRelLayoutParms = new android.widget.RelativeLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT);
lRelLayout.setLayoutParams(lRelLayoutParms);
lLinLayout.addView(lRelLayout);
mVideoView = new VideoView(this);
mVideoView.setId(3);
android.widget.RelativeLayout.LayoutParams lVidViewLayoutParams = new android.widget.RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
lVidViewLayoutParams.addRule(RelativeLayout.CENTER_IN_PARENT);
mVideoView.setLayoutParams(lVidViewLayoutParams);
lRelLayout.addView(mVideoView);
mProgressBar = new ProgressBar(this);
mProgressBar.setIndeterminate(true);
mProgressBar.setVisibility(View.VISIBLE);
mProgressBar.setEnabled(true);
mProgressBar.setId(4);
android.widget.RelativeLayout.LayoutParams lProgressBarLayoutParms = new android.widget.RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
lProgressBarLayoutParms.addRule(RelativeLayout.CENTER_IN_PARENT);
mProgressBar.setLayoutParams(lProgressBarLayoutParms);
lRelLayout.addView(mProgressBar);
mProgressMessage = new TextView(this);
mProgressMessage.setId(5);
android.widget.RelativeLayout.LayoutParams lProgressMsgLayoutParms = new android.widget.RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
lProgressMsgLayoutParms.addRule(RelativeLayout.CENTER_HORIZONTAL);
lProgressMsgLayoutParms.addRule(RelativeLayout.BELOW, 4);
mProgressMessage.setLayoutParams(lProgressMsgLayoutParms);
mProgressMessage.setTextColor(Color.LTGRAY);
mProgressMessage.setTextSize(TypedValue.COMPLEX_UNIT_SP, 12);
mProgressMessage.setText("...");
lRelLayout.addView(mProgressMessage);
}
#Override
protected void onDestroy() {
super.onDestroy();
YouTubeUtility.markVideoAsViewed(this, mVideoId);
if(mQueryYouTubeTask != null){
mQueryYouTubeTask.cancel(true);
}
if(mVideoView != null){
mVideoView.stopPlayback();
}
// clear the flag that keeps the screen ON
getWindow().clearFlags(android.view.WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
this.mQueryYouTubeTask = null;
this.mVideoView = null;
}
public void updateProgress(String pProgressMsg){
try {
mProgressMessage.setText(pProgressMsg);
} catch(Exception e) {
Log.e(this.getClass().getSimpleName(), "Error updating video status!", e);
}
}
private class ProgressUpdateInfo {
public String mMsg;
public ProgressUpdateInfo(String pMsg){
mMsg = pMsg;
}
}
/**
* Task to figure out details by calling out to YouTube GData API. We only use public methods that
* don't require authentication.
*
*/
private class QueryYouTubeTask extends AsyncTask<YouTubeId, ProgressUpdateInfo, Uri> {
private boolean mShowedError = false;
#Override
protected Uri doInBackground(YouTubeId... pParams) {
String lUriStr = null;
String lYouTubeFmtQuality = "17"; // 3gpp medium quality, which should be fast enough to view over EDGE connection
String lYouTubeVideoId = null;
if(isCancelled())
return null;
try {
publishProgress(new ProgressUpdateInfo(mMsgDetect));
WifiManager lWifiManager = (WifiManager) Rads.this.getSystemService(Context.WIFI_SERVICE);
TelephonyManager lTelephonyManager = (TelephonyManager) Rads.this.getSystemService(Context.TELEPHONY_SERVICE);
////////////////////////////
// if we have a fast connection (wifi or 3g), then we'll get a high quality YouTube video
if( (lWifiManager.isWifiEnabled() && lWifiManager.getConnectionInfo() != null && lWifiManager.getConnectionInfo().getIpAddress() != 0) ||
( (lTelephonyManager.getNetworkType() == TelephonyManager.NETWORK_TYPE_UMTS ||
/* icky... using literals to make backwards compatible with 1.5 and 1.6 */
lTelephonyManager.getNetworkType() == 9 /*HSUPA*/ ||
lTelephonyManager.getNetworkType() == 10 /*HSPA*/ ||
lTelephonyManager.getNetworkType() == 8 /*HSDPA*/ ||
lTelephonyManager.getNetworkType() == 5 /*EVDO_0*/ ||
lTelephonyManager.getNetworkType() == 6 /*EVDO A*/)
&& lTelephonyManager.getDataState() == TelephonyManager.DATA_CONNECTED)
){
lYouTubeFmtQuality = "18";
}
///////////////////////////////////
// if the intent is to show a playlist, get the latest video id from the playlist, otherwise the video
// id was explicitly declared.
if(pParams[0] instanceof PlaylistId){
publishProgress(new ProgressUpdateInfo(mMsgPlaylist));
lYouTubeVideoId = YouTubeUtility.queryLatestPlaylistVideo((PlaylistId) pParams[0]);
}
else if(pParams[0] instanceof VideoId){
lYouTubeVideoId = pParams[0].getId();
}
mVideoId = lYouTubeVideoId;
publishProgress(new ProgressUpdateInfo(mMsgToken));
if(isCancelled())
return null;
////////////////////////////////////
// calculate the actual URL of the video, encoded with proper YouTube token
lUriStr = YouTubeUtility.calculateYouTubeUrl(lYouTubeFmtQuality, true, lYouTubeVideoId);
if(isCancelled())
return null;
if(lYouTubeFmtQuality.equals("17")){
publishProgress(new ProgressUpdateInfo(mMsgLowBand));
} else {
publishProgress(new ProgressUpdateInfo(mMsgHiBand));
}
} catch(Exception e) {
Log.e(this.getClass().getSimpleName(), "Error occurred while retrieving information from YouTube.", e);
}
if(lUriStr != null){
return Uri.parse(lUriStr);
} else {
return null;
}
}
#Override
protected void onPostExecute(Uri pResult) {
super.onPostExecute(pResult);
try {
if(isCancelled())
return;
if(pResult == null){
throw new RuntimeException("Invalid NULL Url.");
}
mVideoView.setVideoURI(pResult);
if(isCancelled())
return;
// TODO: add listeners for finish of video
mVideoView.setOnCompletionListener(new OnCompletionListener(){
public void onCompletion(MediaPlayer pMp) {
if(isCancelled())
return;
Rads.this.finish();
}
});
if(isCancelled())
return;
final MediaController lMediaController = new MediaController(Rads.this);
mVideoView.setMediaController(lMediaController);
lMediaController.show(0);
//mVideoView.setKeepScreenOn(true);
mVideoView.setOnPreparedListener( new MediaPlayer.OnPreparedListener() {
public void onPrepared(MediaPlayer pMp) {
if(isCancelled())
return;
Rads.this.mProgressBar.setVisibility(View.GONE);
Rads.this.mProgressMessage.setVisibility(View.GONE);
}
});
if(isCancelled())
return;
mVideoView.requestFocus();
mVideoView.start();
} catch(Exception e){
Log.e(this.getClass().getSimpleName(), "Error playing video!", e);
if(!mShowedError){
showErrorAlert();
}
}
}
private void showErrorAlert() {
try {
Builder lBuilder = new AlertDialog.Builder(Rads.this);
lBuilder.setTitle(mMsgErrorTitle);
lBuilder.setCancelable(false);
lBuilder.setMessage(mMsgError);
lBuilder.setPositiveButton("OK", new DialogInterface.OnClickListener(){
public void onClick(DialogInterface pDialog, int pWhich) {
Rads.this.finish();
}
});
AlertDialog lDialog = lBuilder.create();
lDialog.show();
} catch(Exception e){
Log.e(this.getClass().getSimpleName(), "Problem showing error dialog.", e);
}
}
#Override
protected void onProgressUpdate(ProgressUpdateInfo... pValues) {
super.onProgressUpdate(pValues);
Rads.this.updateProgress(pValues[0].mMsg);
}
}
#Override
protected void onStart() {
super.onStart();
}
#Override
protected void onStop() {
super.onStop();
}
}

Categories

Resources