livewallpaper Double Tap to open an activity - android

I am new in android development.
I want to implement a double tap event in my wallpaper so that when I double tap the wallpaper it opens the application.
here is the code where I have drawn the wallpaper image:
public class AbcService extends WallpaperService
{
public void onCreate()
{
super.onCreate();
}
public void onDestroy()
{
super.onDestroy();
}
public Engine onCreateEngine()
{
return new wallpaperEngine();
}
class wallpaperEngine extends Engine
{
public Bitmap image1;
wallpaperEngine()
{
image1 = BitmapFactory.decodeResource(getResources(), R.drawable.img_3);
}
public void onCreate(SurfaceHolder surfaceHolder)
{
super.onCreate(surfaceHolder);
}
public void onOffsetsChanged(float xOffset, float yOffset, float xStep, float yStep, int xPixels, int yPixels)
{
drawFrame();
}
void drawFrame()
{
final SurfaceHolder holder = getSurfaceHolder();
Canvas c = null;
try
{
c = holder.lockCanvas();
if (c != null)
{
c.drawBitmap(image1, 0, 0, null);
}
} finally
{
if (c != null) holder.unlockCanvasAndPost(c);
}
}
}
what to do now??
am i on right track?
Thank You in Advance..

For a double Tap Action in a Live Wallpaper you can subclass a GestureDetector.SimpleOnGestureListener like this :
class wallpaperEngine extends Engine {
...
...
private GestureDetector gestureListener;
private class GestureListener extends GestureDetector.SimpleOnGestureListener {
#Override
public boolean onDoubleTap(MotionEvent e) {
//start intent/application here
return super.onDoubleTap(e);
}
}
Then create an Instance of that class, f.e. in your onCreate(SurfaceHolder surfaceHolder) Method and enable touch events in your Live Wallpaper :
public void onCreate(SurfaceHolder surfaceHolder) {
super.onCreate(surfaceHolder);
gestureListener = new GestureDetector(getApplicationContext(), new GestureListener());
setTouchEventsEnabled(true);
}
Then #Override onTouchEvent :
#Override
public void onTouchEvent(MotionEvent event) {
gestureListener.onTouchEvent(event);
}
Thats the easiest way I can think of.

Related

Android - Implement security in WallpaperService

I am using the WallpaperService class to set a live wallpaper on the device.
I want to implement security on the system screen (to prevent screenshot or recording) where the 'Set Wallpaper' button shows up by the android system.
So far, I have found one method of SurfaceView class - surfaceview.setSecure(boolean value)
But, I am not able to get the instance of the SurfaceView inside my class.
Please suggest some workaround to get the instance of this class.
My Code-
public class LiveWallpaperService extends WallpaperService {
private int mDeviceWidth, mDeviceHeight;
private int mAnimationWidth, mAnimationHeight;
#Override
public Engine onCreateEngine() {
Movie movie = null;
// Some Code here
return new GIFWallpaperEngine(movie);
}
private class GIFWallpaperEngine extends Engine {
private final int frameDuration = 24;
private SurfaceHolder holder;
private final Movie movie;
private boolean visible;
private final Handler handler;
private final Runnable drawGIF = new Runnable() {
public void run() {
draw();
}
};
public SurfaceView getSurfaceView(){
// How to find the SurfaceView object here?
}
GIFWallpaperEngine(Movie movie) {
this.movie = movie;
handler = new Handler();
}
#Override
public void onCreate(SurfaceHolder surfaceHolder) {
super.onCreate(surfaceHolder);
this.holder = surfaceHolder;
}
#Override
public void onSurfaceChanged(SurfaceHolder holder, int format, int width, int height) {
super.onSurfaceChanged(holder, format, width, height);
mDeviceWidth = width;
mDeviceHeight = height;
}
private void draw() {
if (movie != null) {
try {
if (visible) {
Canvas canvas = holder.lockCanvas();
canvas.save();
final float scaleFactorX = mDeviceWidth / (mAnimationWidth * 1.f); //608 is image width
final float scaleFactorY = mDeviceHeight / (mAnimationHeight * 1.f);
// Adjust size and position to fit animation on the screen
canvas.scale(scaleFactorX, scaleFactorY); // w,h Size of displaying Item
movie.draw(canvas, 0, 0); // position on x,y
canvas.restore();
holder.unlockCanvasAndPost(canvas);
movie.setTime((int) (System.currentTimeMillis() % movie.duration()));
handler.removeCallbacks(drawGIF);
handler.postDelayed(drawGIF, frameDuration);
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
#Override
public void onVisibilityChanged(boolean visible) {
this.visible = visible;
if (visible) {
handler.post(drawGIF);
} else {
handler.removeCallbacks(drawGIF);
}
}
#Override
public void onDestroy() {
super.onDestroy();
handler.removeCallbacks(drawGIF);
}
}
}

SurfaceView and xml

I have program where i use my SurfaceView class. But i want to add ad in my game.To do it i must add xml and use it (i never use xml file and know few about it). Help me pls whith it.
Main Activity on create:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ThisActivity=this;
new Game(this);
setContentView(Game.game);
}
Game:
public class S_Game extends SurfaceView implements CallBack{
public S_Game(Context context){
super(context);
getHolder().addCallback(this);
game=this;
sinh0=false;
sinh1=false;
sinh2=true;
String abas=" "+"";
spacekey=abas.hashCode();
paint=new Paint();
paint.setColor(0xffff0000);
paint.setTextSize(20);
pickx=new AtomicInteger[3];
picky=new AtomicInteger[3];
ifpick0=new AtomicBoolean[3];
for(int i=0;i<3;i++){
pickx[i]=new AtomicInteger();
picky[i]=new AtomicInteger();
ifpick0[i]=new AtomicBoolean();
}
pickt=new AtomicInteger();
NewTimer();
}
public void NewTimer(){
upd=new S_Updater(this);
timer=new Timer();
timer.schedule(upd,250,40);
}
public void Init(){
if(getHeight()>getWidth()){
S_Graff.thisindgraff=0;
}else{
S_Graff.thisindgraff=1;
}
DisplayMetrics metrics = new DisplayMetrics();
MainActivity.ThisActivity.getWindowManager().getDefaultDisplay().getMetrics(metrics);
xdpi=SK(metrics.xdpi);
ydpi=SK(metrics.ydpi);
xdpi=SK(metrics.densityDpi);
float sm=xdpi/3;
float sms=(55/sm);
dpi=sms;
wind=new S_Window(0,0,760,1430);
Board.psize=KonK(18);
Board.DY/=sms;
if(dpi<=0.55){
dpi=0.55f;
}
String s="|";
Board.LINE=s.hashCode();
}
public void Update(Canvas cnv){
if(getHeight()>getWidth()){
maxx=smaxx;
maxy=smaxy;
kx=maxx/getWidth();
ky=maxy/getHeight();
kk=kx;
S_Graff.thisindgraff=0;
debug0=""+maxy+"/"+getHeight();
debug1=""+maxx+"/"+getWidth();
}else{
maxx=smaxy;
maxy=smaxx;
kx=maxx/getWidth();
ky=maxy/getHeight();
kk=ky;
S_Graff.thisindgraff=1;
}
if(binit){LInit();binit=false;}
for(int i=0;i<3;i++){
if(!ifpick0[i].get()){
float px=pickx[i].get();
px/=1000;
float py=picky[i].get();
py/=1000;
ifpick0[i].set(true);
S_Window.Pick(px,py,i);
}
}
S_Graff.OnRotAll();
cnv.drawColor(0xffffffff);
//I draw all S_Graffs in Update
S_Graff.Update(cnv);
Board.UpdateText(cnv);
}
#Override
public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2, int arg3) {}
#Override
public void surfaceCreated(SurfaceHolder holder) {
//new Timer().schedule(upd,250,40);
/*Canvas c = getHolder().lockCanvas();
Update(c);
getHolder().unlockCanvasAndPost(c);*/
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
}
}
S_Updater:
public class S_Updater extends TimerTask{
public S_Game game;
public SurfaceHolder surfaceHolder;
static boolean isrun=true,ispause;
public S_Updater(S_Game g) {
game=g;
surfaceHolder=g.getHolder();
}
#Override
public void run() {
Canvas canvas=null;
try {
synchronized (surfaceHolder) {
if(surfaceHolder.getSurface().isValid()){
canvas=surfaceHolder.lockCanvas(null);
if(canvas!=null){
game.Update(canvas);
surfaceHolder.unlockCanvasAndPost(canvas);
}
}
}
}
finally {}
}
}

Refreshing canvas?

I try to display one from list of bitmaps during onDraw.
When i'm passing list to the canvas all are display and stay in their places.
When I pass one random bitmaps it's redrawing canvas all the time.
All works when i'm using public void drawEnemy(Canvas canvas) but not exactly like I want when using public void drawEn(Canvas canvas).
I want to display one random bitmap, then after a few seconds, delete it and display other bitmap. I think the problem is how I implemented onDrow() method. It's redrawing canvas all the time.
Activity:
public class NewGameActivity extends Activity{
NewGame newgame;
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
// Landscape mode
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
// no title
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
// content Newgame.java
newgame = new NewGame(this);
setContentView(newgame);
}
Thread:
public class MainThread extends Thread{
private SurfaceHolder surfaceHolder;
private NewGame screen;
public MainThread(SurfaceHolder surfaceHolder, NewGame ekran) {
super();
this.surfaceHolder = surfaceHolder;
this.screen= screen;
}
private boolean running;
public void setRunning(boolean running) {
this.running = running;
}
#Override
public void run() {
Canvas canvas;
while (running) {
canvas = null;
try {
canvas = this.surfaceHolder.lockCanvas();
synchronized (surfaceHolder) {
this.screen.onDraw(canvas);
}
} finally {
if (canvas != null) {
surfaceHolder.unlockCanvasAndPost(canvas);
}
}
}
}
}
SurfaceView:
public class NewGame extends SurfaceView implements SurfaceHolder.Callback{
private MainThread thread;
private EnemyManager manager;
public NewGame(Context context) {
super(context);
getHolder().addCallback(this);
thread = new MainThread(getHolder(), this);
manager = new EnemyManager();
// TODO Auto-generated constructor stub
//adding enemy
Enemy e1 = new Enemy(BitmapFactory.decodeResource(getResources(), R.drawable.card), 1);
Enemy e2 = new Enemy(BitmapFactory.decodeResource(getResources(), R.drawable.horse), 2);
EnemyLocation l1 = new EnemyLocation(60, 180);
EnemyLocation l2 = new EnemyLocation(60, 50);
manager.AddEnemy(e1, l1);
manager.AddEnemy(e2, l2);
setFocusable(true);
}
#Override
protected void onDraw(Canvas canvas) {
canvas.drawBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.saloon), 0, 0, null);
manager.drawEn(canvas);
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
// TODO Auto-generated method stub
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
thread.setRunning(true);
thread.start();
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
thread.setRunning(false);
thread.stop();
}
#Override
public boolean onTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
manager.handleActionDown((int)event.getX(), (int)event.getY());
}
return true;
}
}
EnemyManager:
public class EnemyManager {
private ArrayList<Enemy> enemyList;
private ArrayList<Enemy> suspects;
private Enemy cow;
private String message;
private int suspectID;
private Random rnd;
public String getMessage() {
return message;
}
public EnemyManager(){
enemyList = new ArrayList<Enemy>();
suspects = new ArrayList<Enemy>();
}
public void AddEnemy(Enemy enemy, EnemyLocation loc){
// set x,y enemy localization
enemy.setX(loc.getX());
enemy.setY(loc.getY());
enemyList.add(enemy);
}
public void clearEnemy() {
enemyList.clear();
}
// message if enemy touched
public void handleActionDown(int x, int y) {
for (Enemy enemy: enemyList) {
if (enemy.wasTouched(x, y)) {
message = enemy.getId();
return;
}
}
}
public void PrepareEnemy(){
suspectID = enemyList.get(rnd.nextInt(enemyList.size()+1)).getId();
suspects = new ArrayList<Enemy>();
suspects.add(getSuspectByID(suspectID));
}
private Enemy SingleEnemy(){
Double i = 1 + Math.random() * ((enemyList.size()-1)+1);
cow = getSuspectByID(i.intValue());
return cow;
}
private Enemy getSuspectByID(int suspectID) {
for (Enemy s: enemyList) {
if (s.getId() == suspectID) {
return s;
}
}
return null;
}
public void drawEn(Canvas canvas){
try {
Enemy k = SingleEnemy();
canvas.drawBitmap(cow.picture, cow.x, cow.y, null);
} catch (Exception e) {
// TODO: handle exception
}
}
// draw enemy
public void drawEnemy(Canvas canvas) {
try {
for (Enemy enemy: enemyList) {
canvas.drawBitmap(enemy.picture, enemy.x, enemy.y, null);
}
} catch (Exception e) {
// TODO: handle exception
}
}
}
das
As for as understand you are trying to do something like this (if it's not, please correct me):
This is rendering the canvas with all components:
Draw background
Draw enemy
To "refresh" the canvas you simply do something like this:
Draw background
Update
To pause the rendering you could do something like this:
int lastUpdateTime;
int delayTime = 2000; 2 seconds
if(System.currenttimeMillis() > lastUpdateTime + delayTime) {
// Finished waiting
}
You should only define lastUpdateTime when you want to wait and not in every iteration.
NB: Don't call Thread.sleep() in a rendering thread!

How can I change the picture that draws on the screen

This might seem like a silly qustion but how do you change the picture that draws on the screen.I have already been able to program a app were it draws a little icon where you touch the screen.So natually after I completed that I want to make it better by adding a option menu and the ability to change what icon you were being drown but when I ran the code the icon picture stayed the same.When I looked at it I found that when you click on any of the menu item it does do it's job and change the image id but when you go back to the main screen and try to create a new image it revertes back to the old image.I have no idea why it doesn't change because when I look at it everything make sense for it to change icon properly.If any one has any idea on what i am doing wrong or any suggestion on how to do this it would be greatly appreciate
Main
public class main extends Activity {
/** Called when the activity is first created. */
MenuItem item2;
int item3=R.drawable.ic_launcher;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FrameLayout sv = new FrameLayout(this);
LinearLayout ll = new LinearLayout(this);
Panel test = new Panel(this);
//ImageButton button = new ImageButton(this);
ll.setOrientation(LinearLayout.VERTICAL);
sv.addView(test);
//ll.addView(button);
sv.addView(ll);
setContentView(sv);
}
public boolean onCreateOptionsMenu(Menu menu) {
// TODO Auto-generated method stub
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
Log.v("test", "item3 before is: "+item3);
item3=R.drawable.box;
Log.v("test", "item3 after is: "+item3);
return super.onOptionsItemSelected(item);
}
}
Panel
public class Panel extends SurfaceView implements SurfaceHolder.Callback {
private Bitmap image;
private ViewThread mThread;
private int x;
private int y;
private ArrayList<Element> mElements = new ArrayList<Element>();
public Panel(Context context) {
super(context );
image = BitmapFactory.decodeResource(getResources(),yantz.imageapp4.R.drawable.test);
getHolder().addCallback(this);
mThread = new ViewThread(this);
}
public void doDraw(Canvas canvas) {
canvas.drawColor(Color.CYAN);
canvas.drawBitmap(image, x, y, null);
synchronized (mElements){
for(Element element : mElements){
element.doDraw(canvas);
}
}
}
#Override
public boolean onTouchEvent(MotionEvent event) {
// TODO Auto-generated method stub
Log.v("test", "you have touched the sreen: ");
synchronized (mElements){
mElements.add(new Element(getResources(),(int) event.getX(),(int) event.getY()));
}
return super.onTouchEvent(event);
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
// TODO Auto-generated method stub
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
if (!mThread.isAlive()) {
mThread = new ViewThread(this);
mThread.setRunning(true);
mThread.start();
}
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
if (mThread.isAlive()) {
mThread.setRunning(false);
}
}
}
Elements
public class Element extends main{
private int mX;
private int mY;
int location ;
private Bitmap mBitmap;
public Element(Resources res, int x, int y) {
Log.v("element", "item3 before location is: "+item3);
location =item3;
mBitmap = BitmapFactory.decodeResource(res, location);
mX = x - mBitmap.getWidth() / 2;
mY = y - mBitmap.getHeight() / 2;
Log.v("element", "item3 before location is: "+item3);
}
public void doDraw(Canvas canvas) {
canvas.drawBitmap(mBitmap, mX, mY, null);
}
public void setlocation(int location2){
location=location2;
}
}
ViewThread
public class ViewThread extends Thread {
private Panel mPanel;
private SurfaceHolder mHolder;
private boolean mRun = false;
public ViewThread(Panel panel) {
mPanel = panel;
mHolder = mPanel.getHolder();
}
public void setRunning(boolean run) {
mRun = run;
}
#Override
public void run() {
Canvas canvas = null;
while (mRun) {
canvas = mHolder.lockCanvas();
if (canvas != null) {
mPanel.doDraw(canvas);
mHolder.unlockCanvasAndPost(canvas);
}
}
}
}
you can use
#Override
protected void onResume() {
super.onResume();
id="what ever you want";
//and set it to imagevIew;
}
if i have understood the uestion correctly,this happens because your activity pauses when it is not focused and resumes with default values.

Problem in displaying Bitmaps on canvas

I am have some bitmaps which i want to display serially one after another but my code displays only last bitmap.Can anybody tell me why is it happening?
here is the code
class Panel extends SurfaceView implements SurfaceHolder.Callback {
private boolean _run = false;
public Panel(Context context) {
super(context);
getHolder().addCallback(this);
_run = true;
}
#Override
public void onDraw(Canvas canvas) {
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
Log.i("Read","surfaceChanged is called");
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
Log.i("Read","surfaceCreated is called");
while (_run ) {
display();
}
}
public void display() {
Canvas c;
c = null;
try {
c = getHolder().lockCanvas(null);
synchronized (getHolder()) {
onPreviewFrame();
invalidate();
c.drawColor(Color.BLACK);
c.drawBitmap(bmp, 10, 10, null);
//panel.surfaceDestroyed(panel.getHolder());
}
} finally {
if (c != null) {
getHolder().unlockCanvasAndPost(c);
}
}
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
Log.i("Read","surfaceDestroyed is called");
_run = false;
}
}
I am not sure what your requirement is but if your are trying to create a continous horizontal image scroll. Take a look at this
https://github.com/blessenm/SlideshowDemo

Categories

Resources