【发布时间】:2013-04-29 10:48:18
【问题描述】:
我有一个带有服务的应用程序。服务由应用程序在创建方法的主要活动中启动。当我退出应用程序时出现我的问题:服务停止,有时立即重新启动,有时最近重新启动。我在 4.1.2 和 2.3.6 版本中进行了测试。在 2.3.6 版本中不再提供服务。我的方法错了吗?在停止时间和重新启动时间之间,必须阻止的呼叫可能会到来。退出应用程序时有什么方法可以不停止服务? 注意:我不能使用远程服务。
我将 startForeground 添加到服务但同样的问题。当我退出应用程序时服务停止并且即使我看到通知也不会重新启动版本 2.3.3。但是 phoneStateListener 取空值 如何确保退出应用程序时服务不会停止
//application main metod
@Override
protected void onCreate(Bundle savedInstanceState) {
//.....
startService(new Intent(getApplicationContext(), MyPhoneStateListener.class));
}
@Override
public int onStartCommand(Intent intent, int flags, int startId)
{
setCallListener();
setNoti();
return START_STICKY;
}
private void setCallListener()
{
try
{
if (phoneStateListener==null)
{
phoneStateListener = new StateListener();
telephonymanager = (TelephonyManager)getSystemService(TELEPHONY_SERVICE);
telephonymanager.listen(phoneStateListener,PhoneStateListener.LISTEN_CALL_STATE);
}
}
catch(Exception ex)
{
}
}
private void setNoti() {
Notification notification= new Notification(R.drawable.ic_launcher, getResources().getString(R.string.app_name), System.currentTimeMillis());
Intent main = new Intent(this, MainActivity.class);
main.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, main, PendingIntent.FLAG_UPDATE_CURRENT);
notification.setLatestEventInfo(this, getResources().getString(R.string.app_name), getResources().getStringArray(R.array.blockstate)[Sabitler.ShieldState].toString(), pendingIntent);
notification.flags |= Notification.FLAG_FOREGROUND_SERVICE | Notification.FLAG_NO_CLEAR;
startForeground(123456, notification);
}
按照 Dhawal Sodha 的建议,我将设置 callstatelistener 从服务更改为广播,但在这种情况下,阻止不需要的呼叫会变慢。我认为广播 TelephonyManager 会初始化每个呼叫。广播代码如下。当我使用服务时, 退出主要活动时,服务在 2.3.3 版中停止。任何想法 ?广播还是服务?怎样才能让广播更快?每个调用变量和对象在广播中再次初始化。
public class PhoneStateBroadcastReceiver extends BroadcastReceiver{
MyCustomStateListener myCustomStateListener;
TelephonyManager telephonymanager;
@Override
public void onReceive(Context context, Intent intent)
{
try
{
//Log.e("receiver1",String.valueOf(System.currentTimeMillis()));
telephonymanager = (TelephonyManager) context.getSystemService(context.TELEPHONY_SERVICE);
myCustomStateListener = new MyCustomStateListener(context,telephonymanager);
telephonymanager.listen(myCustomStateListener, PhoneStateListener.LISTEN_CALL_STATE);
//Log.e("receiver2",String.valueOf(System.currentTimeMillis()));
telephonymanager.listen(myCustomStateListener, PhoneStateListener.LISTEN_NONE);
}
catch(Exception ex)
{
Toast.makeText(context,"setCallListener:"+ex.toString(), Toast.LENGTH_SHORT).show();
}
}
}
【问题讨论】:
-
你要封号???然后只需在广播接收中使用此代码.. 而不是启动服务..
-
当您说“服务停止”时,您的意思是在完成您的活动后调用它的onDestroy()?另外,当你说“退出应用程序”时,你的意思是刚刚完成活动吗?
-
是的,用 System.exit(0) 完成主要活动;
-
我已经添加了关于这个问题的答案here
标签: android service android-service