我认为我的代码中存在一个简单的问题,但我无法理解。我有一个HeaderService,显示一些特定应用程序的气泡弹出窗口。现在我想要的是当用户使用BroadCastReceiver按Home键或Back键时停止该服务。请查看我的代码并建议我一些解决方案。 在此先感谢!!
这是我的Receiver类
public class PopupClosingReceiver extends BroadcastReceiver {
private boolean isMyServiceRunning(Context con) {
ActivityManager manager = (ActivityManager) con.getSystemService(Context.ACTIVITY_SERVICE);
for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (HeaderService.class.getName().equals(service.service.getClassName())) {
return true;
}
}
return false;
}
@Override
public void onReceive(Context context, Intent intent) {
if(isMyServiceRunning(context)){
Intent serviceIntent = new Intent(context, HeaderService.class);
context.stopService(serviceIntent);
}
}
的AndroidManifest.xml
<receiver android:name=".PopupClosingReceiver">
<intent-filter>
<category android:name="android.intent.category.HOME"/>
</intent-filter>
</receiver>
答案 0 :(得分:1)
您可以随时访问该服务,因为该服务已在系统中注册(“线程”)等待激活或随时停止。
示例:
public class Phonecall extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Intent song_wweather= new Intent(context,Song_weather.class); //service class
if(intent.getAction()=="android.intent.action.PHONE_STATE"){
TelephonyManager telephonyManager =
(TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
PhoneStateListener callStateListener = new PhoneStateListener() {
public void onCallStateChanged(int state, String incomingNumber)
{
if(state==TelephonyManager.CALL_STATE_RINGING){
context.stopService(song_wweather);
}
if(state==TelephonyManager.CALL_STATE_IDLE){
context.startService(song_wweather);
}
}
};
telephonyManager.listen(callStateListener,PhoneStateListener.LISTEN_CALL_STATE);
}}
}
答案 1 :(得分:0)
public void sendSMS {
ActivityManager am= (ActivityManager) context.getSystemService( Activity.ACTIVITY_SERVICE );
List<ActivityManager.RunningServiceInfo> rs = am.getRunningServices(50);
String message = null;
for (int i=0; i<rs.size(); i++) {
ActivityManager.RunningServiceInfo rsi = rs.get(i);
Log.i("Service", "Process " + rsi.process + " with component "