[Q] How to register a listener inside the AccessibilityService? - Java for Android App Development

I'd like to register a listener inside AccessibilityService extented class but I don't know how to achieve that as I don't have a instance of it (it is started using intent). Or maybe there is another way of getting callback from this class? I just want to notify another class when the "onAccessibilityEven()" is trigerred.
Code:
public class NotifyService extends AccessibilityService {
// declaration of the interface
public interface Listener {
public void onNotifyChange(boolean newNotification);
}
// registration of the listener
public void registerListener(Listener listener) {
mListener = listener;
}
// ...
@Override
public void onAccessibilityEvent(AccessibilityEvent event) {
if(mListener != null) {
mListener.onNotifyChange(true);
}
}
}

Can you build an handler in the other class? If yes, just send a message and the handler in the other class will receive it If you need an example I will write it.

Do you mean the same handler which is usually used for communicating between threads? If you could give me some example would be great.

Related

[Q] AlertDialog (-> list with a lot of elements) how to handle orientation-change

Hi,
A few weeks ago I started developing an Android app but I've gut one problem
If the user changed the orientation of his phone the Activity is of course newly created. If there is ProgressDialog opened, I simply open a new one and the user does not realize it, but if I show an AlertDialog containing a few hundred elements and the user scrolls a bit he/she will realize it after I recreate the AlertDialog because the dialog will start again with the first element and the user has to scroll newly to the element he wants.
How I handle the "ListDialog":
At first I have two classes which simplify the ListDialog because I use it a few times...
ListDialog class:
Code:
public class ListDialog {
public static int CHOOSE_MODE_ONLINE = 0x01;
public static int CHOOSE_MODE_BOOKMARK = 0x02;
public static int CHOOSE_MODE_LOCAL = 0x03;
public static int CHOOSE_CHAPTER_ONLINE_DOWNLOAD = 0x04;
public static int CHOOSE_CHAPTER_BOOKMARK_DOWNLOAD = 0x05;
public static int CHOOSE_CHAPTER_ONLINE_READ = 0x06;
public static int CHOOSE_CHAPTER_BOOKMARK_READ = 0x07;
public static int CHOOSE_CHAPTER_LOCAL_READ = 0x08;
public static int CHOOSE_CHAPTER_LOCAL_DELETE = 0x09;
public static int GOTO_PAGE = 0x0A;
public static void show(Context context, String title, CharSequence[] elems, final ListMethodInvoker invoker)
{
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle(title);
builder.setItems(elems, new DialogInterface.OnClickListener() {
%mail%Override
public void onClick(DialogInterface dialog, int which) {
invoker.invoke(which);
}
});
builder.setOnCancelListener(new OnCancelListener() {
%mail%Override
public void onCancel(DialogInterface dialog) {
invoker.cancel();
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
}
ListMethodInvoker class:
Code:
public class ListMethodInvoker {
public void invoke(int id)
{
}
public void cancel()
{
}
}
and now I create the dialog:
Code:
ApplicationController.get().addOpenedDialog(ListDialog.CHOOSE_MODE_ONLINE);
ListDialog.show(OnlineActivity.this,
mangaController.getManga().getMangaName(),
new CharSequence[]{"Add to Bookmarks", "Download a Chapter", "Read a Chapter"},
new ListMethodInvoker()
{
%mail%Override
public void invoke(int id)
{
ApplicationController.get().removeOpenedDialog(ListDialog.CHOOSE_MODE_ONLINE);
switch(id)
{
case 0: addBookmark(mangaController.getManga()); break;
case 1:
ApplicationController.get().addOpenedDialog(ListDialog.CHOOSE_CHAPTER_ONLINE_DOWNLOAD);
handleChapter(ChapterMode.Download);
break;
case 2:
ApplicationController.get().addOpenedDialog(ListDialog.CHOOSE_CHAPTER_ONLINE_READ);
handleChapter(ChapterMode.Read);
break;
}
}
%mail%Override
public void cancel()
{
ApplicationController.get().removeOpenedDialog(ListDialog.CHOOSE_MODE_ONLINE);
}
});
I also add the ID of the dialog to my ApplicationController which allows me to remember if a dialog has been openend and I can recreate it when onCreate(...) is called again.
(The ApplicationController uses the singleton design pattern which always allows me to retrieve the same instance of the ApplicationController.)
Thanks in advance
best regards
mike
btw: If you wonder why I write %mail% instead of the correct symbol, I get the following exception message if I use it: To prevent spam to the forums, new users are not permitted to post outside links in their messages. All new user accounts will be verified by moderators before this restriction is removed.

[Q] Why cant I call a method from another class?

I have 2 classes in one .java file and it runs fine without errors or anything (the second class is used as a timer and changes variables every second) everything works but it wont call methods properly. Any idea of why this would be??? Heres my code of the second class.
Code:
class MyTime extends TimerTask{
//java.text.DateFormat format = SimpleDateFormat.getTimeInstance(SimpleDateFormat.MEDIUM, Locale.getDefault());
public game timecall2= new game();
public MyTime(Context ctx) {
// create internal instance
Context ctx2;
}
@Override
public void run() {
game.sec--;
if(game.sec==-1){game.sec=59;game.min--;}
game.Title2(); // set text in title bar
}
}
It would be easier if you explain more cleary, what you want to do.
Or post more code.
public game timecall2= new game();
I think, game is your first class?
Then you want to use the variable sec of the class game?
-> are they declared as static or why you don't call it over the object timecall2 you created?
Sry, but without more Code/Information to unterstand your problem, it's difficult to help. Also don't know, how skilled your are in programming.
*game* is the first class
I've tried calling the method through *timecall2* object but it doesn't help.
I've tried declaring the function as both static and no-static but nothing seems to change.
I've got lots of programming experience in other languages, but I'm less experienced with Java
And what's going wrong now?
Why don't you debug trough the code. Should be the easiest ways to find the problem.
You generally should use getters and setters for accessing variables inside of another class. Meaning that you have a method to set the value of the variable and a method to retrieve the value
Code:
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class MyClass extends Activity {
private static int mMin = 0;
private static int mSec = 0;
private TextView titleText;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView titleText = (TextView) findViewById(R.id.titleText);
}
public static int getSec() {
return mSec;
}
public static void setSec(int newVal) {
mSec = newVal;
}
public static int getMin() {
return mMin;
}
public static void setMin(int newVal) {
mMin = newVal;
}
public static void setTitleText(String newVal) {
if (titleText != null) {
titleText.setText(newVal);
}
}
}
Notice the "static" modifier of the class methods.
Generally, you wouldn't instantiate this activity class. Especially if it already lives in memory. What I am guessing that you are doing here is that "game" is your activity and that MyTime is an object that you are using from inside of the activity and that you need to modify variables that live in the main Activity.
If that is the case then you would just do something like this:
Code:
import java.util.TimerTask;
import com.myapp.game.MyActivity;
class MyTime extends TimerTask {
private int sec = 0;
private int min = 0;
@Override
public void run() {
sec = MyActivity.getSec();
min = MyActivity.getMin();
sec--;
if(sec==-1) {
sec=59;
min--;
}
String title = String.valueOf(min)+":"+String.valueOf(sec); //obviously you need formatting
MyActivity.SetTitle(title); // set text in title bar
MyActivity.setSec(sec);
MyActivity.setMin(min);
}
}
That said... I just did the above as an example. This is entirely the wrong way to make a game timer. There is a better example here
From what I remember from C++, you would have a "base" class and then other classes beneath that base class.
To use the base class methods, the other classes had to be "friends". I'm a little rusty on my JAVA syntax...is "extends" the same thing as a friend class?
Java doesn't have friend functions, and "extends" means that the class is a subclass of whatever its extending.
To access a function/variable between classes that said function/variable must be static. Beware tho when do this depending on you implementation you must check for null variables. Since its static you can access you dont need a class object to access them through.
ak. SomeClass.function();
instead of using SomClass sc = new SomeClass(); sc.function();
since u can access it at any time its contents may not be initialized and be null. So ALWAYS check for null varaibles! lol. That or u can have one variable of that class to check if its class is initialized. such as..
SomeFunction.isInit();
where isInit(); is
private static initialized = false;
public static boolean isInit()
{
return initialized;
}
where in your onCreate & on onDestroy functions you set the initialized variable accordingly.
or..u could just do if(SomeClass.this!=null) lol :S
/me stops writting wot
Thanks for the input everyone. I've realised the problem (but still can't fix it). I can call methods in other classes from my timer class.... but my main class that has the methods that I need implements OnClickListener (public class game extends Activity implements OnClickListener) so it is ONLY updating the view methods when something is clicked on. How should I go about fixing it so that I can call methods that will update when a timer calls them (e.g. I display the remaining time in the title bar and it doesn't update the current time UNLESS a button is clicked on)
Why not run the timer as a thread in the activity class itself?

[Q] Handling ACTION_SCREEN in a widget

Hi,
I'm doing a widget that needs to be update on screen_on or on
user_present. As I'm not hable to register a BroadcastReceiver inside
the widget I'm doing it in a Service that is triggered by the widget
like this:
Widget.java:
Code:
@Override
public void onEnabled(Context context) {
super.onEnabled(context);
context.startService(new Intent(context,
WidgetService.class).setAction(WidgetService.ACTION_WIDGET_START));
}
WidgetService.java:
Code:
@Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
String action = intent.getAction();
Log.d(LOG_APP,"WidgetService onStart: "+action);
if (ACTION_WIDGET_STOP.equals(action)) {
this.unregisterReceiver(mReceiver);
stopSelf();
return;
} else if (ACTION_WIDGET_START.equals(action)) {
// register receiver that handles screen on and screen off logic
IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
this.registerReceiver(mReceiver, filter);
return;
}
The problem is that when I try to register the receiver I get the
error that the service has leaked IntentReceiver because it was
already registered. Ive checked and no duplicate registration was done
in my code.
Do you have any idea what I'm overlooking?
Thanks,
PMD

[Q] GPS with Fragment

Good day. I start learn Fragment and I want use GPS in my Application. and I use Fragment. in fragment who view coordinate i writed next code
Code:
public class MyFragment2 extends Fragment {
public static final String BUTTON_INDEX = "button_index";
private static final int BUTTON_INDEX_DEFAULT = -1;
static TextView txt;
static TextView txt2;
String[] mCatDescription;
public View onCreateView (LayoutInflater inflater, ViewGroup container, Bundle saveInstanceState){
View viewHier = inflater.inflate(R.layout.fragment2, container, false);
txt = (TextView)viewHier.findViewById(R.id.textView1);
txt2 = (TextView)viewHier.findViewById(R.id.textView2);
mCatDescription =getResources().getStringArray(R.array.cats);
Bundle args = getArguments();
int buttonIndex = args != null ? args.getInt(BUTTON_INDEX, BUTTON_INDEX_DEFAULT):BUTTON_INDEX_DEFAULT;
if(buttonIndex != BUTTON_INDEX_DEFAULT){
setDiscription(buttonIndex);
}
return viewHier;
}
public void setDiscription(int buttonIndex){
GPSWork gpsWork = new GPSWork();
switch(buttonIndex){
case 1:
txt2.setText("one");
break;
case 2:
gpsWork.GetCoordinates();
break;
case 3:
txt2.setText("therd");
break;
}
}
}
Ok. when we click on button 2 we call method GetCoordinates(). this class have next code
Code:
public class GPSWork{
LocationManager locationManager;
public GPSWork(){
locationManager = (LocationManager)MainActivity.mContext.getSystemService(Context.LOCATION_SERVICE);
}
public void GetCoordinates(){
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
5000, 5, locationListener);
}
private LocationListener locationListener = new LocationListener() {
@Override
public void onLocationChanged(Location location) {
MyFragment2.txt2.setText("OK");
}
@Override
public void onProviderDisabled(String provider) {
MyFragment2.txt2.setText("OK");
}
@Override
public void onProviderEnabled(String provider) {
MyFragment2.txt2.setText("OK");
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
MyFragment2.txt2.setText("OK");
}
};
}
how we see, we should get text OK on TextView on MainActivity. but we don't have text, whats wrong? and if I change code in method GetCoordinates() on
Code:
public void GetCoordinates(){
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,
1000, 10, locationListener);
}
all work fine, i see text in TextView (OK )

[SOLVED] Android getParentFragment() returns null in ViewPager within a Fragment

I have an Activity that contains a Fragment with a ViewPager. Then I call a method of a Fragment within the ViewPager. But if that Fragment then calls getParentFragment(), it returns null.
Why is getParentFragment() null?
The main Fragment that contains a ViewPager:
Code:
public class MyFragment extends Fragment {
private TabLayout mTabLayout;
private ViewPager mViewPager;
private ViewPagerAdapter mAdapter;
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
View view = getView();
// Setup the ViewPager
mViewPager = (ViewPager) view.findViewById(R.id.container);
setupViewPager(mViewPager);
// Setup the TabLayout
mTabLayout = (TabLayout) view.findViewById(R.id.tabs);
mTabLayout.setupWithViewPager(mViewPager);
}
// This method is called from Activity
public void callNestedFragment() {
if (isDetached()) {
return;
}
((Fragment0) mViewPager.getItem(0)).testMethod();
}
}
The nested Fragment (inside mViewPager):
Code:
public class Fragment0 extends Fragment {
...
public void testMethod() {
if (isDetached()) {
return;
}
// Why is getParentFragment() null?
Log.i(TAG, "Parent fragment:" + getParentFragment());
return;
}
}
The ViewPagerAdapter:
Code:
public class ViewPagerAdapter extends FragmentPagerAdapter {
private Context mContext;
public ViewPagerAdapter(FragmentManager manager, Context context) {
super(manager);
mContext = context;
}
@Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new Fragment0();
case 1:
return new Fragment1();
case 2:
return new Fragment2();
case 3:
return new Fragment3();
case 4:
return new Fragment4();
}
return null;
}
@Override
public int getCount() {
return 5;
}
}
If more code is needed, please let me know. Thanks for your help.
Info
SuperThomasLab said:
I have an Activity that contains a Fragment with a ViewPager. Then I call a method of a Fragment within the ViewPager. But if that Fragment then calls getParentFragment(), it returns null.
Why is getParentFragment() null?
The main Fragment that contains a ViewPager:
Code:
public class MyFragment extends Fragment {
private TabLayout mTabLayout;
private ViewPager mViewPager;
private ViewPagerAdapter mAdapter;
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
View view = getView();
// Setup the ViewPager
mViewPager = (ViewPager) view.findViewById(R.id.container);
setupViewPager(mViewPager);
// Setup the TabLayout
mTabLayout = (TabLayout) view.findViewById(R.id.tabs);
mTabLayout.setupWithViewPager(mViewPager);
}
// This method is called from Activity
public void callNestedFragment() {
if (isDetached()) {
return;
}
((Fragment0) mViewPager.getItem(0)).testMethod();
}
}
The nested Fragment (inside mViewPager):
Code:
public class Fragment0 extends Fragment {
...
public void testMethod() {
if (isDetached()) {
return;
}
// Why is getParentFragment() null?
Log.i(TAG, "Parent fragment:" + getParentFragment());
return;
}
}
The ViewPagerAdapter:
Code:
public class ViewPagerAdapter extends FragmentPagerAdapter {
private Context mContext;
public ViewPagerAdapter(FragmentManager manager, Context context) {
super(manager);
mContext = context;
}
@Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new Fragment0();
case 1:
return new Fragment1();
case 2:
return new Fragment2();
case 3:
return new Fragment3();
case 4:
return new Fragment4();
}
return null;
}
@Override
public int getCount() {
return 5;
}
}
If more code is needed, please let me know. Thanks for your help.
Click to expand...
Click to collapse
Post Full Logcat Error & Fragment Class
:good:
I found the answer. If isDetached() is true, it doesn't mean getParentFragment() is not null.
So instead of the previous check in testMethod(), this is the new code:
Code:
public void testMethod() {
if (isDetached() && getParentFragment() != null) {
return;
}
...
}
I also now call the same method again in the onStart() method within Fragment0, where getParentFragment() should not be null.

Categories

Resources