stranges with android mediaservice - Android Q&A, Help & Troubleshooting

I've got nexus 4 and have some issue with media servicem cause my MS could not find music on my internal SD card; So I make an app;
Code:
public class SingleMediaScanner implements MediaScannerConnectionClient {
private MediaScannerConnection mMs;
private File mFile;
public SingleMediaScanner(Context context, File f) {
mFile = f;
mMs = new MediaScannerConnection(context, this);
mMs.connect();
}
[user=439709]@override[/user]
public void onMediaScannerConnected() {
Log.v("MS", "connected");
mMs.scanFile(mFile.getAbsolutePath(), "audio/*");
Log.v("MS-file", mFile.getAbsolutePath());
}
[user=439709]@override[/user]
public void onScanCompleted(String path, Uri uri) {
mMs.disconnect();
}
}
Code:
File root = android.os.Environment.getExternalStorageDirectory();
File dir = new File (root.getAbsolutePath()+"/Music/");
for (int i=0;i<dir.listFiles().length;i++)
{
if (dir.listFiles()[i].isFile()==true&&dir.listFiles()[i].getName().endsWith(".mp3"))
{
new SingleMediaScanner(this, dir.listFiles()[i].getAbsoluteFile());
}
Log says that MS was connected and tried to scan media file, but file doesnt appear in Media library , what's the problem? by the way I have CM ROM

Related

[Q] Problem with JSR 179 (Localization API) [WM] [GPS]

Hello.
I'm trying to write a program in J2ME on WM 6.5 (concrete HTC Leo) to locate the position using internal GPS receiver. The problem is that WM does not support JSR 179 Java package corresponding to the location API. Do you know maybe some way to attach the package to the environment WM (JBlend Java emulator). If not, is there some other way to communicate with the built-in GPS in J2ME?
It may be a simpler way to write a program in C #. Unfortunately, I haven't experience in C #. What library to use to get to the GPS?
Below is a basic code that I use to read longitude and latitude from a GPS receiver. It works for sure with the Nokia 5230, but probably also with other devices based on Symbian, as this is included in the package JSR 179.
Code:
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;
import javax.microedition.location.*;
public class GPS_Speedometer extends MIDlet implements CommandListener {
private Form mMainForm;
private StringItem message;
public GPS_Speedometer() {
message = new StringItem("","");
Retriever ret = new Retriever(this);
ret.start();
mMainForm = new Form("GPS Speedometer");
mMainForm.append(new StringItem(null, "GPS Speedometer!\n"));
mMainForm.append(message);
mMainForm.addCommand(new Command("Exit", Command.EXIT, 0));
mMainForm.setCommandListener(this);
}
public void startApp() {
Display.getDisplay(this).setCurrent(mMainForm);
}
public void pauseApp() {}
public void destroyApp(boolean unconditional) {}
public void commandAction(Command c, Displayable s) {
notifyDestroyed();
}
public void displayString(String string) {
message.setText(string);
}
class Retriever extends Thread {
private GPS_Speedometer midlet;
public Retriever(GPS_Speedometer midlet) {
this.midlet = midlet;
}
public void run() {
try
{
while (true){
checkLocation();
Thread.sleep(5000);
}
}
catch (Exception ex)
{
ex.printStackTrace();
midlet.displayString(ex.toString());
}
}
public void checkLocation() throws Exception {
String string;
Location location;
LocationProvider location_provider;
Coordinates c;
Criteria cr = new Criteria();
cr.setHorizontalAccuracy(500);
location_provider = LocationProvider.getInstance(cr);
location = location_provider.getLocation(60);
c = location.getQualifiedCoordinates();
if(c != null ) {
double lat = c.getLatitude();
double lon = c.getLongitude();
double alt = c.getAltitude();
string = "\nLatitude: " + lat + "\nLongitude: " + lon + "\nAltitude: " + alt;
} else {
string ="Localization API failed.";
}
midlet.displayString(string);
}
}
}
I will be grateful for any help and suggestions.

[HELP] Adding a Toast message to Decompress activity

Hi everyone,
I am currently working on my first app which grabs a ZIP from the internet and the extracts it to a certain location. Everything works great but I can not figure out how to show a Toast message when the extraction operation is done.
The code I am using for unzipping is:
Code:
package mmarin.test.download;
import android.util.Log;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
/**
*
* @author jon
*/
public class Decompress{
private String _zipFile;
private String _location;
byte[] buffer = new byte[1024];
int length;
public Decompress(String zipFile, String location) {
_zipFile = zipFile;
_location = location;
_dirChecker("");
}
public void unzip() {
try {
FileInputStream fin = new FileInputStream(_zipFile);
ZipInputStream zin = new ZipInputStream(fin);
ZipEntry ze = null;
while ((ze = zin.getNextEntry()) != null) {
Log.v("Decompress", "Unzipping " + ze.getName());
if(ze.isDirectory()) {
_dirChecker(ze.getName());
} else {
FileOutputStream fout = new FileOutputStream(_location + ze.getName());
while ((length = zin.read(buffer))>0) {
fout.write(buffer, 0, length);
}
zin.closeEntry();
fout.close();
}
}
zin.close();
} catch(Exception e) {
Log.e("Decompress", "unzip", e);
}
}
private void _dirChecker(String dir) {
File f = new File(_location + dir);
if(!f.isDirectory()) {
f.mkdirs();
}
}
}
I am calling the Decompress activity through a button:
Code:
Button decompress = (Button)findViewById(R.id.button1);
decompress.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
String zipFile = Environment.getExternalStorageDirectory() + "/IPM/Splash.zip";
String unzipLocation = Environment.getExternalStorageDirectory() + "/IPM/Splash/";
Decompress d = new Decompress(zipFile, unzipLocation);
d.unzip();
}
});
I found this here: http://www.jondev.net/articles/Unzipping_Files_with_Android_(Programmatically) and it works great.
As I said above, only issue is displaying a message that everything is done.
Can someone please help me out?
Thank you!
Please use the Q&A Forum for questions &
Read the Forum Rules Ref Posting
Moving to Q&A
Put the toast after zin.close()
www.stackoverflow.com
Here you can find what you want
Xperian using xda app
http://stackoverflow.com/questions/9824772/toast-after-email-intent-message
Check this
Xperian using xda app
RoberGalarga said:
Put the toast after zin.close()
Click to expand...
Click to collapse
Hey,
I tried this but it doesn't work. I used this statement:
Code:
Toast.makeText(this, "Extraction complete", "LENGTH_SHORT").show();
and I got this error message: The method makeText(Context, CharSequence, int) in the type Toast is not applicable for the arguments (Decompress, String, String).
Help?
The method makeText(Context, CharSequence, int) in the type Toast is not applicable for the arguments (Decompress, String, String)
What the above line means is that you need to pass a Context object, a CharSequence object and an int. You are passing the wrong object types (Decompress, String, String).
The example you saw used the Toast in the activity class itself, that is why the first value passed was a this. The "LENGTH_SHORT" is actually a constant Toast.LENGTH_SHORT.
I am guessing you are making the button object in your main activity class. So i'd suggest making an additional method for the activity class that looks like this
Code:
public void displayToast(CharSequence cs)
{
Toast.makeText(this, cs, Toast.LENGTH_SHORT).show();
}
and then make the following change to your code
Code:
Button decompress = (Button)findViewById(R.id.button1);
decompress.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
String zipFile = Environment.getExternalStorageDirectory() + "/IPM/Splash.zip";
String unzipLocation = Environment.getExternalStorageDirectory() + "/IPM/Splash/";
Decompress d = new Decompress(zipFile, unzipLocation);
d.unzip();
// Add the following line
displayToast("Unzip complete");
}
});
Let me know if it worked for you.
The_R said:
The method makeText(Context, CharSequence, int) in the type Toast is not applicable for the arguments (Decompress, String, String)
What the above line means is that you need to pass a Context object, a CharSequence object and an int. You are passing the wrong object types (Decompress, String, String).
The example you saw used the Toast in the activity class itself, that is why the first value passed was a this. The "LENGTH_SHORT" is actually a constant Toast.LENGTH_SHORT.
I am guessing you are making the button object in your main activity class. So i'd suggest making an additional method for the activity class that looks like this
Code:
public void displayToast(CharSequence cs)
{
Toast.makeText(this, cs, Toast.LENGTH_SHORT).show();
}
and then make the following change to your code
Code:
Button decompress = (Button)findViewById(R.id.button1);
decompress.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
String zipFile = Environment.getExternalStorageDirectory() + "/IPM/Splash.zip";
String unzipLocation = Environment.getExternalStorageDirectory() + "/IPM/Splash/";
Decompress d = new Decompress(zipFile, unzipLocation);
d.unzip();
// Add the following line
displayToast("Unzip complete");
}
});
Let me know if it worked for you.
Click to expand...
Click to collapse
PERFECT! You're amazing!

[HELP] Hard brick after writing to SD card!

Hello guys, I'd like to ask you for your wisdom and maybe a little help.
After using an application that writes to SD card, my I9100 was bricked. It won't turn on, won't react to power button or any combination (recovery/download mode). When I plug the power, nothing comes up on the screen. I tried jump-starting it and other tricks with the exception of USB jig. The phone is just dead and nothing comes up on screen.
Below I paste a code of the ran application. It writes an image to SD card. The program ran without any problems, but the image was not written. I suppose the dd program somehow wrote to the wrong section and thus bricked the phone. Could someone confirm?
The path to the SD Card was /dev/block/mmcblk0
After the reboot, the phone just went stone cold dead.
Code:
protected void writeImage()
{
// Verify that root access is obtainable
if (!execCommandAsRoot("true")) {
showMessage("Your device is not rooted. Cannot proceed.");
return;
}
// Verify that SD card device exists
File sdDevice = new File(editOutputDevice.getText().toString());
if (!sdDevice.exists()) {
showMessage("SD card device does not exist, or no card inserted");
return;
}
// Progress dialog
final Handler progressHandler = new Handler();
final ProgressDialog progress = new ProgressDialog(this);
progress.setCancelable(false);
progress.setMessage("Starting thread");
progress.show();
// Write image in worker thread
new Thread(new Runnable() {
public void run() {
String imagefile = editImageFile.getText().toString();
String sd = editOutputDevice.getText().toString();
String datadir = getFilesDir().getPath();
/* The image files need to be extracted from the .apk to the data folder
* unless the user has run the app before, and this has already been done.
* We store the version (lastUpdate timestamp) of the extracted files in the preferences.
*/
SharedPreferences preferences = getPreferences(MODE_PRIVATE);
long berrybootVersion = -1;
try {
berrybootVersion = getPackageManager().getPackageInfo(getPackageName(), 0).lastUpdateTime;
} catch (NameNotFoundException e) {
e.printStackTrace();
}
if (!new File(datadir+"/a10-patchspl").exists()
|| preferences.getLong("berrybootimgversion", 0) != berrybootVersion)
{
updateProgress("Uncompressing files from .apk");
try {
uncompressFile("berryboot.img", datadir);
uncompressFile("sunxi-spl.bin", datadir);
uncompressFile("a10-patchspl", datadir);
new File(datadir+"/a10-patchspl").setExecutable(true);
new File(datadir+"/mntNand").mkdir();
new File(datadir+"/mntSD").mkdir();
preferences.edit().putLong("berrybootimgversion", berrybootVersion).commit();
} catch (IOException ie) {
error("Error uncompressing files. Check disk space.");
return;
}
}
updateProgress("Unmounting SD card");
execCommandAsRoot("umount "+sd);
execCommandAsRoot("umount "+sd+"p1");
/* Also unmount everything mounted to /mnt/extSdCard,
* as vold seems to mount /dev/vold/somedevice instead of /dev/block/mmcblk0p1 */
String[] extsdFolders = new File("/mnt/extSdCard").list();
for (String extsdFolder : extsdFolders)
{
execCommandAsRoot("umount /mnt/extSdCard/"+extsdFolder);
}
execCommandAsRoot("umount /mnt/extSdCard");
updateProgress("Writing image to SD card");
if (!execCommandAsRoot("dd 'if="+imagefile+"' of="+sd+" bs=1024k"))
{
error("Error writing image file to SD card");
return;
}
if (checkPatch.isChecked())
{
updateProgress("Patching u-boot SPL");
if (!execCommandAsRoot(datadir+"/a10-patchspl "+datadir+"/sunxi-spl.bin "+sd))
{
error("Error patching u-boot SPL");
return;
}
updateProgress("Copying script.bin from NAND to SD");
if (!execCommandAsRoot("mount -t vfat /dev/block/nanda "+datadir+"/mntNand"))
{
error("Error mounting /dev/block/nanda");
return;
}
if (!execCommandAsRoot("mount -t vfat "+sd+"p1 "+datadir+"/mntSD"))
{
error("Error mounting SD card device");
return;
}
String scriptbin;
if ( new File(datadir+"/mntNand/script.bin").exists() )
scriptbin = datadir+"/mntNand/script.bin";
else if ( new File(datadir+"/mntNand/evb.bin").exists() )
scriptbin = datadir+"/mntNand/evb.bin";
else
{
error("Neither script.bin nor evb.bin exists in NAND");
return;
}
if (!execCommandAsRoot("cat "+scriptbin+ " >"+datadir+"/mntSD/script.bin"))
{
error("Error copying "+scriptbin+" to SD");
return;
}
/* Save human readable a10-memdump info to a10-meminfo.txt on the SD card for debugging purposes */
execCommandAsRoot(datadir+"/a10-patchspl -dump > "+datadir+"/mntSD/a10-meminfo.txt");
if (!execCommandAsRoot("umount "+datadir+"/mntNand"))
{
error("Error unmounting /dev/block/nanda");
return;
}
if (!execCommandAsRoot("umount "+datadir+"/mntSD"))
{
error("Error unmounting SD card device");
return;
}
}
updateProgress("Finish writing... (sync)");
execCommandAsRoot("sync");
finished();
}
// Update the progress in the UI thread
protected void updateProgress(final String msg)
{
progressHandler.post(new Runnable() {
@Override
public void run() {
progress.setMessage(msg);
}
});
}
// Show error in UI thread
protected void error(final String msg)
{
progressHandler.post(new Runnable() {
@Override
public void run() {
progress.hide();
showMessage(msg);
}
});
}
// Notify UI thread we are finished
protected void finished() {
progressHandler.post(new Runnable() {
@Override
public void run() {
progress.hide();
askReboot();
}
});
}
/*
* Uncompress utility file stored in .apk to datadir
*/
protected void uncompressFile(String filename, String dest) throws IOException
{
InputStream is = getAssets().open(filename);
OutputStream os = new FileOutputStream(dest+"/"+filename);
byte[] buf = new byte[4096];
int len;
while ((len =is.read(buf)) > 0) {
os.write(buf, 0, len);
}
os.close();
is.close();
}
}).start(); // start thread
}
protected void showMessage(String msg)
{
new AlertDialog.Builder(this)
.setMessage(msg)
.setNeutralButton("Ok", null)
.create().show();
}
protected void askReboot()
{
/* Ask if user wants to reboot */
new AlertDialog.Builder(this)
.setMessage("All done! Reboot now?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
execCommandAsRoot("reboot");
}
})
.setNegativeButton("No", null)
.create().show();
}
protected boolean execCommandAsRoot(String path)
{
try {
String[] cmd = {"su","-c",path};
Process p = Runtime.getRuntime().exec(cmd);
int exitCode = p.waitFor();
return (exitCode == 0);
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
}
If absolutely nothing comes on with the charger or even the power button your phone may truly be bricked. Are you sure you have tried everything? There may be hope yet.
Perhaps the only way is via the USB jig. Try that.
Sent from my ONE TOUCH 4033A using Tapatalk
Service centre = motherboard replacement. Try a jig, but very very unlikely to work.
Vexi said:
Hello guys, I'd like to ask you for your wisdom and maybe a little help.
After using an application that writes to SD card, my I9100 was bricked. It won't turn on, won't react to power button or any combination (recovery/download mode). When I plug the power, nothing comes up on the screen. I tried jump-starting it and other tricks with the exception of USB jig. The phone is just dead and nothing comes up on screen.
Below I paste a code of the ran application. It writes an image to SD card. The program ran without any problems, but the image was not written. I suppose the dd program somehow wrote to the wrong section and thus bricked the phone. Could someone confirm?
The path to the SD Card was /dev/block/mmcblk0
After the reboot, the phone just went stone cold dead.
Code:
protected void writeImage()
{
// Verify that root access is obtainable
if (!execCommandAsRoot("true")) {
showMessage("Your device is not rooted. Cannot proceed.");
return;
}
// Verify that SD card device exists
File sdDevice = new File(editOutputDevice.getText().toString());
if (!sdDevice.exists()) {
showMessage("SD card device does not exist, or no card inserted");
return;
}
// Progress dialog
final Handler progressHandler = new Handler();
final ProgressDialog progress = new ProgressDialog(this);
progress.setCancelable(false);
progress.setMessage("Starting thread");
progress.show();
// Write image in worker thread
new Thread(new Runnable() {
public void run() {
String imagefile = editImageFile.getText().toString();
String sd = editOutputDevice.getText().toString();
String datadir = getFilesDir().getPath();
/* The image files need to be extracted from the .apk to the data folder
* unless the user has run the app before, and this has already been done.
* We store the version (lastUpdate timestamp) of the extracted files in the preferences.
*/
SharedPreferences preferences = getPreferences(MODE_PRIVATE);
long berrybootVersion = -1;
try {
berrybootVersion = getPackageManager().getPackageInfo(getPackageName(), 0).lastUpdateTime;
} catch (NameNotFoundException e) {
e.printStackTrace();
}
if (!new File(datadir+"/a10-patchspl").exists()
|| preferences.getLong("berrybootimgversion", 0) != berrybootVersion)
{
updateProgress("Uncompressing files from .apk");
try {
uncompressFile("berryboot.img", datadir);
uncompressFile("sunxi-spl.bin", datadir);
uncompressFile("a10-patchspl", datadir);
new File(datadir+"/a10-patchspl").setExecutable(true);
new File(datadir+"/mntNand").mkdir();
new File(datadir+"/mntSD").mkdir();
preferences.edit().putLong("berrybootimgversion", berrybootVersion).commit();
} catch (IOException ie) {
error("Error uncompressing files. Check disk space.");
return;
}
}
updateProgress("Unmounting SD card");
execCommandAsRoot("umount "+sd);
execCommandAsRoot("umount "+sd+"p1");
/* Also unmount everything mounted to /mnt/extSdCard,
* as vold seems to mount /dev/vold/somedevice instead of /dev/block/mmcblk0p1 */
String[] extsdFolders = new File("/mnt/extSdCard").list();
for (String extsdFolder : extsdFolders)
{
execCommandAsRoot("umount /mnt/extSdCard/"+extsdFolder);
}
execCommandAsRoot("umount /mnt/extSdCard");
updateProgress("Writing image to SD card");
if (!execCommandAsRoot("dd 'if="+imagefile+"' of="+sd+" bs=1024k"))
{
error("Error writing image file to SD card");
return;
}
if (checkPatch.isChecked())
{
updateProgress("Patching u-boot SPL");
if (!execCommandAsRoot(datadir+"/a10-patchspl "+datadir+"/sunxi-spl.bin "+sd))
{
error("Error patching u-boot SPL");
return;
}
updateProgress("Copying script.bin from NAND to SD");
if (!execCommandAsRoot("mount -t vfat /dev/block/nanda "+datadir+"/mntNand"))
{
error("Error mounting /dev/block/nanda");
return;
}
if (!execCommandAsRoot("mount -t vfat "+sd+"p1 "+datadir+"/mntSD"))
{
error("Error mounting SD card device");
return;
}
String scriptbin;
if ( new File(datadir+"/mntNand/script.bin").exists() )
scriptbin = datadir+"/mntNand/script.bin";
else if ( new File(datadir+"/mntNand/evb.bin").exists() )
scriptbin = datadir+"/mntNand/evb.bin";
else
{
error("Neither script.bin nor evb.bin exists in NAND");
return;
}
if (!execCommandAsRoot("cat "+scriptbin+ " >"+datadir+"/mntSD/script.bin"))
{
error("Error copying "+scriptbin+" to SD");
return;
}
/* Save human readable a10-memdump info to a10-meminfo.txt on the SD card for debugging purposes */
execCommandAsRoot(datadir+"/a10-patchspl -dump > "+datadir+"/mntSD/a10-meminfo.txt");
if (!execCommandAsRoot("umount "+datadir+"/mntNand"))
{
error("Error unmounting /dev/block/nanda");
return;
}
if (!execCommandAsRoot("umount "+datadir+"/mntSD"))
{
error("Error unmounting SD card device");
return;
}
}
updateProgress("Finish writing... (sync)");
execCommandAsRoot("sync");
finished();
}
// Update the progress in the UI thread
protected void updateProgress(final String msg)
{
progressHandler.post(new Runnable() {
@Override
public void run() {
progress.setMessage(msg);
}
});
}
// Show error in UI thread
protected void error(final String msg)
{
progressHandler.post(new Runnable() {
@Override
public void run() {
progress.hide();
showMessage(msg);
}
});
}
// Notify UI thread we are finished
protected void finished() {
progressHandler.post(new Runnable() {
@Override
public void run() {
progress.hide();
askReboot();
}
});
}
/*
* Uncompress utility file stored in .apk to datadir
*/
protected void uncompressFile(String filename, String dest) throws IOException
{
InputStream is = getAssets().open(filename);
OutputStream os = new FileOutputStream(dest+"/"+filename);
byte[] buf = new byte[4096];
int len;
while ((len =is.read(buf)) > 0) {
os.write(buf, 0, len);
}
os.close();
is.close();
}
}).start(); // start thread
}
protected void showMessage(String msg)
{
new AlertDialog.Builder(this)
.setMessage(msg)
.setNeutralButton("Ok", null)
.create().show();
}
protected void askReboot()
{
/* Ask if user wants to reboot */
new AlertDialog.Builder(this)
.setMessage("All done! Reboot now?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
execCommandAsRoot("reboot");
}
})
.setNegativeButton("No", null)
.create().show();
}
protected boolean execCommandAsRoot(String path)
{
try {
String[] cmd = {"su","-c",path};
Process p = Runtime.getRuntime().exec(cmd);
int exitCode = p.waitFor();
return (exitCode == 0);
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
}
Click to expand...
Click to collapse
Take your phone to local repair mobile shop.... and asks for POWER IC replacement( if there is problem in it.. ask him to check for it)
or motherboard replacement..
If your finally decision is motherboard replacement.. then in mean time do this on your motherboard may be it'll work :
check out this link-
http://forum.gsmhosting.com/vbb/f258/samsung-galaxy-s2-i9100-short-circuit-solution-1537757/
If your hand are handy to these things you can do it yourself otherwise Ask an technician to do this...
And
Let us know what will happen
Do you think JTAG / RIFF Box will help anything in this situation?
Vexi said:
Do you think JTAG / RIFF Box will help anything in this situation?
Click to expand...
Click to collapse
It doesn't guarantee your phone will be repaired or not.. BUT yes you can give it a chance...
Very very unlikely to work. Don't go out and buy one, put it that way.

[Q] [LibGdx] Is this the correct way to disable ads? :)

Hi! So Im about to release two versions of my app, one free with ads and one for 99cent. I followed Marios instuctions on how to add AdMob for Libgdx so I ended up with this:
Code:
public class MainActivity extends AndroidApplication implements IActivityRequestHandler {
protected AdView adView;
private final int SHOW_ADS = 1;
private final int HIDE_ADS = 0;
protected Handler handler = new Handler()
{
@Override
public void handleMessage(Message msg) {
switch(msg.what) {
case SHOW_ADS:
{
adView.setVisibility(View.VISIBLE);
break;
}
case HIDE_ADS:
{
adView.setVisibility(View.GONE);
break;
}
}
}
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Create the layout
RelativeLayout layout = new RelativeLayout(this);
// Do the stuff that initialize() would do for you
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
// Create the libgdx View
View gameView = initializeForView(new Game(this), false);
// Create and setup the AdMob view
adView = new AdView(this, AdSize.BANNER, "secretKey"); // Put in your secret key here
adView.loadAd(new AdRequest());
// Add the libgdx view
layout.addView(gameView);
// Add the AdMob view
RelativeLayout.LayoutParams adParams =
new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
adParams.addRule(RelativeLayout.ALIGN_PARENT_TOP);
adParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
layout.addView(adView, adParams);
// Hook it all up
setContentView(layout);
}
@Override
public void showAds(boolean show) {
handler.sendEmptyMessage(show ? SHOW_ADS : HIDE_ADS);
}
}
My question is, since Im going to have a adfree version and I want to make it as easy as possible, can I just call "handler.showAds(false);" to completely dissable ads in the paid version or should I completely remove everything that have to do with the ads? I don't know much about how the ads works and Im afraid there will be some mix up since I read something about impressions might go wrong and stuff
I changed it to this, will this work?
Code:
public class MainActivity extends AndroidApplication implements IActivityRequestHandler {
protected AdView adView;
private final int SHOW_ADS = 1;
private final int HIDE_ADS = 0;
private boolean isBought = false;
protected Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
switch(msg.what) {
case SHOW_ADS:
{
adView.setVisibility(View.VISIBLE);
break;
}
case HIDE_ADS:
{
adView.setVisibility(View.GONE);
break;
}
}
}
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Create the layout
RelativeLayout layout = new RelativeLayout(this);
// Do the stuff that initialize() would do for you
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
// Create the libgdx View
View gameView = initializeForView(new Game(this, isBought), false);
// Create and setup the AdMob view
if(!isBought){
adView = new AdView(this, AdSize.BANNER, "Secret Key"); // Put in your secret key here
adView.loadAd(new AdRequest());
}
// Add the libgdx view
layout.addView(gameView);
// Add the AdMob view
if(!isBought){
RelativeLayout.LayoutParams adParams =
new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
adParams.addRule(RelativeLayout.ALIGN_PARENT_TOP);
adParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
layout.addView(adView, adParams);
}
// Hook it all up
setContentView(layout);
}
@Override
public void showAds(boolean show) {
handler.sendEmptyMessage(show ? SHOW_ADS : HIDE_ADS);
}
}
Okay, so I have the fix for this, but I have another problem now. I had to create two different android projects (both linked to the main source of the game) with a ".free" at the free versions packaging name in the AndroidManifest, because you cant have two apps with the same packaging on Google Play. But this makes it so that the user have to restart everything if they upgrade from the free version to paid version.
All I want to is that I could save the preference file to a specific place (so it wont get removed if the free version gets removed) and make the paid version read it. And Im using LibGdx btw Smiley
EDIT:
I have tried doing it now with using Context. I'm able to find the preference file, but it's not able to get the contents from the preference file itself, since it always returns 0 (the default value). Is this because I use LibGdx? I have read that LibGdx saves its own preference files as SharedPreferences on Android so that shouldn't be the issue.
Code:
public void tryLoadPrefs(){
Context otherAppsContext = null;
try {
otherAppsContext = createPackageContext("com.mayogames.zombiecubes.free", 0);
} catch (NameNotFoundException e) {
System.out.println(e);
}
System.out.println("Extracting = " + otherAppsContext.getSharedPreferences("Settings", CONTEXT_IGNORE_SECURITY).getInt("seconds", 0));
}
Delta517 said:
Okay, so I have the fix for this, but I have another problem now. I had to create two different android projects (both linked to the main source of the game) with a ".free" at the free versions packaging name in the AndroidManifest, because you cant have two apps with the same packaging on Google Play. But this makes it so that the user have to restart everything if they upgrade from the free version to paid version.
All I want to is that I could save the preference file to a specific place (so it wont get removed if the free version gets removed) and make the paid version read it. And Im using LibGdx btw Smiley
EDIT:
I have tried doing it now with using Context. I'm able to find the preference file, but it's not able to get the contents from the preference file itself, since it always returns 0 (the default value). Is this because I use LibGdx? I have read that LibGdx saves its own preference files as SharedPreferences on Android so that shouldn't be the issue.
Code:
public void tryLoadPrefs(){
Context otherAppsContext = null;
try {
otherAppsContext = createPackageContext("com.mayogames.zombiecubes.free", 0);
} catch (NameNotFoundException e) {
System.out.println(e);
}
System.out.println("Extracting = " + otherAppsContext.getSharedPreferences("Settings", CONTEXT_IGNORE_SECURITY).getInt("seconds", 0));
}
Click to expand...
Click to collapse
EDIT: Im loading in the onCreate() method. Is that a problem?
Personally, the way I do it with libGDX is I create two projects. One with the adds and one without, like you said.
To solve the problem of not having two projects with the same package name, I change the second one. Then go into the android manifest file and change it there too. Then it should work.

How to integrate Search Kit?

Article Introduction
In this article we will work in integrate search and will explore many features together in this service.
Search Kit
HUAWEI Search Kit fully opens Petal Search capabilities through the device-side SDK and cloud-side APIs, enabling ecosystem partners to quickly provide the optimal mobile app search experience.
Dependencies that needed
Code:
//design
implementation 'com.google.android.material:material:1.2.1'
implementation 'androidx.recyclerview:recyclerview:1.1.0'
implementation 'com.github.bumptech.glide:glide:4.10.0'
//rxJava
implementation 'io.reactivex.rxjava2:rxjava:2.2.19'
implementation 'io.reactivex.rxjava2:rxandroid:2.1.1'
implementation 'com.squareup.retrofit2:retrofit:2.5.0'
implementation 'com.squareup.retrofit2:converter-gson:2.5.0'
implementation 'com.squareup.retrofit2:adapter-rxjava2:2.5.0'
//searchKit HMS
implementation 'com.huawei.hms:searchkit:5.0.4.303'
1. Create a class that extends from Application
Code:
import android.app.Application
import com.huawei.hms.searchkit.SearchKitInstance
class SearchKitApplication: Application() {
override fun onCreate() {
super.onCreate()
// Initialize Search Kit.
SearchKitInstance.init(this, "your_app_id");
}
}
In Manifest in Application tag apply this below line of code
Code:
android:name=".SearchKitApplication"
3. Now we can create an empty activity with this name
SearchActivity. please take a look on important part in references.
or as you like you can modify it, if you would like.
4. In Utils package that we created in point 2, let’s create AnimationUtils class
Code:
public class AnimationUtils {
public static void expand(final View v) {
int matchParentMeasureSpec =
View.MeasureSpec.makeMeasureSpec(((View) v.getParent()).getWidth(), View.MeasureSpec.EXACTLY);
int wrapContentMeasureSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
v.measure(matchParentMeasureSpec, wrapContentMeasureSpec);
final int targetHeight = v.getMeasuredHeight();
v.getLayoutParams().height = 1;
v.setVisibility(View.VISIBLE);
Animation a =
new Animation() {
@Override
protected void applyTransformation(float interpolatedTime, Transformation t) {
v.getLayoutParams().height =
interpolatedTime == 1
? ViewGroup.LayoutParams.WRAP_CONTENT
: (int) (targetHeight * interpolatedTime);
v.requestLayout();
}
@Override
public boolean willChangeBounds() {
return true;
}
};
a.setDuration((int) (targetHeight / v.getContext().getResources().getDisplayMetrics().density));
v.startAnimation(a);
}
public static void collapse(final View v) {
final int initialHeight = v.getMeasuredHeight();
Animation a =
new Animation() {
@Override
protected void applyTransformation(float interpolatedTime, Transformation t) {
if (interpolatedTime == 1) {
v.setVisibility(View.GONE);
} else {
v.getLayoutParams().height = initialHeight - (int) (initialHeight * interpolatedTime);
v.requestLayout();
}
}
@Override
public boolean willChangeBounds() {
return true;
}
};
a.setDuration((int) (initialHeight / v.getContext().getResources().getDisplayMetrics().density));
v.startAnimation(a);
}
}
5. Now in network package let’s work on it to can get access token that will let us able to use search kit features
Code:
public class UrlHelper {
/**
* The Content REQUEST_TOKEN.
*/
public static final String REQUEST_TOKEN = "oauth2/v3/token";
// public static final String REQUEST_TOKEN = "oauth2/v2/token/https://logintestlf.hwcloudtest.cn/";
}
Code:
public interface QueryService {
@FormUrlEncoded
@POST(UrlHelper.REQUEST_TOKEN)
Observable<TokenResponse> getRequestToken(
@Field("grant_type") String grantType,
@Field("client_id") String ClientId,
@Field("client_secret") String clientSecret);
}
Code:
public class NetworkManager {
private static final String TAG = NetworkManager.class.getSimpleName();
private static NetworkManager networkManager;
public static NetworkManager getInstance() {
if (networkManager == null) {
syncInit();
}
return networkManager;
}
private static synchronized void syncInit() {
if (networkManager == null) {
networkManager = new NetworkManager();
}
}
public QueryService createService(Context context, String baseUrl) {
QueryService queryService = null;
Retrofit retrofit = null;
Retrofit.Builder builder = new Retrofit.Builder().baseUrl(baseUrl);
OkHttpClient.Builder clientBuilder = new OkHttpClient.Builder();
try {
SSLSocketFactory ssf = SecureSSLSocketFactory.getInstance(context);
X509TrustManager xtm = new SecureX509TrustManager(context);
clientBuilder.sslSocketFactory(ssf, xtm);
clientBuilder.hostnameVerifier(new StrictHostnameVerifier());
} catch (IOException e) {
Log.e(TAG, "getRetrofit: " + e.getMessage());
} catch (IllegalAccessException e) {
Log.e(TAG, "getRetrofit: " + e.getMessage());
} catch (NoSuchAlgorithmException e) {
Log.e(TAG, "getRetrofit: " + e.getMessage());
} catch (KeyManagementException e) {
Log.e(TAG, "getRetrofit: " + e.getMessage());
} catch (KeyStoreException e) {
Log.e(TAG, "getRetrofit: " + e.getMessage());
} catch (CertificateException e) {
Log.e(TAG, "getRetrofit: " + e.getMessage());
} catch (Exception e) {
Log.e(TAG, "getRetrofit: " + e.getMessage());
}
OkHttpClient client =
clientBuilder
.retryOnConnectionFailure(true)
.readTimeout(5000, TimeUnit.MILLISECONDS)
.connectTimeout(5000, TimeUnit.MILLISECONDS)
.build();
try {
retrofit =
builder.client(client)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build();
queryService = retrofit.create(QueryService.class);
} catch (Exception e) {
Log.e(TAG, "createRestClient error: " + e.getMessage());
}
return queryService;
}
}
6. In bean package, let’s start with create ListBean class
Code:
public class ListBean {
String title;
String url;
String click_url;
public String getClick_url() {
return click_url;
}
public void setClick_url(String click_url) {
this.click_url = click_url;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
}
Now we will work on create TokenResponse class:
Code:
public class TokenResponse {
String access_token;
Integer expires_in;
String token_type;
public String getAccess_token() {
return access_token;
}
public void setAccess_token(String access_token) {
this.access_token = access_token;
}
public Integer getExpires_in() {
return expires_in;
}
public void setExpires_in(Integer expires_in) {
this.expires_in = expires_in;
}
public String getToken_type() {
return token_type;
}
public void setToken_type(String token_type) {
this.token_type = token_type;
}
}
More details, you can visit https://forums.developer.huawei.com/forumPortal/en/topic/0204411812493980212
Hi i was following your sample, How can I obtain app id?
SearchKitInstance.init(this, "your_app_id");
Please help me

Categories

Resources