Trying to make a session timer with a camera timer - Java for Android App Development

Hello all ,
i'm trying to make a timer that will kick the user out after let's say a few seconds , i used asynctask for it
it supposed to work on all activities including one that uses a camera on a diffrent thread ( using vuforia api and needs internet )
for some reason when i do it the camera doesn't work
(the same thing happens when there is no internet connection - might be related)
any ideas why ?
here's my asynctask
Code:
private class LoadSessionASYNC extends AsyncTask<String, Void, String> {
long time;
long interval;
public LoadSessionASYNC(long seshTime, long interval) {
time = seshTime;
interval=inter;
}
@Override
protected String doInBackground(String... urls) {
while (time >0)
{
publishProgress();
try {
Thread.sleep(interval);
} catch (InterruptedException e) {e.printStackTrace();}
time= time-interval;
}
return null;
}
@Override
protected void onPostExecute(String result) {
Intent startfresh = new Intent(getBaseContext(),WelcomActivity.class);
startActivity(startfresh);
}
@Override
protected void onProgressUpdate(Void... values) {
Toast.makeText(getApplicationContext(), "time to finish : "+time/1000+"seconds", Toast.LENGTH_SHORT).show();
super.onProgressUpdate(values);
}
}

Related

SoftReference caching

Hi,
I am trying to write simple cache class. Class uses SoftReference in order to avoid killing application.
Code:
import java.lang.ref.SoftReference;
import java.util.HashMap;
import java.util.Map;
public class MemoryCache {
// singleton implemtation
private static MemoryCache instance = null;
protected MemoryCache() { }
public static MemoryCache getInstance() {
if(instance == null) {
instance = new MemoryCache();
}
return instance;
}
//
private Map<String, SoftReference<Object>> cachedItems = new HashMap<String, SoftReference<Object>>();
public void saveCacheItem(String itemId, Object objForCache) {
cachedItems.put(itemId, new SoftReference<Object>(objForCache));
}
public Object getCacheItem(String itemId) {
if(cacheItemExists(itemId)) {
return cachedItems.get(itemId).get();
}
else {
return null;
}
}
public Boolean cacheItemExists(String itemId) {
if(cachedItems.containsKey(itemId)) {
if(cachedItems.get(itemId) != null ) {
return true;
}
}
return false;
}
public void deleteCacheItem(String itemId) {
if(cachedItems.containsKey(itemId)) {
cachedItems.remove(itemId);
}
}
}
However, referenced objects are cleaned too early. Even though cached item is a class with just few attributes, its lifespan is very short.
I tested this functionality only on android emulator.
Does my class cause problem or garbage collector/vm?

Camera picture is very dark

Hi,
im playing around with the Camera Service. The preview mode works well, but if I take a picture and save it, it is a lot darker as in the preview. I tried it with the delivered camera app and there is no such problem.
I tried it with many diffrent values (iso, brightness, scenemode, whitebalance), but nothing changed, but the preview. It seems, that the preferences only have effect in the previewmode.
Device: altek A14 leo
OS: Android 2.1
Picture saved by the standard camera app:
abload.de/img/stdapp8uql.jpg
Preview mode:
abload.de/img/previewrne6.jpg
Picture saved by my app:
abload.de/img/myappiugc.jpg
parameters of the camera
Code:
atk-frame=0
brightness-max=12
brightness-min=0
brightness=6
camera-id=1
contrast-max=2
contrast-min=0
contrast=1
effect-values=none,mono,sepia,whiteboard
effect=none
flash-mode-values=off,auto,on,red-eye
flash-mode=off
focus-mode-values=auto,infinity
focus-mode=auto
gps-altitude=0
gps-latitude=0.0
gps-longitude=0.0
gps-timestamp=1199145600
iso-values=auto,80,100,200,400,800,1600,3200
iso=auto
jpeg-quality=100
jpeg-thumbnail-height=384
jpeg-thumbnail-quality=100
jpeg-thumbnail-width=512
max-zoom=9
metering-values=spot,center,matrix
metering=center
min-zoom=0
orientation=landscape
picture-format-values=jpeg
picture-format=jpeg
picture-size-values=2048x1536,1280x960
picture-size=2048x1536
preview-format-values=yuv420sp
preview-format=yuv420sp
preview-frame-rate-values=15
preview-frame-rate=15
preview-size-values=640x480
preview-size=640x480
rotation=0
saturation-max=0
saturation-min=2
saturation=1
scene-mode-values=auto,portrait,landscape,night,beach,snow,sunset,fireworks,sports,candlelight
scene-mode=auto
SD9-poweron-mode=0
sharpness-max=2
sharpness-min=0
sharpness=1
smooth-zoom-supported=true
whitebalance-values=auto,fluorescent,daylight,cloudy-daylight
whitebalance=auto
zoom-factors=100,130,160,190,220,250,280,310,340,360,400
zoom-supported=true
zoom=0
Code:
private OnClickListener cameraClickListener = new OnClickListener() {
public void onClick(View v) {
inPreview = false;
cam.takePicture(null, null, photoCallback);
}
};
PictureCallback photoCallback = new PictureCallback() {
public void onPictureTaken(byte[] data, Camera camera) {
new SavePhotoTask().execute(data);
startPreview();
}
};
class SavePhotoTask extends AsyncTask<byte[], String, String> {
protected String doInBackground(byte[]... imageData) {
File photo = new File(Environment.getExternalStorageDirectory(), "photo.jpg");
if (photo.exists()) {
photo.delete();
}
try {
FileOutputStream fos = new FileOutputStream(photo.getPath());
fos.write(imageData[0]);
fos.close();
Log.i("IMAGE SAVED ASYNC", photo.getPath());
} catch (java.io.IOException e) {
Log.e("Error", "Exception in photoCallback", e);
}
return (null);
}
}
Does anybody have an idea, what causes this behaviour?
thanks.
rgds
I am not sure what happening with you. But as far as your codes it should work well. try other camera apps. Like 360. But problem persist then go to service center. The problem is with hardware.
Hi,
sorry for the late response. It was no hardware issue. I just had to call autoFocus and takePicture in the AutoFocusCallback.
Code:
private OnClickListener cameraClickListener = new OnClickListener() {
public void onClick(View v) {
if (!isFocusing) {
isFocusing = true;
cam.autoFocus(autoFocusCallback);
}
}
};
AutoFocusCallback autoFocusCallback = new AutoFocusCallback() {
public void onAutoFocus(boolean success, Camera camera) {
if (success) {
isFocusing = false;
camera.takePicture(null, null, photoCallback);
}
}
};
regards

[Q] How to make faster lockscreen application?

I want to make a lockscreen application, so I made simple application.
But, this is too slow. Time from being on screen to seeing my application is almost 3 seconds.
Why this app is too slow?
Here is the my code.
(this method is included in the class that inherit BroadcastReceiver)
public void onReceive(Context context, Intent intent)
{
if (intent.getAction() == Intent.ACTION_SCREEN_OFF)
{
Toast.makeText(context, "Screen is off", Toast.LENGTH_SHORT).show();
Intent i = new Intent( context, MainActivity.class );
//i.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pi = PendingIntent.getActivity(context, 0, i, PendingIntent.FLAG_ONE_SHOT);
try
{
pi.send();
}
catch (CanceledException e)
{
e.printStackTrace();
}
}
}

[Q]Service Socket closed by Background Foreground Lifecycle

I am writing an IRC Client, and so far as long as I dont send the app to the background and try to restore it it works fine. Tabs for multiple channels, the connected socket is in a bound service (started separately via INTENT and a startService call), etc and so on.
However, whenever I send the app to the background, then bring it back forward, the socket closes. I would have the same issue with screen rotation but I found the config setting that stops it from going through destroy/create on rotation. If I figure this out I may actually get rid of that since the issue will have been solved.
The other issue I seem to be having is that it takes a long time to re-bind to the service, and I have no idea why (the initial binding and startup is pretty quick, but re-binding to it seems to take forever, and when It does re-bind, the socket is closed).
Here are the code samples that I feel to be relevant, let me know if there's something more specific you want to see.
Code:
//This is the Service in question
public class ConnectionService extends Service{
private BlockingQueue<String> MessageQueue;
public final IBinder myBind = new ConnectionBinder();
public class ConnectionBinder extends Binder {
ConnectionService getService() {
return ConnectionService.this;
}
}
private Socket socket;
private BufferedWriter writer;
private BufferedReader reader;
private IRCServer server;
private WifiManager.WifiLock wLock;
private Thread readThread = new Thread(new Runnable() {
@Override
public void run() {
try {
String line;
while ((line = reader.readLine( )) != null) {
//message parsing stuff
}
}
catch (Exception e) {}
}
});
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if(MessageQueue == null)
MessageQueue = new LinkedBlockingQueue<String>();
return Service.START_STICKY;
}
@Override
public IBinder onBind(Intent arg0) {
return myBind;
}
@Override
public boolean stopService(Intent name) {
try {
socket.close();
wLock.release();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return super.stopService(name);
}
@Override
public void onDestroy()
{//I put this here so I had a breakpoint in place to make sure this wasn't firing instead of stopService
try {
socket.close();
wLock.release();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
super.onDestroy();
}
public void SendMessage(String message)
{
try {
writer.write(message + "\r\n");
writer.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
public String readLine()
{//this is called by the activity which consumes the service. Its just an accessor to MessageQueue
try {
if(!isConnected())
return null;
else
return MessageQueue.take();
} catch (InterruptedException e) {
return "";
}
}
public boolean ConnectToServer(IRCServer newServer)
{
try {
//create a new message queue (connecting to a new server)
MessageQueue = new LinkedBlockingQueue<String>();
//lock the wifi
WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
wLock = wifiManager.createWifiLock(WifiManager.WIFI_MODE_FULL, "LockTag");
wLock.acquire();
server = newServer;
//connect to server
socket = new Socket();
socket.setKeepAlive(true);
socket.setSoTimeout(60000);
socket.connect(new InetSocketAddress(server.NAME, Integer.parseInt(server.PORT)), 10000);
writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
//run basic login scripts.
String line;
while ((line = reader.readLine( )) != null) {
//server initialization stuff
}
//start the reader thread AFTER the primary login!!!
CheckStartReader();
if(server.START_CHANNEL == null || server.START_CHANNEL == "")
{
server.WriteCommand("/join " + server.START_CHANNEL);
}
//we're done here, go home everyone
} catch (NumberFormatException e) {
return false;
} catch (IOException e) {
return false;
}
return true;
}
private void queueMessage(String line) {
try {
MessageQueue.put(line);
} catch (InterruptedException e) {
}
}
public boolean isConnected()
{
return socket.isConnected();
}
public void CheckStartReader()
{
if(this.isConnected() && !readThread.isAlive())
readThread.start();
}
}
Code:
//Here are the relevant portions of the hosting Activity that connects to the service
//NOTE: THE FOLLOWING CODE IS PART OF THE ACTIVITY, NOT THE SERVICE
private ConnectionService conn;
private ServiceConnection mConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
conn = ((ConnectionService.ConnectionBinder)service).getService();
//debug toast
Toast.makeText(main_tab_page.this, "Connected", Toast.LENGTH_SHORT)
.show();
synchronized (_serviceConnWait) {
_serviceConnWait.notify();
}
}
@Override
public void onServiceDisconnected(ComponentName name) {
conn = null;//does this even run? Breakpoint here
}
};
@Override
protected void onSaveInstanceState(Bundle state){
super.onSaveInstanceState(state);
state.putParcelable("Server", server);
state.putString("Window", CurrentTabWindow.GetName());
//have to unbind, othewise we get that leaked service exception
unbindService(mConnection);
}
@Override
protected void onDestroy()
{
super.onDestroy();
if(this.isFinishing())
stopService(new Intent(this, ConnectionService.class));
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_tab_page);
localTabHost = (TabHost)findViewById(R.id.tabHostMain);
localTabHost.setup();
localTabHost.setOnTabChangedListener(new tabChange());
_serviceConnWait = new Object();
if(savedInstanceState == null)
{//initial startup, coming from Intent to start
//get server definition
server = (IRCServer)this.getIntent().getParcelableExtra(IRC_WINDOW);
server.addObserver(this);
AddTabView(server);
//this should only run the first time, all other calls to OnCreate should have something in SavedInstanceState
startService(new Intent(this, ConnectionService.class));
}
else
{
server = (IRCServer)savedInstanceState.getParcelable("Server");
String windowName = savedInstanceState.getString("Window");
//Add Needed Tabs
//Server
if(!(windowName.equals(server.GetName())))
AddTabView(server);
//channels
for(IRCChannel c : server.GetAllChannels())
if(!(windowName.equals(c.GetName())))
AddTabView(c);
//reset each view's text (handled by tabChange)
if(windowName.equals(server.GetName()))
SetCurrentTab(server.NAME);
else
SetCurrentTab(windowName);
ResetMainView(CurrentTabWindow.GetWindowTextSpan());
//Rebind to service
BindToService(new Intent(this, ConnectionService.class));
}
}
@Override
protected void onStart()
{
super.onStart();
final Intent ServiceIntent = new Intent(this, ConnectionService.class);
//check start connection service
final Thread serverConnect = new Thread(new Runnable() {
@Override
public void run() {
if(!BindToService(ServiceIntent))
return;
server.conn = conn;
conn.ConnectToServer(server);
server.StartReader();
if(server.START_CHANNEL != null && !server.START_CHANNEL.equals(""))
{
IRCChannel chan = server.FindChannel(server.START_CHANNEL);
if(chan != null)
{
AddTabView(chan);
}
else
{
server.JoinChannel(server.START_CHANNEL);
chan = server.FindChannel(server.START_CHANNEL);
AddTabView(chan);
}
}
}
});
serverConnect.start();
}
private boolean BindToService(Intent ServiceIntent)
{
int tryCount = 0;
bindService(ServiceIntent, mConnection, Context.BIND_AUTO_CREATE);
while(conn == null && tryCount < 10)
{
tryCount++;
try {
synchronized (_serviceConnWait) {
_serviceConnWait.wait(1500);
}
}
catch (InterruptedException e) {
//do nothing
}
}
return conn != null;
}
Logcat...well...there isn't really any exception thrown, the code runs just fine...except that it closes the socket. I suppose that counts as an exception. Whenever I run the socket write command It throws a "Socket Closed" exception at me. No other crash involved.

CountDownTimer problem

Hello! I'm new to this forum. I'm developing an Android app, I have some problems with the functionality of a timer and I don't figure out why. I would need some ideas.
In my application I have 2 activities: one is with the levels of a game, where you can chose between them and the second one is with the game itself. In the second activity I have a CountDownTimer which tells me when the game must finish. I have a progressBar assigned to that timer.
CountDownTimer mCountDownTimer; -global variable
In onCreate I have:
mProgressBar=(ProgressBar)findViewById(R.id.progressBar);
mProgressBar.setProgress(0);
mCountDownTimer=new CountDownTimer(90000,1000) {
int i=0;
@override
public void onTick(long millisUntilFinished) {
Log.v("Log_tag", "Tick of Progress" + i + millisUntilFinished);
i++;
mProgressBar.setProgress(i); }
@override
public void onFinish() {
i++;
mProgressBar.setProgress(i);
Intent in = new Intent(getApplicationContext(), MyActivity2.class);
startActivity(in);
}
};
mCountDownTimer.start();
I have also overriden the native back button from Android to go to the first activity, the one with the levels and there I try to stop the counter, but it doesn't seem to work at all. The counter doesn't stop, and the other functions don't work as well.
Here is the code:
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK)) { //Back key pressed
mCountDownTimer.cancel();
Intent in = new Intent(getApplicationContext(), MyActivity2.class);
startActivity(in);
mCountDownTimer.cancel();
return true;
}
return super.onKeyDown(keyCode, event);
}
public void onBackPressed(){
mCountDownTimer.cancel();
Intent in = new Intent(getApplicationContext(), MyActivity2.class);
startActivity(in);
return;
How could I solve this? Thank you so much!
Here is your problem:
CountDownTimer mCountDownTimer; -global variable
There are no global variables in Java, only instance variables. Since you didn't post your full code I'm going to make a few assumptions here...
public class myAwesomeTimerClass {
CountDownTimer mCountDownTimer;
// bla bla
}
Then in your second activity/class, you should refer to the class:
instead of:
mCountDownTimer.cancel();
try:
myAwesomeTimerClass.mCountDownTimer.cancel();
Good luck.

Categories

Resources