Unable to start Android Service - android

I am trying to make a build a simple service kinda facebook chathead but for some reason i am not able to start the service, whenever i click on the start service button nothing happens. if someone can help me here and tell me what am i doing wrong, i would really appreciate it. Thanks
FloatService.java
package com.example.justeen.floatexample;
import android.app.Service;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.os.IBinder;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
public class FloatService extends Service{
private WindowManager windowManager;
private ImageView floatIcon;
#Override public IBinder onBind(Intent intent) {
// Not used
return null;
}
#Override public void onCreate() {
super.onCreate();
windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
floatIcon = new ImageView(this);
floatIcon.setImageResource(R.drawable.android_head);
final WindowManager.LayoutParams params = new WindowManager.LayoutParams(
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.TYPE_PHONE,
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
PixelFormat.TRANSLUCENT);
params.gravity = Gravity.TOP | Gravity.LEFT;
params.x = 0;
params.y = 100;
windowManager.addView(floatIcon, params);
try {
floatIcon.setOnTouchListener(new View.OnTouchListener() {
private int initialX;
private int initialY;
private float initialTouchX;
private float initialTouchY;
#Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
initialX = params.x;
initialY = params.y;
initialTouchX = event.getRawX();
initialTouchY = event.getRawY();
return true;
case MotionEvent.ACTION_UP:
return true;
case MotionEvent.ACTION_MOVE:
params.x = initialX + (int) (event.getRawX() - initialTouchX);
params.y = initialY + (int) (event.getRawY() - initialTouchY);
windowManager.updateViewLayout(floatIcon, params);
return true;
}
return false;
}
});
} catch (Exception e) {
// TODO: handle exception
}
}
#Override
public void onDestroy() {
super.onDestroy();
if (floatIcon != null) windowManager.removeView(floatIcon);
}
}
Activity.Java
package com.example.justeen.floatexample;
import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.PopupWindow;
public class HelloWorldActivity extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_hello_world);
Bundle bundle = getIntent().getExtras();
if(bundle != null && bundle.getString("LAUNCH").equals("YES")) {
startService(new Intent(HelloWorldActivity.this, FloatService.class));
Button launch = (Button) findViewById(R.id.button1);
launch.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
startService(new Intent(HelloWorldActivity.this, FloatService.class));
}
});
Button stop = (Button) findViewById(R.id.button2);
stop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
stopService(new Intent(HelloWorldActivity.this, FloatService.class));
}
});
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_hello_world, menu);
return true;
}
}
Manifet.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.justeen.floatexample" >
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".HelloWorldActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name="com.example.justeen.floatexample.FloatService"
android:enabled="true">
</service>
</application>
</manifest>

You have to remove the bundle check since it is kind of a copy paste without sense. When the onCreate is called first in the main activity, the Bundle value will be null so this is not attaching the click listeners to your service. Remove the bundle check and everything will work.

Related

how over android navigation android studio with canvas?

i find this canvas that allows you to write geometrics form in your layout , i use this to cover the android status bar and the android notification bar and it worked so right now i want to cover , with another rectangle , the navigation bar but i can't achieve this goal.
i tried to change the hight of the top of the rectangle to be at the bottom of the screen but it didn't work because the rectangle remains at the top of the screen.
can you help me to move this rectangle to the bottom?
this is my customViewGroup :
package com.liliumduva;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.util.Log;
import android.view.MotionEvent;
import android.view.ViewGroup;
import android.view.WindowManager;
public class CustomViewGroup extends ViewGroup {
public CustomViewGroup(Context context) {
super(context);
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
Paint paint = new Paint();
// paint.setColor(Color.RED);
//canvas.drawRect(0, 0, getWidth(), getHeight() / 10, paint);
Rect rect = new Rect();
paint.setColor(Color.BLUE);
rect.left = 0;
rect.top = getHeight() - getHeight() / 10 - getStatusBarHeight();
rect.right = getWidth();
rect.bottom = getHeight() - getResources().getDimensionPixelSize(getResources().getIdentifier("navigation_bar_height", "dimen", "android"));
canvas.drawRect(rect, paint);
}
private int getStatusBarHeight() {
int result = 0;
int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
if (resourceId > 0) {
result = getResources().getDimensionPixelSize(resourceId);
}
return result;
}
#Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int width = MeasureSpec.getSize(widthMeasureSpec);
int height = MeasureSpec.getSize(heightMeasureSpec);
setMeasuredDimension(width, height);
}
#Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
Log.v("CustomViewGroup", "**********Intercepted");
return true;
}
}
and this is my main activity:
package com.liliumduva;
import android.app.Activity;
import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.PixelFormat;
import android.hardware.usb.UsbAccessory;
import android.hardware.usb.UsbManager;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import com.facebook.react.ReactActivity;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;
import com.facebook.react.ReactPackage;
import com.facebook.react.shell.MainReactPackage;
public class MainActivity extends ReactActivity {
#Override
protected String getMainComponentName() {
return "liliumDuva";
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
hideSystemUI();
//Remove notification bar
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
WindowManager manager = ((WindowManager) getApplicationContext()
.getSystemService(Context.WINDOW_SERVICE));
WindowManager.LayoutParams localLayoutParams = new WindowManager.LayoutParams();
localLayoutParams.type = WindowManager.LayoutParams.TYPE_SYSTEM_ERROR;
localLayoutParams.gravity = Gravity.TOP;
localLayoutParams.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE|
// this is to enable the notification to receive touch events
WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL |
// Draws over status bar
WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN;
localLayoutParams.width = WindowManager.LayoutParams.MATCH_PARENT;
localLayoutParams.height = (int) (35 * getResources()
.getDisplayMetrics().scaledDensity);
localLayoutParams.format = PixelFormat.TRANSPARENT;
CustomViewGroup view = new CustomViewGroup(this);
manager.addView(view, localLayoutParams);
manager = ((WindowManager) getApplicationContext()
.getSystemService(Context.WINDOW_SERVICE));
localLayoutParams = new WindowManager.LayoutParams();
localLayoutParams.type = WindowManager.LayoutParams.TYPE_SYSTEM_ERROR;
localLayoutParams.gravity = Gravity.BOTTOM;
localLayoutParams.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE|WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL |
WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN;
localLayoutParams.width = WindowManager.LayoutParams.MATCH_PARENT;
localLayoutParams.height = (int) (80 * getResources()
.getDisplayMetrics().scaledDensity);
localLayoutParams.format = PixelFormat.TRANSPARENT;
}
#Override
public void onBackPressed() {
// Define custom behavior for the back button here
}
#Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
if (keyCode==KeyEvent.KEYCODE_HOME)
return false;
if (keyCode==KeyEvent.KEYCODE_BACK)
return false;
if (keyCode==KeyEvent.KEYCODE_MENU)
return false;
if (keyCode==KeyEvent.KEYCODE_VOLUME_DOWN) {
return false;
}
if (keyCode==KeyEvent.KEYCODE_VOLUME_UP) {
return false;
}
if (keyCode==KeyEvent.KEYCODE_APP_SWITCH)
return false;
if (keyCode==KeyEvent.KEYCODE_ALL_APPS)
return false;
return super.onKeyUp(keyCode,event);
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
// nothing to do here
// … really
if (keyCode==KeyEvent.KEYCODE_HOME)
return false;
if (keyCode==KeyEvent.KEYCODE_BACK)
return false;
if (keyCode==KeyEvent.KEYCODE_MENU)
return false;
if (keyCode==KeyEvent.KEYCODE_APP_SWITCH)
return false;
if (keyCode==KeyEvent.KEYCODE_ALL_APPS)
return false;
return super.onKeyDown(keyCode,event);
}
public class RelaunchService extends Service {
private Notification mNotification;
private Timer mTimer;
public RelaunchService() {
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
startForeground(1, mNotification);
mTimer.schedule(new TimerTask() {
#Override
public void run() {
Intent intent = new Intent(RelaunchService.this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
}, 300);
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
stopForeground(true);
mTimer.cancel();
}
#Override
public IBinder onBind(Intent intent) {
throw new UnsupportedOperationException("Not yet implemented");
}
}
#Override
protected void onResume() {
super.onResume();
boolean exitAllowed = false;
Intent servIntent = new Intent(this, RelaunchService.class);
stopService(servIntent);
}
#Override
protected void onPause() {
super.onPause();
savePersistentData();
boolean exitAllowed = false;
if (!exitAllowed) {
Intent servIntent = new Intent(this, RelaunchService.class);
startService(servIntent);
}
}
private void savePersistentData() {
}
private void hideSystemUI() {
getWindow().getDecorView().setSystemUiVisibility(
View.SYSTEM_UI_FLAG_LAYOUT_STABLE
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
| View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_FULLSCREEN
| View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
}
#Override
public void onWindowFocusChanged(boolean hasFocus)
{
super.onWindowFocusChanged(hasFocus);
if(android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT && hasFocus)
{
hideSystemUI();
}
}
}

PinchToZoom not working with multiple activities in Android

I am trying to implement pinch to zoom, in my project i have used multiple activities which interconnect them. Initially when i had my complete project in one activity it was performing zoom, however it is not the case with multiple activities.
CODE: AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.kmay.calculatephase">
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:debuggable="true"
android:theme="#style/AppTheme" >
<activity android:name=".MainActivity" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".LoadImage" >
</activity>
<activity android:name=".Phase" >
</activity>
<activity android:name=".ColorGray" >
</activity>
<activity android:name=".Information" >
</activity>
</application>
CODE: MainActivity.java
package com.example.stiwari.myappli;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.InputStream;
public class MainActivity extends AppCompatActivity {
Button btn1;Bitmap imgb;Bitmap operation;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn1 = (Button) findViewById(R.id.btn1);
Bitmap bmp;
btn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent rawIntent = new Intent(Intent.ACTION_PICK);
File pictureDirectory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
String pictureDirectoryPath = pictureDirectory.getPath();
Uri data = Uri.parse(pictureDirectoryPath);
rawIntent.setDataAndType(data, "image/*");
startActivityForResult(rawIntent, 10);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode==RESULT_OK){
if(requestCode==10){
final float red = (float) 0.299;
final float green = (float) 0.587;
final float blue = (float) 0.114;
final Uri imagef = data.getData();
InputStream streamI;
try {
streamI = getContentResolver().openInputStream(imagef);
//Create bitmap from selected image
imgb = BitmapFactory.decodeStream(streamI);
//Define rows and columns of selected image
int rows = imgb.getHeight();int cols = imgb.getWidth();
operation = Bitmap.createBitmap(cols, rows, imgb.getConfig());
//Convert original image to Gray Image
for (int i=0;i<cols;i++){
for(int j=0;j<rows;j++){
int p = imgb.getPixel(i,j);
int r = Color.red(p);
int g = Color.green(p);
int b = Color.blue(p);
r = (int) (red*r);
g = (int) (green*g);
b = (int) (blue*b);
int gray = (int) (r*0.299+g*0.587+b*0.114);
operation.setPixel(i, j, Color.argb(Color.alpha(p), gray, gray, gray));
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();}
}
//Use Intent property to send data to Main2Activity.class
Intent i = new Intent(this,Main2Activity.class);
ByteArrayOutputStream bs = new ByteArrayOutputStream();
operation.compress(Bitmap.CompressFormat.PNG, 50, bs);
i.putExtra("byteArray", bs.toByteArray());
startActivity(i);
}
}
}
CODE: activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context=".MainActivity">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Next Page"
android:id="#+id/btn1"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
CODE:Main2Activity.java
package com.example.stiwari.myappli;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.MotionEvent;
import android.view.ScaleGestureDetector;
import android.view.View;
import android.widget.ImageView;
public class Main2Activity extends AppCompatActivity {
Bitmap imgb;
ImageView imageView1;float scaleFactor;View view;
ScaleGestureDetector detector;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
imageView1 = (ImageView) findViewById(R.id.imageView1);
detector = new ScaleGestureDetector(this, new ScaleListener());
if (getIntent().hasExtra("byteArray")) {
//ImageView previewThumbnail = new ImageView(this);
imgb = BitmapFactory.decodeByteArray(
getIntent().getByteArrayExtra("byteArray"), 0, getIntent().getByteArrayExtra("byteArray").length);
//previewThumbnail.setImageBitmap(imgb);
}imageView1.setImageBitmap(imgb);
imageView1.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
Main2Activity.this.view = v;
detector.onTouchEvent(event);
return false;
}
});
}
CODE: activity_main2.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context="com.example.stiwari.myappli.Main2Activity">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/imageView1"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
Use the below code for Pinch Zoom.
ScaleGestureDetector detector = new ScaleGestureDetector(this, new ScaleListener());
private class ScaleListener extends
ScaleGestureDetector.SimpleOnScaleGestureListener {
#Override
public boolean onScale(ScaleGestureDetector detector) {
scaleFactor *= detector.getScaleFactor();
scaleFactor = (scaleFactor < 1 ? 1 : scaleFactor);
scaleFactor = ((float) ((int) (scaleFactor * 100))) / 100;
view.setScaleX(scaleFactor);
view.setScaleY(scaleFactor);
return true;
}
}
Also,Setup a touchListener to you view on onCreate(The one which you want to zoom).
example
(YOUR_VIEW).setClickable(true);
(YOUR_VIEW).setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
MainActivity.this.view = v;
detector.onTouchEvent(event);
return false;
});
Hope this will help :)
UPDATE 1:
Based on your code.change condition like this
imageView1.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_UP) {
} else {
Main2Activity.this.view = v;
detector.onTouchEvent(event);
}
return false;
}
});

How to start popupwindow from service in android?

I wish to create a floating button which will hover over the entire Android screen. When the button or hovering icon is clicked, it should open a small popupwindow.
I was able to create the hovering icon using service class however I am unable to launch popupwindow. Whenever I click the floating icon, the error log says:
Caused by: android.view.WindowManager$BadTokenException: Unable to add window -- token null is not valid; is your activity running?
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.WindowManager.LayoutParams;
import android.widget.ImageView;
import android.widget.PopupWindow;
/**
* Created by sejal on 17-Oct-15.
*/
public class bubble extends Service{
PopupWindow popw;
private WindowManager windowManager;
private ImageView floatingFaceBubble;
public void onCreate() {
super.onCreate();
floatingFaceBubble = new ImageView(this);
//a face floating bubble as imageView
floatingFaceBubble.setImageResource(R.drawable.bubble);
windowManager = (WindowManager)getSystemService(WINDOW_SERVICE);
//here is all the science of params
final LayoutParams myParams = new LayoutParams(
LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT,
LayoutParams.TYPE_PHONE,
LayoutParams.FLAG_NOT_FOCUSABLE,
PixelFormat.TRANSLUCENT);
myParams.gravity = Gravity.TOP | Gravity.LEFT;
myParams.x=0;
// add a floatingfacebubble icon in window
windowManager.addView(floatingFaceBubble, myParams);
try{
floatingFaceBubble.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getpopuppwindow();
}
});
//for moving the picture on touch and slide
floatingFaceBubble.setOnTouchListener(new View.OnTouchListener() {
LayoutParams paramsT = myParams;
private int initialX;
private int initialY;
private float initialTouchX;
private float initialTouchY;
private long touchStartTime = 0;
#Override
public boolean onTouch(View v, MotionEvent event) {
//remove face bubble on long press
/* if(System.currentTimeMillis()-touchStartTime> ViewConfiguration.getLongPressTimeout() && initialTouchX== event.getX()){
//// windowManager.removeView(floatingFaceBubble);
//// stopSelf();
// return false;
// } */
switch(event.getAction()){
case MotionEvent.ACTION_DOWN:
touchStartTime = System.currentTimeMillis();
initialX = myParams.x;
initialY = myParams.y;
initialTouchX = event.getRawX();
initialTouchY = event.getRawY();
break;
case MotionEvent.ACTION_UP:
break;
case MotionEvent.ACTION_MOVE:
myParams.x = initialX + (int) (event.getRawX() - initialTouchX);
myParams.y = initialY + (int) (event.getRawY() - initialTouchY);
windowManager.updateViewLayout(v, myParams);
break;
}
return false;
}
});
} catch (Exception e){
e.printStackTrace();
}
}
//(ViewGroup) floatingFaceBubble.findViewById(R.id.pop)
private void getpopuppwindow() {
try {
System.out.print("111111");
LayoutInflater inflater = (LayoutInflater)bubble.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
System.out.print("222222");
View layout = inflater.inflate(R.layout.popup,(ViewGroup) floatingFaceBubble.findViewById(R.id.pop));
System.out.print("333333");
popw = new PopupWindow(layout ,300,100 ,true) ;
System.out.print("444444");
popw.showAtLocation(layout, Gravity.CENTER,0,0);
}
catch(Exception e)
{
e.printStackTrace();
}
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
You should not do these ui operations in your service class. Because after you show your button service instance will be removed and there is no context when you click the button. I think you should follow similar approach like below.
Service Class:
Intent activityIntent = new Intent(context, MainActivity);
activityIntent.putExtra("showPopup", true);
context.startActivity(activityIntent);
Activity Class:
onCreate(){
boolean showPopUp = getIntent().getBooleanExtra("showPopup", false);
if(showPopUp){
// Show your popup here
}
}

Cannot use this in Builder Android Service

I am trying to use a Bulider from a library that i have imported in my project but for some reason the Builder doesn't accept 'this' as Service context. if anyone can help me out i would truly appreciate it. Thanks
import android.app.Service;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Color;
import android.graphics.PixelFormat;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;
import com.oguzdev.circularfloatingactionmenu.library.FloatingActionMenu;
import com.oguzdev.circularfloatingactionmenu.library.FloatingActionButton;
import com.oguzdev.circularfloatingactionmenu.library.SubActionButton;
import com.example.andrew.reddit2go.R;
import java.util.Calendar;
/**
* Created by Justeen on 2015-02-26.
*/
public class FloatService extends Service {
private WindowManager windowManager;
public TextView textView;
private final IBinder mBinder = new LocalBinder();
private FloatingActionButton rightLowerButton;
private FloatingActionButton topCenterButton;
private FloatingActionMenu rightLowerMenu;
private FloatingActionMenu topCenterMenu;
private boolean serviceWillBeDismissed;
//keep track of an instance to communicate with
private static FloatService floatingInstance;
public class LocalBinder extends Binder {
FloatService getService() {
// Return this instance of LocalService so clients can call public methods
return FloatService.this;
}
}
public FloatService(){
}
#Override
public IBinder onBind(Intent intent) {
return mBinder;
}
#Override
public void onCreate() {
super.onCreate();
serviceWillBeDismissed = false;
floatingInstance = FloatService.this;
windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
textView = new TextView(this);
textView.setBackgroundResource(R.drawable.icon);
textView.setTypeface(null, Typeface.BOLD);
textView.setTextColor(Color.GRAY);
textView.setText("0");
Resources res = getResources();
Drawable shape = res.getDrawable(R.drawable.gradient_box);
//textView.findViewById(R.id.textView);
textView.setBackground(shape);
final WindowManager.LayoutParams params = new WindowManager.LayoutParams(
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.TYPE_PHONE,
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
PixelFormat.TRANSLUCENT);
params.gravity = Gravity.TOP | Gravity.LEFT;
params.x = 0;
params.y = 100;
windowManager.addView(textView, params);
try {
textView.setOnTouchListener(new View.OnTouchListener() {
private int initialX;
private int initialY;
private float initialTouchX;
private float initialTouchY;
private final int MAX_CLICK_DURATION = 200;
private long startClickTime;
#Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
initialX = params.x;
initialY = params.y;
initialTouchX = event.getRawX();
initialTouchY = event.getRawY();
startClickTime = Calendar.getInstance().getTimeInMillis();
return true;
case MotionEvent.ACTION_UP:
long clickDuration = Calendar.getInstance().getTimeInMillis() - startClickTime;
//if this is not a move, consider it a click and start the activity to see the posts
if(clickDuration < MAX_CLICK_DURATION) {
Intent activityStart = new Intent(getApplicationContext(), MainActivity.class);
activityStart.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(activityStart);
}
return true;
case MotionEvent.ACTION_MOVE:
params.x = initialX + (int) (event.getRawX() - initialTouchX);
params.y = initialY + (int) (event.getRawY() - initialTouchY);
windowManager.updateViewLayout(textView, params);
return true;
}
return false;
}
});
} catch (Exception e) {
// TODO: handle exception
}
rightLowerButton = new FloatingActionButton.Builder(this)
.setContentView(textView)
.setSystemOverlay(true)
.setLayoutParams(params)
.build();
}
#Override
public int onStartCommand( Intent intent , int flags , int startId ) {
super.onStartCommand(intent, flags, startId);
return START_REDELIVER_INTENT;
}
#Override
public void onDestroy() {
super.onDestroy();
if (textView != null) windowManager.removeView(textView);
floatingInstance = null;
}
//called to update the number on this ChatHead
public void updateUnreadNum(int unreadPosts){
if (null != textView) {
Log.d("Reddit2Go", "number of posts is: " + unreadPosts);
textView.setText(""+unreadPosts);
}
}
//called to update the list of available networks and the number on this ChatHead
public void updateUnreadNum(int unreadPosts, String networkList){
if (null != textView) {
Log.d("Reddit2Go", "number of posts is: " + unreadPosts);
//textView.setTextAlignment(TextView.TEXT_ALIGNMENT_CENTER);
textView.setGravity(Gravity.CENTER);
textView.setText(""+unreadPosts+" Cached\n" + networkList);
}
}
//get a reference to a running instance of this service
public static FloatService getFloatingInstance(){
return floatingInstance;
}
}

Moving image with touch events

I need a sample code for when we move(touch) a image from left to right and right to left. Please help me.
Regards,
chakri
try this code...
this is your main activity class
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.ImageView;
import android.widget.LinearLayout.LayoutParams;
import android.widget.RelativeLayout;
import android.support.v4.app.NavUtils;
public class MainActivity extends Activity {
ImageView imageView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = (ImageView)findViewById(R.id.imageView1);
imageView.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
int eid = event.getAction();
switch (eid) {
case MotionEvent.ACTION_MOVE:
RelativeLayout.LayoutParams mParams = (RelativeLayout.LayoutParams) imageView.getLayoutParams();
int x = (int) event.getRawX();
int y = (int) event.getRawY();
mParams.leftMargin = x-50;
mParams.topMargin = y-50;
imageView.setLayoutParams(mParams);
break;
default:
break;
}
return true;
}
});
}
}
main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="126dp"
android:layout_marginTop="168dp"
android:src="#drawable/ic_launcher" />
</RelativeLayout>

Categories

Resources