ImageView isn't visible and motion event isn't works well - android

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.

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();
}
}
}

Duplication of views using WindowManager

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

Android finish() method is not closing the app but minimizing it

I'm starting an activity from the background service by using following piece of code:
Intent intent = new Intent(getApplicationContext(),AlarmActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
But when I finish the activity by clicking the OK or Snooze button the app doesn't close but minimises instead.
When that minimised app is opened, the alarm starts ringing again until the app is closed manually.
I've tried by following commands as well but no gain.
android.os.Process.killProcess(android.os.Process.myPid());
System.exit(1);
What could be the issue?
ActivityCode:
import android.content.Context;
import android.graphics.Point;
import android.graphics.PorterDuff;
import android.media.AudioAttributes;
import android.media.AudioManager;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.PowerManager;
import android.os.Vibrator;
import android.support.annotation.RequiresApi;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.Display;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.ScaleAnimation;
import android.widget.ImageView;
import android.widget.TextView;
import com.solutionz.battery.saver.master.alarm.utils.AdInterstitial;
import com.solutionz.battery.saver.master.alarm.utils.AppGlobal;
import com.solutionz.battery.saver.master.alarm.utils.MySharedPreferences;
public class AlarmActivity extends AppCompatActivity {
Context context;
TextView title_tv, message_tv;
ImageView batteryIcon_iv;
TextView ok_tv, snooze_tv;
boolean isCharging;
Ringtone ringtone;
Vibrator vibrator;
Handler handler;
Runnable runnable;
PowerManager.WakeLock screenLock;
MySharedPreferences mySharedPreferences;
AdInterstitial adInterstitial;
long[] pattern = {1000, 500, 1000, 1000, 500};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_alarm);
mySharedPreferences = new MySharedPreferences(context);
adInterstitial = new AdInterstitial(context);
screenLock = ((PowerManager) getSystemService(POWER_SERVICE)).newWakeLock(
PowerManager.SCREEN_DIM_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP, "TAG");
screenLock.acquire();
setScreenSize();
setViews();
setContent();
setTimer();
adInterstitial.requestLoadInterstitial(false);
}
private void setScreenSize() {
// getting and setting the window size
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
// int width = (int) (size.x * 0.7);
// int height = (int) (size.y * 0.4);
WindowManager.LayoutParams params = getWindow().getAttributes();
params.gravity = Gravity.CENTER;
//params.height = height;
//params.width = width;
params.height = WindowManager.LayoutParams.WRAP_CONTENT;
params.width = WindowManager.LayoutParams.WRAP_CONTENT;
this.getWindow().setAttributes(params);
}
private void setViews() {
title_tv = (TextView) findViewById(R.id.title_tv);
message_tv = (TextView) findViewById(R.id.message_tv);
batteryIcon_iv = (ImageView) findViewById(R.id.batteryIcon_iv);
ok_tv = (TextView) findViewById(R.id.ok_tv);
snooze_tv = (TextView) findViewById(R.id.snooze_tv);
scaleView(batteryIcon_iv, 0.7f, 1.0f);
ok_tv.getCompoundDrawables()[1].mutate().setColorFilter(ContextCompat.getColor(context, R.color.white), PorterDuff.Mode.SRC_ATOP);
snooze_tv.getCompoundDrawables()[1].mutate().setColorFilter(ContextCompat.getColor(context, R.color.white), PorterDuff.Mode.SRC_ATOP);
ok_tv.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mySharedPreferences.SetLastNotifiedChargingState(isCharging);
mySharedPreferences.SetIsNotified(true);
finish();
//android.os.Process.killProcess(android.os.Process.myPid());
// System.exit(1);
}
});
snooze_tv.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mySharedPreferences.SetIsSnoozed(true);
finish();
//android.os.Process.killProcess(android.os.Process.myPid());
// System.exit(1);
}
}
});
}
private void setContent() {
Bundle bundle = getIntent().getBundleExtra("data");
title_tv.setText(bundle.getString("title"));
message_tv.setText(bundle.getString("message"));
isCharging = bundle.getBoolean("isCharging");
if (!isCharging) {
batteryIcon_iv.setImageDrawable(ContextCompat.getDrawable(context, R.drawable.ic_battery_30));
batteryIcon_iv.getDrawable().mutate().setColorFilter(ContextCompat.getColor(context, R.color.white), PorterDuff.Mode.SRC_ATOP);
} else {
batteryIcon_iv.setImageDrawable(ContextCompat.getDrawable(context, R.drawable.ic_battery_charging_80));
batteryIcon_iv.getDrawable().mutate().setColorFilter(ContextCompat.getColor(context, R.color.white), PorterDuff.Mode.SRC_ATOP);
}
// playAlarmTone();
mediaPlayerSetting();
}
public void scaleView(View v, float startScale, float endScale) {
Animation anim = new ScaleAnimation(
startScale, endScale, // Start and end values for the X axis scaling
startScale, endScale, // Start and end values for the Y axis scaling
Animation.RELATIVE_TO_SELF, 0.5f, // Pivot point of X scaling
Animation.RELATIVE_TO_SELF, 0.5f); // Pivot point of Y scaling
anim.setFillAfter(true); // Needed to keep the result of the animation
anim.setDuration(1000);
anim.setRepeatMode(Animation.REVERSE);
anim.setRepeatCount(Animation.INFINITE);
v.startAnimation(anim);
}
public void mediaPlayerSetting() {
AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
ringtone = RingtoneManager.getRingtone(getApplicationContext(), notification);
if (mySharedPreferences.GetIsSoundEnabled()) // Play sound
{
int volume = audioManager.getStreamVolume(AudioManager.STREAM_ALARM);
if (volume == 0)
volume = audioManager.getStreamMaxVolume(AudioManager.STREAM_ALARM);
audioManager.setStreamVolume(AudioManager.STREAM_ALARM, volume, AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);
ringtone = RingtoneManager.getRingtone(getApplicationContext(), notification);
if (ringtone != null) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
ringtone.setAudioAttributes(new AudioAttributes.Builder().setUsage(AudioAttributes.USAGE_ALARM).build());
} else {
ringtone.setStreamType(AudioManager.STREAM_ALARM);
}
ringtone.play();
}
}
if (mySharedPreferences.GetIsVibrationEnabled()) // Start vibration
{
vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
vibrator.vibrate(pattern, 0);
}
}
private void setTimer() {
handler = new Handler();
runnable = new Runnable() {
#RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
#Override
public void run() {
AppGlobal.showNotification(getApplicationContext(), title_tv.getText().toString(), message_tv.getText().toString());
AlarmActivity.this.finish();
}
};
handler.postDelayed(runnable, mySharedPreferences.GetAlarmDuration() * 1000);
}
#Override
protected void onDestroy() {
super.onDestroy();
if (ringtone != null && ringtone.isPlaying()) ringtone.stop();
if (vibrator != null) vibrator.cancel();
handler.removeCallbacks(runnable);
screenLock.release();
}
}
In Android finish() method is not closing the app but minizing it
No. First of all there's no concept of "minimizing" apps on Android, and finish() is NOT closing the main app process, but only finished the activity.

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;
}
}

The View.OnSystemUiVisibilityChangeListener is not work in android Service

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.

Categories

Resources