gpt4 book ai didi

android - 如何管理服务中的广播接收器

转载 作者:行者123 更新时间:2023-11-30 03:29:16 26 4
gpt4 key购买 nike

我正在编写一个应用程序,其主要目标是在我的设备连接到交流电时启动 TuneIn 播放器。第一个版本仅使用广播接收器并且运行良好,除了 android OS 丢弃接收器的正常行为一旦被触发,因为,我正在寻找更永久的东西我正在尝试使用服务来保持广播接收器处于 Activity 状态,但我遇到了一些我无法理解的错误。

那么可以通过什么方式在服务中使用广播接收器?

我正在放置一个错误日志和我的部分代码。

错误:

07-19 08:03:27.019: ERROR/AndroidRuntime(15785): FATAL EXCEPTION: main
java.lang.RuntimeException: Error receiving broadcast Intent { act=android.intent.action.BATTERY_CHANGED flg=0x60000000 (has extras) } in com.upm.radioC.Servicio$1@407a0420
at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:722)
at android.os.Handler.handleCallback(Handler.java:587)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:130)
at android.app.ActivityThread.main(ActivityThread.java:3683)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:507)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:895)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:653)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.IllegalStateException: System services not available to Activities before onCreate()
at android.app.Activity.getSystemService(Activity.java:3536)
at com.upm.radioC.Tools.checkData(Tools.java:26)
at com.upm.radioC.Servicio$1.onReceive(Servicio.java:60)
at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:709)

主类

public class Inicio extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflador = getMenuInflater();
inflador.inflate(R.menu.menu, menu);
return true;
}

@Override
public boolean onMenuItemSelected(int featureId, MenuItem opcion) {
TextView btn = (TextView) findViewById(R.id.txtEtiqueta);
Intent svc = new Intent(this, Servicio.class);
switch (opcion.getItemId()) {
case R.id.mnuRegistra:
startService(svc);
btn.setText("Monitoreo Iniciado");
break;
case R.id.mnuLibera:
stopService(svc);
btn.setText("Monitoreo Detenido");
break;
}
return super.onMenuItemSelected(featureId, opcion);
}
}

服务等级

public class Servicio extends Service {

private BroadcastReceiver receiver;
private IntentFilter filter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
private Tools NetWork = new Tools(); //Custom Class for activate/deactivate GSM data

@Override
public IBinder onBind(Intent arg0) {
return null;}

@Override
public void onCreate() {
super.onCreate();}

@Override
public int onStartCommand(Intent i, int flags, int startID) {
_startService();
return START_STICKY; }

@Override
public void onDestroy() {
super.onDestroy();
_shutdownService(); }

private void _startService() {
receiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
int plugged = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
if (plugged == BatteryManager.BATTERY_PLUGGED_USB) {
Toast.makeText(getApplicationContext(), "Conectado a USB", Toast.LENGTH_LONG).show();
}else if (plugged == BatteryManager.BATTERY_PLUGGED_AC) {
if (!NetWork.checkData()) try {
NetWork.turnData(true);
} catch (Exception e) {
e.printStackTrace();
}
Intent LaunchIntent = getPackageManager().getLaunchIntentForPackage("tunein.player");
startActivity(LaunchIntent);
Toast.makeText(getApplicationContext(), "Conectado a AC", Toast.LENGTH_LONG).show();
} else {
if (NetWork.checkData()) try {
NetWork.turnData(false);
} catch (Exception e) {
e.printStackTrace();
}
Toast.makeText(getApplicationContext(), "Desconectado de las fuentes de poder", Toast.LENGTH_LONG).show();
}
}
};
registerReceiver(receiver, filter);
}

private void _shutdownService() {
unregisterReceiver(receiver);}

}

提前致谢!

最佳答案

看起来它与您调用 getSystemService 的上下文有关。尝试将服务上下文传递给 Tools 类,然后使用该上下文调用 getSystemService

ServicioonCreate 中创建 Tools 实例

private Tools NetWork = null;

@Override
public void onCreate() {
super.onCreate();
Network = new Tools(this);
}

然后在您的 Tools 类中将传入的 Context 存储在一个私有(private)变量中(例如 mContext),并在其中的方法中使用它类。

boolean checkData() { 
ConnectivityManager connManager = (ConnectivityManager) mContext.getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo mMobile = connManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
return mMobile.isConnected();
}

编辑:

为了理解上下文,您可以引用以下引用资料

  1. demystifyind context

  2. Context, What Context

关于android - 如何管理服务中的广播接收器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17764281/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com