简体   繁体   English

无法从ON_BOOT_COMPLETED广播接收器启动PhoneStateListener

[英]Trouble starting a PhoneStateListener from an ON_BOOT_COMPLETED Broadcast Receiver

I am trying to restart a PhoneStateListener after the phone has been rebooted (if my isRunning SharedPref is true... ie the listener was running before the reboot) 我尝试在电话重新引导后重新启动PhoneStateListener(如果我的isRunning SharedPref为true ...即,侦听器在重新引导之前正在运行)

Here is my code... 这是我的代码...

Eclipse gives me an error on the line: final TelephonyManager telephonyManager = (TelephonyManager)getSystemService(srvcName); Eclipse在行上给我一个错误:最终TelephonyManager telephonyManager =(TelephonyManager)getSystemService(srvcName);

It says that getSystemService(String) is not defined. 它说未定义getSystemService(String)。 Anyone know why? 有人知道为什么吗? The same basic code works just fine in my main app activity. 相同的基本代码在我的主要应用活动中也可以正常工作。

public class MyReceiver extends BroadcastReceiver {
    SharedPreferences mPrefs;

    String srvcName = Context.TELEPHONY_SERVICE;
    final TelephonyManager telephonyManager = (TelephonyManager)getSystemService(srvcName); 

    @Override
    public void onReceive(Context context, Intent intent) {


        mPrefs = context.getSharedPreferences("myAppPrefs", 0); 
        if(getRunning()){
             telephonyManager.listen(phoneStateListener, PhoneStateListener.LISTEN_DATA_CONNECTION_STATE);
        }

      }

First, it won't compile because BroadcastReceiver is not a Context . 首先,它不会编译,因为BroadcastReceiver不是Context

Second, a manifest-registered BroadcastReceiver cannot register a listener. 其次,清单注册的BroadcastReceiver无法注册侦听器。 That BroadcastReceiver object, and likely its whole process, will go away milliseconds after onReceive() completes. onReceive()完成后,该BroadcastReceiver对象及其整个过程可能会在几毫秒后消失。

Please listen for the ACTION_PHONE_STATE_CHANGED broadcast, which gives you the same information as a PhoneStateListener . 请收听ACTION_PHONE_STATE_CHANGED广播,该广播为您提供与PhoneStateListener相同的信息。 As an added bonus, you will not need to get control at boot time, which saves you a permission and speeds up reboots on your users' phones. 另外,您无需在启动时进行控制,从而节省了权限并加快了用户手机的重新启动速度。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM