从Java服务访问Android上下文

3
我正在尝试创建一个Java服务,该服务在系统服务器之外运行,并且可以在启动时基于配置监视Android设备并侦听广播。我无法找到有关如何编写长时间运行的Java服务的文档,该服务作为不由zygote启动的进程运行。我正在尝试修改平台,并将此服务添加到通过重新构建Android源生成的自定义system.img中。
该服务的启动方式类似于使用adb运行am的脚本。
base=/system
export CLASSPATH=$base/framework/am.jar
exec app_process $base/bin com.android.commands.am.Am "$@"

我所发现的唯一添加守护进程的例子是实现完全在设备上运行的本地服务

嵌入式Android描述了Android用户空间以及运行在那里的一些本地守护进程,以及如何创建服务并将它们添加到init以在设备引导时启动,至少在Zygote和系统服务器之前等。

public class Monitor{
    public static void main(String [] args){
        new Monitor.run();
    }
    public void run(){
         Application app = new Application();
         Context con = app.getApplicationContext();
         BroadcastReceiver receiver = new BroadcastReceiver(){
             public void onReceive(Context context, Intent intent){
                 Log.i(TAG, "Received intent:"+ intent.getAction());
             }   
         }
         IntentFilter filter = new IntentFilter("android.intent.action.TIME_TICK")
    }
}

我也尝试了一下基于ActivityManagerService代码片段的方法。 public class Monitor{ private Context mContext;

    Monitor(){
        Looper.prepare()
        ActivityThread at = ActivityThread.systemMain();
        mContext = at.getSystemContext();
    }
    public static void main(String [] args){
        new Monitor.run();
    }
    public void run(){
         BroadcastReceiver receiver = new BroadcastReceiver(){
             public void onReceive(Context context, Intent intent){
                 Log.i(TAG, "Received intent:"+ intent.getAction());
             }   
         }
         IntentFilter  filter = new IntentFiler("android.intent.action.AIRPLANE_MODE");
         mContext.registerReceiver(receiver,filter);
    }
}

我知道可以使用adb和am从命令行生成意图/广播,但是否有任何方法可以接收广播。欢迎提供任何建议或建议。

1个回答

0

Activity管理器在Android中有代码来防止非Apps/Zygote进程接收广播。最终我采用了不同的方法来满足自己的需求。

public Intent registerReceiver(IApplicationThread caller, String 
callerPackage, 
        IIntentReceiver receiver, IntentFilter filter, String 
permission, int userId) { 
    enforceNotIsolatedCaller("registerReceiver"); 
... 
} 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接