I have build an app where I need to show card on an incoming call. It works fine in Kitkat, but in Android L, M, N the card appears twice, why?
Result (Kitkat)
Result (Lollipop-Nougat-Marshmallow)
My code
package tutorials.hackro.com.callincoming;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.PixelFormat;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
/**
* Created by hackro on 4/03/17.
*/
public class MyPhoneBroadcastReceiver extends BroadcastReceiver {
private WindowManager wm;
private WindowManager.LayoutParams params;
private LinearLayout ly;
private View view;
private TextView lblCelular,nameContact;
private Button btnExpediente;
private int height;
private Context context;
private String number;
private Display display;
private LayoutInflater mInflater;
private Bundle bundle;
private TelephonyManager telephony;
private boolean callincoming;
public void onReceive(final Context cc, Intent intent) {
this.context= cc;
bundle = intent.getExtras();
number = bundle.getString("incoming_number");
intializeElements();
initializeUI();
initializeValuesElements();
events();
telephony = (TelephonyManager) context
.getSystemService(Context.TELEPHONY_SERVICE);
telephony.listen(phoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);
}
private PhoneStateListener phoneStateListener = new PhoneStateListener() {
public void onCallStateChanged(int state, String incomingNumber) {
if (state == TelephonyManager.CALL_STATE_RINGING) {
if(!callincoming){
wm.addView(ly, params);
Log.e("a","a");
callincoming = !callincoming;
}
}
if (state == TelephonyManager.CALL_STATE_OFFHOOK) {
System.exit(0);
}
if (state == TelephonyManager.CALL_STATE_IDLE) {
System.exit(0);
}
}
};
private void intializeElements() {
wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
ly = new LinearLayout(context);
mInflater = LayoutInflater.from(context);
view = mInflater.inflate(R.layout.call,null);
display = wm.getDefaultDisplay();
height = display.getHeight();
initializeParams();
ly.addView(view,params);
}
public void events(){
ly.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);
wm.updateViewLayout(ly, params);
return true;
}
return false;
}
});
btnExpediente.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
params.height = 0;
ly.removeView(view);
wm.updateViewLayout(ly,params);
Intent i = new Intent(context,Main2Activity.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
}
});
}
public static String getContactName(Context context, String phoneNumber) {
ContentResolver cr = context.getContentResolver();
Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(phoneNumber));
Cursor cursor = cr.query(uri, new String[]{ContactsContract.PhoneLookup.DISPLAY_NAME}, null, null, null);
if (cursor == null) {
return null;
}
String contactName = null;
if(cursor.moveToFirst()) {
contactName = cursor.getString(cursor.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME));
}
if(cursor != null && !cursor.isClosed()) {
cursor.close();
}
return contactName;
}
private void initializeParams(){
params = new WindowManager.LayoutParams(
WindowManager.LayoutParams.MATCH_PARENT,
WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.TYPE_SYSTEM_ALERT |
WindowManager.LayoutParams.TYPE_SYSTEM_OVERLAY,
WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL |
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
PixelFormat.TRANSPARENT);
int SDK_INT = android.os.Build.VERSION.SDK_INT;
if(SDK_INT >= Build.VERSION_CODES.KITKAT && SDK_INT <= Build.VERSION_CODES.LOLLIPOP){
params.height = (height/2);
}
else if(SDK_INT >= Build.VERSION_CODES.LOLLIPOP && SDK_INT <= Build.VERSION_CODES.M){
params.height = (height/4) + (height/15);
}
else if(SDK_INT >= Build.VERSION_CODES.M && SDK_INT <= Build.VERSION_CODES.N){
params.height = (height/4) + (height/15);
}
else if(SDK_INT >= Build.VERSION_CODES.N){
params.height = (height/4) + (height/15);
}
params.height = (height/2);
params.width = WindowManager.LayoutParams.MATCH_PARENT;
params.gravity = Gravity.TOP;
params.format = PixelFormat.TRANSLUCENT;
}
public void initializeUI(){
lblCelular = (TextView) view.findViewById(R.id.lblCelular);
nameContact= (TextView) view.findViewById(R.id.nameContact);
btnExpediente = (Button) view.findViewById(R.id.btnExpediente);
}
public void initializeValuesElements(){
nameContact.setText(getContactName(context,number));
lblCelular.setText(number);
}
public void onDestroy() {
telephony.listen(null, PhoneStateListener.LISTEN_NONE);
}
}
I solved my problem.
The problem is multiple call onReceive
SOLUTION
public static final String TAG = "PHONE STATE";
private static String mLastState;
String state = intent.getStringExtra(TelephonyManager.EXTRA_STATE);
if (!state.equals(mLastState)) {
mLastState = state;
Log.e(TAG, state);
telephony = (TelephonyManager) context
.getSystemService(Context.TELEPHONY_SERVICE);
telephony.listen(phoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);
}
You can see more details here
Related
I am trying to implement the app similar to true caller,I am able to get the phone number when the phone rings using broadcast receiver and opening the MyCustomDialog Activity
This is my receiver class by which I am getting the Call State that the call is starts or ends. In this, I make some methods which I am using in CallReceiver.java
PhonecallReceiver.java
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.telephony.TelephonyManager;
import java.util.Date;
public abstract class PhonecallReceiver extends BroadcastReceiver
{
private static int lastState = TelephonyManager.CALL_STATE_IDLE;
private static Date callStartTime;
private static boolean isIncoming;
private static String savedNumber;
#Override
public void onReceive(Context context, Intent intent)
{
try
{
if (intent.getAction().equals("android.intent.action.NEW_OUTGOING_CALL"))
{
savedNumber = intent.getExtras().getString("android.intent.extra.PHONE_NUMBER");
}
else
{
String stateStr = intent.getExtras().getString(TelephonyManager.EXTRA_STATE);
String number = intent.getExtras().getString(TelephonyManager.EXTRA_INCOMING_NUMBER);
int state = 0;
if(stateStr.equals(TelephonyManager.EXTRA_STATE_IDLE))
{
state = TelephonyManager.CALL_STATE_IDLE;
}
else if(stateStr.equals(TelephonyManager.EXTRA_STATE_OFFHOOK))
{
state = TelephonyManager.CALL_STATE_OFFHOOK;
}
else if(stateStr.equals(TelephonyManager.EXTRA_STATE_RINGING))
{
state = TelephonyManager.CALL_STATE_RINGING;
}
onCallStateChanged(context, state, number);
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
//Derived classes should override these to respond to specific events of interest
protected void onIncomingCallStarted(Context ctx, String number, Date start){}
protected void onIncomingCallEnded(Context ctx, String number, Date start, Date end){}
public void onCallStateChanged(Context context, int state, String number)
{
if(lastState == state)
{
//No change, debounce extras
return;
}
switch (state)
{
case TelephonyManager.CALL_STATE_RINGING:
isIncoming = true;
callStartTime = new Date();
savedNumber = number;
onIncomingCallStarted(context, number, callStartTime);
break;
case TelephonyManager.CALL_STATE_OFFHOOK:
if (isIncoming)
{
onIncomingCallEnded(context,savedNumber,callStartTime,new Date());
}
case TelephonyManager.CALL_STATE_IDLE:
if(isIncoming)
{
onIncomingCallEnded(context, savedNumber, callStartTime, new Date());
}
}
lastState = state;
}
}
CallReceiver.java
import android.app.Activity;
import android.app.Dialog;
import android.app.Notification;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.Toast;
import android.os.Handler;
import java.util.Date;
import dootam.dspl.com.lawyercasecall.R;
public class CallReceiver extends PhonecallReceiver
{
Context context;
#Override
protected void onIncomingCallStarted(final Context ctx, String number, Date start)
{
Toast.makeText(ctx,"Kushal Incoming Call"+ number,Toast.LENGTH_LONG).show();
context = ctx;
final Intent intent = new Intent(context, MyCustomDialog.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
intent.putExtra("phone_no",number);
new Handler().postDelayed(new Runnable()
{
#Override
public void run()
{
context.startActivity(intent);
}
},2000);
// MyCus/*tomDialog dialog = new MyCustomDialog(context);
// dialog.*/show();
}
#Override
protected void onIncomingCallEnded(Context ctx, String number, Date start, Date end)
{
Toast.makeText(ctx,"Bye Bye"+ number,Toast.LENGTH_LONG).show();
}
}
MyCustomDialog.java
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.TextView;
import dootam.dspl.com.lawyercasecall.R;
public class MyCustomDialog extends Activity
{
TextView tv_client;
String phone_no;
Button dialog_ok;
#Override
protected void onCreate(Bundle savedInstanceState)
{
try
{
requestWindowFeature(Window.FEATURE_NO_TITLE);
this.setFinishOnTouchOutside(false);
super.onCreate(savedInstanceState);
setContentView(R.layout.dialog);
initializeContent();
/*WindowManager.LayoutParams params = getWindow().getAttributes();
params.x = -100;
params.height = 70;
params.width = 1000;
params.y = -50;
this.getWindow().setAttributes(params);*/
phone_no = getIntent().getExtras().getString("phone_no");
tv_client.setText(""+phone_no +" is calling you");
dialog_ok.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
MyCustomDialog.this.finish();
// this.setFinishOnTouchOutside(false);
System.exit(0);
}
});
}
catch (Exception e)
{
Log.d("Exception", e.toString());
e.printStackTrace();
}
}
private void initializeContent()
{
tv_client = (TextView) findViewById(R.id.tv_client);
dialog_ok = (Button) findViewById(R.id.dialog_ok);
}
}
My AndroidManifest.xml
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".AddCasesActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".receiver.MyCustomDialog"
android:theme="#android:style/Theme.Dialog"
android:noHistory="true"
/>
<receiver android:name=".receiver.CallReceiver" >
<intent-filter>
<action android:name="android.intent.action.PHONE_STATE" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.NEW_OUTGOING_CALL" />
</intent-filter>
</receiver>
</application>
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.PROCESS_OUTGOING_CALLS"/>
<uses-permission android:name="android.permission.MODIFY_PHONE_STATE" tools:ignore="ProtectedPermissions"/>
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
By implementing all this stuff I am getting the desired output
Please guide me how to make this activity dialog dragable like the popup of the truecaller app.
I am searching for the dialog similar to this image ,
It is possible through OnTouchListener, Try this https://github.com/andreilisun/Swipe-To-Dismiss-Dialog
The Dialog is draggable, I have changed the SwipeDimissDialog to remove dismissal of Dialog in the following class -
public class SwipeDismissDialog extends FrameLayout {
private final Params params;
private View dialog;
protected SwipeDismissDialog(#NonNull Context context, Params params) {
super(context);
this.params = params;
init();
}
private void init() {
setOnClickListener(overlayClickListener);
setBackgroundColor(params.overlayColor);
dialog = params.view;
if (dialog == null) {
dialog = LayoutInflater.from(getContext()).inflate(params.layoutRes, this, false);
}
LayoutParams layoutParams = (LayoutParams) dialog.getLayoutParams();
if (layoutParams == null) {
layoutParams = new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT, Gravity.CENTER);
} else {
layoutParams.gravity = Gravity.CENTER;
}
dialog.setOnTouchListener(touchListener);
addView(dialog, layoutParams);
}
#Override
public boolean dispatchKeyEvent(KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN
&& event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
cancel();
return true;
}
return false;
}
public SwipeDismissDialog show() {
WindowManager windowManager = (WindowManager)
getContext().getSystemService(Context.WINDOW_SERVICE);
WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams();
layoutParams.height = WindowManager.LayoutParams.MATCH_PARENT;
layoutParams.width = WindowManager.LayoutParams.MATCH_PARENT;
layoutParams.type = WindowManager.LayoutParams.TYPE_APPLICATION;
layoutParams.format = PixelFormat.TRANSLUCENT;
windowManager.addView(this, layoutParams);
return this;
}
public void cancel() {
if (params.cancelListener != null) {
params.cancelListener.onCancel(dialog);
}
if (params.dismissOnCancel) {
dismiss();
}
}
public void dismiss() {
dialog.setOnTouchListener(null);
removeView(dialog);
WindowManager windowManager = (WindowManager)
getContext().getSystemService(Context.WINDOW_SERVICE);
windowManager.removeViewImmediate(this);
}
private void dismiss(SwipeDismissDirection direction) {
if (params.swipeDismissListener != null) {
params.swipeDismissListener.onSwipeDismiss(this, direction);
}
dismiss();
}
private final OnTouchListener touchListener = new OnTouchListener() {
private float initCenterX;
private float lastEventY;
private float lastEventX;
private float initY;
private float initX;
public boolean onTouch(View view, MotionEvent motionEvent) {
/*Fling detected*/
int action = motionEvent.getAction();
switch (action) {
case MotionEvent.ACTION_DOWN: {
initX = view.getX();
initY = view.getY();
lastEventX = motionEvent.getRawX();
lastEventY = motionEvent.getRawY();
initCenterX = initX + view.getWidth() / 2;
break;
}
case MotionEvent.ACTION_MOVE: {
float eventX = motionEvent.getRawX();
float eventY = motionEvent.getRawY();
float eventDx = eventX - lastEventX;
float eventDy = eventY - lastEventY;
float centerX = view.getX() + eventDx + view.getWidth() / 2;
float centerDx = centerX - initCenterX;
view.setX(view.getX() + eventDx);
view.setY(view.getY() + eventDy);
//view.invalidate();
lastEventX = eventX;
lastEventY = eventY;
break;
}
}
return true;
}
};
private final OnClickListener overlayClickListener = new OnClickListener() {
#Override
public void onClick(View v) {
cancel();
}
};
public static class Builder {
private final Params params;
private final Context context;
public Builder(Context context) {
this.context = context;
this.params = new Params();
}
public Builder setView(#NonNull View view) {
params.view = view;
params.layoutRes = 0;
return this;
}
public Builder setLayoutResId(#LayoutRes int layoutResId) {
params.layoutRes = layoutResId;
params.view = null;
return this;
}
public SwipeDismissDialog build() {
if (params.view == null && params.layoutRes == 0) {
throw new IllegalStateException("view should be set with setView(View view) " +
"or with setLayoutResId(int layoutResId)");
}
return new SwipeDismissDialog(context, params);
}
}
}
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;
}
}
I was wondering whether to display SystemUI and Listenering. The window is created in Service
package com.example.testwindow;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.PixelFormat;
import android.os.IBinder;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.WindowManager.LayoutParams;
import com.android.internal.policy.PolicyManager;
public class WindowManagerService extends Service {
private String TAG ="WindowManagerService";
private Context mContext;
private WindowManager mWindowManager;
private Window mWindow;
#Override
public void onCreate() {
super.onCreate();
Log.i(TAG, "onCreate view");
this.mWindowManager = ((WindowManager) getSystemService("window"));
mContext = this;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
int i = super.onStartCommand(intent, flags, startId);
View editWindow = LayoutInflater.from(mContext).inflate(R.layout.activity_main, null);
mWindow = addWindow(editWindow, 0, 0, LayoutParams.TYPE_PHONE);
int mSystemUiVisibility = mWindow.getDecorView().getSystemUiVisibility();
mWindow.getDecorView().setOnSystemUiVisibilityChangeListener(new View.OnSystemUiVisibilityChangeListener(){
#Override
public void onSystemUiVisibilityChange(int visibility) {
Log.e(TAG,"systemUI onSystemUiVisibilityChange ="+visibility);
}
});
Log.e(TAG, "mSystemUiVisibility ="+mSystemUiVisibility);
WindowManager.LayoutParams layoutParams = mWindow.getAttributes();
layoutParams.x = 0;
layoutParams.y = 0;
layoutParams.width = 500;
layoutParams.height = 600;
layoutParams.gravity = Gravity.TOP | Gravity.LEFT;
layoutParams.hasSystemUiListeners = true;
layoutParams.setTitle("WindowManagerService");
mWindow.setAttributes(layoutParams);
mWindowManager.updateViewLayout(mWindow.getDecorView(), layoutParams);
return i;
}
public WindowManager.LayoutParams createLayoutParams() {
Log.i(TAG , "createLayoutParams");
WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams(
LayoutParams.TYPE_SYSTEM_ERROR,
LayoutParams.FLAG_NOT_FOCUSABLE,
PixelFormat.TRANSLUCENT);
layoutParams.softInputMode = LayoutParams.SOFT_INPUT_ADJUST_PAN;
layoutParams.setTitle(getClass().getName());
return layoutParams;
}
public Window addWindow(View paramView, int width, int height,
int type) {
Log.i(TAG, "addWindow view");
WindowManager.LayoutParams layoutParams = createLayoutParams();
Window localWindow = PolicyManager.makeNewWindow(this.mContext);
if (localWindow != null) {
localWindow.setWindowManager(this.mWindowManager, null, null);
localWindow.requestFeature(Window.FEATURE_NO_TITLE);
localWindow.setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
layoutParams.width = width;
layoutParams.height = height;
layoutParams.type = type;
layoutParams.format= PixelFormat.TRANSPARENT;
layoutParams.flags = (LayoutParams.FLAG_NOT_FOCUSABLE | layoutParams.flags);
localWindow.setAttributes(layoutParams);
localWindow.setContentView(paramView);
View localView = localWindow.getDecorView();
if (localView != null) {
localView.setVisibility(View.VISIBLE);
this.mWindowManager.addView(localView, layoutParams);
}
return localWindow;
}
return null;
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onDestroy() {
if (mWindow != null) {
mWindowManager.removeView(mWindow.getDecorView());
mWindow = null;
}
super.onDestroy();
}
}
When I start service,Other App changed to FULLSCREEN or not ,I can't get the log "systemUI onSystemUiVisibilityChange ="
Can someone explain the behaviour? Why can't listener the change?
You can try to add the listener before calling addView.
Is there some way to implement drag and drop functionality in API 8 Android?
Looked here, but it appears after API 11.
I need to drag view from one LinearLayout to another. Ho can i implement this on API 8?
Try like this
import android.app.Activity;
import android.content.ClipData;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.Rect;
import android.os.Bundle;
import android.view.DragEvent;
import android.view.View;
import android.view.View.DragShadowBuilder;
import android.view.View.OnDragListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
public class MainActivity extends Activity {
ListView source = null;
TextView target1 = null;
TextView target2 = null;
TextView target3 = null;
String[] listItems = {"Samsung", "Apple", "Google", "Nokia"};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
source = (ListView)findViewById(R.id.dragSource);
target1 = (TextView) findViewById(R.id.dragTarget1);
target2 = (TextView) findViewById(R.id.dragTarget2);
target3 = (TextView) findViewById(R.id.dragTarget3);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, listItems);
source.setAdapter(adapter);
// Start Drag
source.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
String item = listItems[position];
ClipData data = ClipData.newPlainText("DragIt", item);
source.startDrag(data, new MyShadowBuilder(view), null, 0);
}
});
// Handle Drag
target1.setOnDragListener(new MyDragListener());
target2.setOnDragListener(new MyDragListener());
target3.setOnDragListener(new MyDragListener());
}
// Drag Shadow
private class MyShadowBuilder extends DragShadowBuilder {
public MyShadowBuilder(View v) {
super(v);
}
#Override
public void onDrawShadow(Canvas canvas) {
// Set Drag image background or anything you want
int width = getView().getWidth();
int height = getView().getHeight();
Paint paint = new Paint();
paint.setColor(0x55858585);
canvas.drawRect(new Rect(0, 0, width, height), paint);
super.onDrawShadow(canvas);
}
#Override
public void onProvideShadowMetrics(Point shadowSize,
Point shadowTouchPoint) {
int width = getView().getWidth();
int height = getView().getHeight();
shadowSize.set(width, height);
shadowTouchPoint.set(width/2, height);
}
}
// Drag Listener
private class MyDragListener implements OnDragListener {
private final int DEFAULT_BG_COLOR = 0xFF858585;
private final int HIGHLIGHT_BG_COLOR = 0xFF0000FF;
#Override
public boolean onDrag(View v, DragEvent event) {
if(event.getAction() == DragEvent.ACTION_DRAG_ENTERED) {
v.setBackgroundColor(HIGHLIGHT_BG_COLOR);
}
else if(event.getAction() == DragEvent.ACTION_DRAG_EXITED) {
v.setBackgroundColor(DEFAULT_BG_COLOR);
}
else if(event.getAction() == DragEvent.ACTION_DROP) {
// Perform drop
ClipData clip = event.getClipData();
ClipData.Item item = clip.getItemAt(0);
String text = item.getText().toString();
((TextView) v).setText(text);
v.setBackgroundColor(DEFAULT_BG_COLOR);
}
// Send true to listen All Drag Events.
return true;
}
}
}
XML is like:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal" >
<LinearLayout
android:layout_width="161dp"
android:layout_height="fill_parent"
android:background="#FF858585"
android:orientation="vertical" >
<TextView
android:id="#+id/dragTarget1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="0.04"
android:text="Drop Here"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/dragTarget2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="0.04"
android:text="Drop Here"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/dragTarget3"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="0.04"
android:text="Drop Here"
android:textAppearance="?android:attr/textAppearanceLarge" />
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:orientation="vertical" >
<ListView
android:id="#+id/dragSource"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
</LinearLayout>
Try another approach by using WindowManager :
package com.example.cooldraganddrop;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.PixelFormat;
import android.graphics.drawable.BitmapDrawable;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ImageView;
public class CoolDragAndDropGridView extends SpanVariableGridView implements `View.OnTouchListener {`
private static final int ITEM_HOVER_DELAY = 450;
private int mDragPointX;
private int mDragPointY;
private int mDragOffsetX;
private int mDragOffsetY;
private int mDragPosition = AdapterView.INVALID_POSITION;
private int mDropPosition = AdapterView.INVALID_POSITION;
private int mCurrentPosition = AdapterView.INVALID_POSITION;
private Runnable mDelayedOnDragRunnable = null;
ScrollingStrategy mScrollingStrategy = null;
WindowManager mWindowManager = null;
WindowManager.LayoutParams mWindowParams = null;
private ImageView mDragImageView = null;
private boolean mDragAndDropStarted = false;
private DragAndDropListener mDragAndDropListener = null;
private OnTrackTouchEventsListener mOnTrackTouchEventsListener = null;
public static interface OnTrackTouchEventsListener {
void trackTouchEvents(final MotionEvent motionEvent);
};
public static interface DragAndDropListener {
void onDragItem(int from);
void onDraggingItem(int from, int to);
void onDropItem(int from, int to);
boolean isDragAndDropEnabled(int position);
}
public CoolDragAndDropGridView(Context context) {
super(context);
initialize();
}
public CoolDragAndDropGridView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
initialize();
}
public CoolDragAndDropGridView(Context context, AttributeSet attrs) {
super(context, attrs);
initialize();
}
private void initialize() {
setOnTouchListener(this);
setChildrenDrawingOrderEnabled(true);
}
public void startDragAndDrop() {
mDragAndDropStarted = true;
}
public void setDragAndDropListener(DragAndDropListener dragAndDropListener) {
mDragAndDropListener = dragAndDropListener;
}
private void destroyDragImageView() {
if (mDragImageView != null) {
mWindowManager.removeView(mDragImageView);
BitmapDrawable bitmapDrawable = (BitmapDrawable) mDragImageView.getDrawable();
if (bitmapDrawable != null) {
final Bitmap bitmap = bitmapDrawable.getBitmap();
if (bitmap != null && !bitmap.isRecycled()) {
bitmap.recycle();
}
}
mDragImageView.setImageDrawable(null);
mDragImageView = null;
}
}
private ImageView createDragImageView(final View v, final int x, final int y) {
v.destroyDrawingCache();
v.setDrawingCacheEnabled(true);
Bitmap bm = Bitmap.createBitmap(v.getDrawingCache());
mDragPointX = x - v.getLeft();
mDragPointY = y - v.getTop();
mWindowParams = new WindowManager.LayoutParams();
mWindowParams.gravity = Gravity.TOP | Gravity.LEFT;
mWindowParams.x = x - mDragPointX + mDragOffsetX;
mWindowParams.y = y - mDragPointY + mDragOffsetY;
mWindowParams.height = WindowManager.LayoutParams.WRAP_CONTENT;
mWindowParams.width = WindowManager.LayoutParams.WRAP_CONTENT;
mWindowParams.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE
| WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON | WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN;
mWindowParams.format = PixelFormat.TRANSLUCENT;
mWindowParams.alpha = 0.7f;
mWindowParams.windowAnimations = 0;
ImageView iv = new ImageView(getContext());
iv.setBackgroundColor(Color.parseColor("#ff555555"));
iv.setImageBitmap(bm);
mWindowManager = (WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE);// "window"
mWindowManager.addView(iv, mWindowParams);
return iv;
}
private void startDrag(final int x, final int y) {
final View v = getChildAt(mDragPosition);
destroyDragImageView();
mDragImageView = createDragImageView(v, x, y);
v.setVisibility(View.INVISIBLE);
if (mDragAndDropListener != null) {
mDragAndDropListener.onDragItem(mDragPosition);
}
}
#Override
protected int getChildDrawingOrder(int childCount, int i) {
if (mCurrentPosition == -1)
return i;
else if (i == childCount - 1)
return mCurrentPosition;
else if (i >= mCurrentPosition)
return i + 1;
return i;
}
private void onDrop() {
destroyDragImageView();
removeCallbacks(mDelayedOnDragRunnable);
View v = getChildAt(mDropPosition);
v.setVisibility(View.VISIBLE);
v.clearAnimation();
if (mDragAndDropListener != null && mDropPosition != AdapterView.INVALID_POSITION) {
mDragAndDropListener.onDropItem(mDragPosition, mDropPosition);
}
mDragPosition = mDropPosition = mCurrentPosition = AdapterView.INVALID_POSITION;
mDragAndDropStarted = false;
}
public void setScrollingStrategy(ScrollingStrategy scrollingStrategy) {
mScrollingStrategy = scrollingStrategy;
}
private void onDrag(final int x, final int y) {
if (mScrollingStrategy != null && mScrollingStrategy.performScrolling(x, y, this)) {
removeCallbacks(mDelayedOnDragRunnable);
return;
}
final int tempDropPosition = pointToPosition(mCurrentPosition, x, y);
if (mDragAndDropListener != null && mDropPosition != tempDropPosition && tempDropPosition != AdapterView.INVALID_POSITION) {
removeCallbacks(mDelayedOnDragRunnable);
if (mDragAndDropListener.isDragAndDropEnabled(tempDropPosition)) {
mDropPosition = tempDropPosition;
mDelayedOnDragRunnable = new Runnable() {
#Override
public void run() {
mDragAndDropListener.onDraggingItem(mCurrentPosition, tempDropPosition);
performDragAndDropSwapping(mCurrentPosition, tempDropPosition);
final int nextDropPosition = pointToPosition(tempDropPosition, x, y);
if (nextDropPosition == AdapterView.INVALID_POSITION) {
mCurrentPosition = mDropPosition = tempDropPosition;
}
}
};
postDelayed(mDelayedOnDragRunnable, ITEM_HOVER_DELAY);
} else {
mDropPosition = mDragPosition;
}
}
if (mDragImageView != null) {
mWindowParams.x = x - mDragPointX + mDragOffsetX;
mWindowParams.y = y - mDragPointY + mDragOffsetY;
mWindowManager.updateViewLayout(mDragImageView, mWindowParams);
}
}
public void setOnTrackTouchEventListener(OnTrackTouchEventsListener onTrackTouchEventsListener) {
mOnTrackTouchEventsListener = onTrackTouchEventsListener;
}
#Override
public boolean onInterceptTouchEvent(MotionEvent event) {
if (mOnTrackTouchEventsListener != null) {
mOnTrackTouchEventsListener.trackTouchEvents(event);
}
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
case MotionEvent.ACTION_MOVE:
if (mDragAndDropListener != null && mDragAndDropStarted) {
mDragAndDropStarted = false;
getParent().requestDisallowInterceptTouchEvent(true);
return launchDragAndDrop(event);
}
break;
default:
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL:
mDragAndDropStarted = false;
getParent().requestDisallowInterceptTouchEvent(false);
break;
}
return super.onInterceptTouchEvent(event);
}
private boolean launchDragAndDrop(final MotionEvent event) {
final int x = (int) event.getX();
final int y = (int) event.getY();
mCurrentPosition = mDragPosition = mDropPosition = pointToPosition(mDragPosition, x, y);
if (mDragPosition != AdapterView.INVALID_POSITION && mDragAndDropListener.isDragAndDropEnabled(mDragPosition)) {
mDragOffsetX = (int) (event.getRawX() - x);
mDragOffsetY = (int) (event.getRawY() - y);
startDrag(x, y);
return true;
}
return false;
}
#Override
public boolean onTouch(View view, MotionEvent event) {
if (mDragPosition != AdapterView.INVALID_POSITION && mDragImageView != null) {
final int x = (int) event.getX();
final int y = (int) event.getY();
switch (event.getAction()) {
case MotionEvent.ACTION_MOVE:
mDragOffsetX = (int) (event.getRawX() - x);
mDragOffsetY = (int) (event.getRawY() - y);
onDrag(x, y);
break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL:
onDrop();
resetLongClickTransition();
getParent().requestDisallowInterceptTouchEvent(false);
return false;
default:
}
return true;
}
return false;
}
}
Sample using this approach of a drag and drop is here
i'm writing service class that has image overlay
imageView overlay was visible, but it isn't visible after i added imageview resize code.
Also, MotionEvent for resized imageview isn't works well
Why imageview overlay isn't visible and MotionEvent isn't works well?
Could you help me to solve this problem?
here's my code
This code show ImageView overlay which isn't resized,
it is visible and MotionEvent works well
package kr.hybdms.sidepanel;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.Intent;
import android.net.Uri;
import android.os.IBinder;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.WindowManager;
import android.widget.ImageView;
import android.graphics.PixelFormat;
public class TouchDetectService extends Service {
private ImageView mTouchDetector;
private WindowManager.LayoutParams mParams;
private WindowManager mWindowManager;
private static final int MY_NOTIFICATION_ID=1;
private NotificationManager notificationManager;
private Notification myNotification;
final static String ACTION = "NotifyServiceAction";
final static String STOP_SERVICE = "";
final static int RQS_STOP_SERVICE = 1;
private OnTouchListener mViewTouchListener = new OnTouchListener() {
#Override public boolean onTouch(View v, MotionEvent event) {
switch(event.getAction()) {
case MotionEvent.ACTION_MOVE:
Intent lsp = new Intent(getBaseContext(), SidePanel.class);
lsp.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
getApplication().startActivity(lsp);
break;
}
return true;
}
};
#Override
public IBinder onBind(Intent arg0) { return null; }
#Override
public void onCreate() {
super.onCreate();
boolean rightpanel = getSharedPreferences(getPackageName() + "_preferences", Context.MODE_PRIVATE).getBoolean("panelpos_right", true);
boolean notificationison = getSharedPreferences(getPackageName() + "_preferences", Context.MODE_PRIVATE).getBoolean("noti_toggle", true);
Log.i("BOOTSVC", "Service started at the BOOT_COMPLETED.");
if(rightpanel)
{
mTouchDetector = new ImageView(this);
mTouchDetector.setImageResource(R.drawable.detector);
mTouchDetector.setOnTouchListener(mViewTouchListener);
mParams = new WindowManager.LayoutParams(
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.TYPE_PHONE,
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
PixelFormat.TRANSLUCENT);
mParams.gravity = Gravity.RIGHT | Gravity.CENTER;
mWindowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
mWindowManager.addView(mTouchDetector, mParams);
}
else
{
mTouchDetector = new ImageView(this);
mTouchDetector.setImageResource(R.drawable.detector);
mTouchDetector.setOnTouchListener(mViewTouchListener);
mParams = new WindowManager.LayoutParams(
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.TYPE_PHONE,
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
PixelFormat.TRANSLUCENT);
mParams.gravity = Gravity.LEFT | Gravity.CENTER;
mWindowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
mWindowManager.addView(mTouchDetector, mParams);
}
if(notificationison){
notificationManager =
(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
myNotification = new Notification(R.drawable.ic_stat_sidepanel,
getText(R.string.service_notification),
System.currentTimeMillis());
Context context = getApplicationContext();
CharSequence notificationTitle = getText(R.string.service_running);
CharSequence notificationText = getText(R.string.service_running_desc);
Intent myIntent = new Intent(getBaseContext(), Settings.class);;
PendingIntent pendingIntent
= PendingIntent.getActivity(getBaseContext(),
0, myIntent,
Intent.FLAG_ACTIVITY_NEW_TASK);
myNotification.defaults |= Notification.DEFAULT_SOUND;
myNotification.flags |= Notification.FLAG_AUTO_CANCEL;
myNotification.flags = Notification.FLAG_ONGOING_EVENT;
myNotification.setLatestEventInfo(context,
notificationTitle,
notificationText,
pendingIntent);
notificationManager.notify(MY_NOTIFICATION_ID, myNotification);
}
else
{
}
}
#Override
public void onDestroy() {
if(mWindowManager != null) {
if(mTouchDetector != null) mWindowManager.removeView(mTouchDetector);
}
super.onDestroy();
notificationManager.cancel(MY_NOTIFICATION_ID);
}
}
This code show ImageView overlay which resized,
it isn't visible and MotionEvent isn't works well
imageview is resizes by preference value
package kr.hybdms.sidepanel;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.IBinder;
import android.os.Vibrator;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.WindowManager;
import android.widget.ImageView;
import android.graphics.PixelFormat;
public class TouchDetectService extends Service {
private ImageView mTouchDetector;
private WindowManager.LayoutParams mParams;
private WindowManager mWindowManager;
private static final int MY_NOTIFICATION_ID=1;
private NotificationManager notificationManager;
private Notification myNotification;
final static String ACTION = "NotifyServiceAction";
final static String STOP_SERVICE = "";
final static int RQS_STOP_SERVICE = 1;
private OnTouchListener mViewTouchListener = new OnTouchListener() {
#Override public boolean onTouch(View v, MotionEvent event) {
switch(event.getAction()) {
case MotionEvent.ACTION_MOVE:
boolean vibeon = getSharedPreferences(getPackageName() + "_preferences", Context.MODE_PRIVATE).getBoolean("vibe_toggle", true);
if(vibeon){
Vibrator vibe = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
vibe.vibrate(10);}
else{}
Intent lsp = new Intent(getBaseContext(), SidePanel.class);
lsp.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
getApplication().startActivity(lsp);
break;
}
return true;
}
};
#Override
public IBinder onBind(Intent arg0) { return null; }
#Override
public void onCreate() {
super.onCreate();
boolean rightpanel = getSharedPreferences(getPackageName() + "_preferences", Context.MODE_PRIVATE).getBoolean("panelpos_right", true);
boolean notificationison = getSharedPreferences(getPackageName() + "_preferences", Context.MODE_PRIVATE).getBoolean("noti_toggle", true);
Log.i("BOOTSVC", "Service started at the BOOT_COMPLETED.");
SharedPreferences myPreference = PreferenceManager.getDefaultSharedPreferences(this);
String dw = myPreference.getString("detector_width", "");
String dh = myPreference.getString("detector_height", "");
mTouchDetector = new ImageView(this);
mTouchDetector.setImageResource(R.drawable.detector);
mTouchDetector.setOnTouchListener(mViewTouchListener);
WindowManager.LayoutParams params = new WindowManager.LayoutParams();
if(dw.equals("025")){
params.height = (int) (mTouchDetector.getDrawable().getIntrinsicWidth()*0.25);
}
else if(dw.equals("050")){
params.height = (int) (mTouchDetector.getDrawable().getIntrinsicWidth()*0.5);
}
else if(dw.equals("075")){
params.height = (int) (mTouchDetector.getDrawable().getIntrinsicWidth()*0.75);
}
else if(dw.equals("100")){
params.height = mTouchDetector.getDrawable().getIntrinsicWidth();
}
else if(dw.equals("200")){
params.height = mTouchDetector.getDrawable().getIntrinsicWidth()*2;
}
else if(dw.equals("300")){
params.height = mTouchDetector.getDrawable().getIntrinsicWidth()*3;
}
else if(dw.equals("400")){
params.height = mTouchDetector.getDrawable().getIntrinsicWidth()*4;
}
if (dh.equals("025")){
params.width = (int) (mTouchDetector.getDrawable().getIntrinsicHeight()*0.25);
}
else if (dh.equals("050")){
params.width = (int) (mTouchDetector.getDrawable().getIntrinsicHeight()*0.5);
}
else if (dh.equals("075")){
params.width = (int) (mTouchDetector.getDrawable().getIntrinsicHeight()*0.75);
}
else if (dh.equals("100")){
params.width = mTouchDetector.getDrawable().getIntrinsicHeight();
}
else if (dh.equals("200")){
params.width = mTouchDetector.getDrawable().getIntrinsicHeight()*2;
}
else if (dh.equals("300")){
params.width = mTouchDetector.getDrawable().getIntrinsicHeight()*3;
}
else if (dh.equals("400")){
params.width = mTouchDetector.getDrawable().getIntrinsicHeight()*4;
}
params.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
params.format = PixelFormat.TRANSLUCENT;
params.type = WindowManager.LayoutParams.TYPE_PHONE;
if(rightpanel)
{
params.gravity = Gravity.RIGHT & Gravity.CENTER;
}
else
{
params.gravity = Gravity.LEFT & Gravity.CENTER;
}
mWindowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
mWindowManager.addView(mTouchDetector, params);
if(notificationison){
notificationManager =
(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
myNotification = new Notification(R.drawable.ic_stat_sidepanel,
getText(R.string.service_notification),
System.currentTimeMillis());
Context context = getApplicationContext();
CharSequence notificationTitle = getText(R.string.service_running);
CharSequence notificationText = getText(R.string.service_running_desc);
Intent myIntent = new Intent(getBaseContext(), Settings.class);;
PendingIntent pendingIntent
= PendingIntent.getActivity(getBaseContext(),
0, myIntent,
Intent.FLAG_ACTIVITY_NEW_TASK);
myNotification.defaults |= Notification.DEFAULT_SOUND;
myNotification.flags |= Notification.FLAG_AUTO_CANCEL;
myNotification.flags = Notification.FLAG_ONGOING_EVENT;
myNotification.setLatestEventInfo(context,
notificationTitle,
notificationText,
pendingIntent);
notificationManager.notify(MY_NOTIFICATION_ID, myNotification);
}
else
{
}
}
#Override
public void onDestroy() {
if(mWindowManager != null) {
if(mTouchDetector != null) mWindowManager.removeView(mTouchDetector);
}
super.onDestroy();
notificationManager.cancel(MY_NOTIFICATION_ID);
}
}
The code that you are complaining about isn't adding the ImageView - mTouchDetector - to your layout. You must add it in order for it to be visible if you are using plain Java instead of XML. Look at your first example (the working one):
mWindowManager.addView(mTouchDetector, mParams);
That's the idea here.