サービス付きのアプリケーションがあります。サービスは、create メソッドのメイン アクティビティでアプリによって開始されます。私の問題は、アプリケーションを終了するときに発生します。サービスが停止し、すぐに再起動することもあれば、最近再起動することもあります。バージョン 4.1.2 とバージョン 2.3.6 でテストしました。サービスは、バージョン 2.3.6 では再度ありません。私のアプローチは間違っていますか?停止時間と再開時間の間に、ブロックする必要があるコールが来る可能性があります。アプリの終了時にサービスを停止しない方法はありますか? 注: リモート サービスを使用できません。
サービスに startForeground を追加しましたが、同じ問題がありました。アプリケーションを終了するとサービスが停止し、通知が表示されてもバージョン 2.3.3 を再起動しません。ただし、phoneStateListener は null 値を取ります
//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)
{
}
}
プライベートボイド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のwhere設定をサービスからブロードキャストに変更しますが、この場合、不要な呼び出しのブロックは遅くなります。ブロードキャスト 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();
}
}
}