全球一流的注册听众为Android的所有活动 [英] Global class to register listeners for all the activities in android

查看:109
本文介绍了全球一流的注册听众为Android的所有活动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个活动课。 活动A b活动。后来我加了活动ç当用户摇动设备正对活动A b活动。现在,如果我注册了ShakeListener的活动A 活性的研究乙,我可以实现我的目标。

I have two Activity classes. Activity A and Activity B. Later on I added Activity C which gets launched when user shakes the device being on Activity A or Activity B. Now if I register the ShakeListener in the Activity A and Acitivity B, I can achieve my goal

但我现在想,是一个不同的事情,我不想改变活动A b活动。我想写一个不同的类,它运行的整个应用程序,并注册ShakeListener在应用程序的所有活动。我该怎么办呢?什么样的班会这样?

But what I want now, is a different thing, I do not want to change Activity A and Activity B. I want to write a different class, which runs for the whole app, and registers the ShakeListener for all the activities in the app. How can I do that? What kind of class should that be?

我试图延长的BroadcastReceiver,并登记在的onReceive方法ShakeListener,但使用BOOT_EVENT这被炒鱿鱼设备启动和应用程序不启动,只有当。因此,不能达到我的目标。

I tried extending BroadcastReceiver and registering the ShakeListener in the onReceive method, but used BOOT_EVENT which gets fired only when the device boots and not the starting of the application. So could not achieve my goal.

然后,我建议由SO用户,扩展应用程序类和注册监听器那里。现在,听众被注册了,但现在我需要当前运行的活动和上下文传递给活动ç。在这里,我又回到零了,因为我不想增加code在活动A或B.此外,AFAIK,应用类称为之前的任何活动中被发起的,所以是有可能获得当前正在运行的活动的前景?

Then I was suggested by an SO user, to extend the Application class and registering the listener there. Now the listener gets registered, but now I need the currently running Activity and context to be passed to the Activity C. Here I'm back to zero again, because I don't want to add code in the Activity A or B. Also, AFAIK, the Application class is called before any of the Activity gets initiated, so is it possible to get the currently running Activity in the foreground?

后来我想移动code找到监听器本身的活动。在这里,我也需要获得当前活动和上下文。上下文是应用程序上下文,然后我试图访问当前打开的所有活动,<一个href="http://stackoverflow.com/questions/8131909/how-to-find-the-current-foreground-activity-in-android">following这个线程。基于版本的code是一个有点不同。这是不是推荐的方法,给我的错误。

Then I thought to move the code to find the activity in the Listener itself. Here also I needed to get the current activity and context. The context was the application context and then I tried to access all the currently open activities, following this thread. Based on the version the code is a bit different. And this is not the recommended way and gives me error.

这是类:

package com.something.someotherthing;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.os.Build;
import android.util.Log;    
import java.lang.reflect.Field;
import java.util.List;

/**
 * Created by  Inquisitive on 20/5/15.
 */
public class ShakeEventListener implements SensorEventListener {

    private Context context;
    private Activity activity;


    private String[] getPreLollipop() {
        try {
               @SuppressWarnings("deprecation")
            List<ActivityManager.RunningTaskInfo> tasks =
                    activityManager().getRunningTasks(1);
            ActivityManager.RunningTaskInfo currentTask = tasks.get(0);
            ComponentName currentActivity = currentTask.topActivity;
            return new String[]{currentActivity.getClassName()};
        }
        catch(Exception e){
            Log.d("version","Exception" +e.getClass());
            String str[]= {"abc","def"};
            return str;
        }
    }

    private String[] getLollipop() {
        final int PROCESS_STATE_TOP = 2;

        try {
            Field processStateField = ActivityManager.RunningAppProcessInfo.class.getDeclaredField("processState");

            List<ActivityManager.RunningAppProcessInfo> processes =
                    activityManager().getRunningAppProcesses();
            for (ActivityManager.RunningAppProcessInfo process : processes) {
                if (
                    // Filters out most non-activity processes
                        process.importance <= ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND
                                &&
                                // Filters out processes that are just being
                                // _used_ by the process with the activity
                                process.importanceReasonCode == 0
                        ) {
                    int state = processStateField.getInt(process);

                    if (state == PROCESS_STATE_TOP)
                    /*
                    If multiple candidate processes can get here,
                            it's most likely that apps are being switched.
                    The first one provided by the OS seems to be
                    the one being switched to, so we stop here.
                            */
                        return process.pkgList;
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        return new String[] { };
    }

    private ActivityManager activityManager() {
        return (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
    }


    public String[] get() {
        if (Build.VERSION.SDK_INT < 21) {
            Log.d("Version","Pre-lollipop");
            for(String str:getPreLollipop())
                Log.d("Version",str);
            return getPreLollipop();
        }
        else {
            Log.d("Version","Lollipop");
            for(String str:getLollipop())
                Log.d("Version",str);
            return getLollipop();
        }
    }
    public ShakeEventListener(Context context){
        Log.d("ACCELEROMETER","inside the constructor of shake event listener");
        this.context=context;
        String str[] = get();
        try {
            Class<?> myClass = Class.forName(str[0]);
            activity = (Activity) myClass.newInstance();
        }catch(Exception  e){
            //do something
        }

    }
    public void onAccuracyChanged(Sensor sensor, int accuracy){

    }
    public void onSensorChanged(SensorEvent se){
        Log.d("SENSOR","On sensor changed");

      //need the activity and context here..
    }


}

当我尝试使用其他版本低于棒棒糖的设备。它惹人SecurityException异常。对于具有以上版本棒棒糖的设备,它给我的应用程序的包名,而不是特定的类。

When I try with a device having version below lollipop. It catches the SecurityException. With a device having version above lollipop, it gives the package name of my application, but not the particular class.

1 的是什么来实现我的目标,正确的方法是什么?我下面不管的做法是正确的?在这种情况下,我会尝试调试code找到活动

1 what is the correct way to achieve my goal? Whatever approach I'm following is correct? in that case, I will try to debug the code to find activity

2 的如果不是,有什么其他办法通过,我可以实现我的具有监听从应用程序内的任何活动的全球听众的目标。

2 If not, what are the other alternatives by which I can achieve my goal of having a global listener that listens from any activity within the app.

3 的是它可以实现在所有的,不改变活动?

3 Is it achievable at all, without changing the activities?

请帮忙。

推荐答案

在你的情况,你需要实现一个服务来听背景传感器。穿过文档:服务

In your case, you need to implement a Service to listen to sensors in the background. Go through documentation:Service

您不能随便使用的BroadcastReceiver来完成这个任务。

You cannot just use Broadcastreceiver to accomplish this task.

参考:

<一个href="http://stackoverflow.com/questions/22093572/android-sensor-listening-when-app-in-background">Android传感器聆听当后台应用

请参考以下链接获得帮助: <一href="http://$c$c.tutsplus.com/tutorials/android-barometer-logger-acquiring-sensor-data--mobile-10558" rel="nofollow">http://$c$c.tutsplus.com/tutorials/android-barometer-logger-acquiring-sensor-data--mobile-10558

Refer this link for help: http://code.tutsplus.com/tutorials/android-barometer-logger-acquiring-sensor-data--mobile-10558

这篇关于全球一流的注册听众为Android的所有活动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆