退出后广播消息继续投入使用并重新启动启动服务的活动

时间:2015-01-16 01:27:16

标签: android service broadcast

我正在开发Android APP。有一项主要活动和服务。通过在主活动中调用startService(intent)来启动该服务。无论活动是否正在运行,它都将在后台运行。创建活动后,它会向服务发送广播消息以查询某些状态。第一次运行是正常的,活动和服务都正确启动。但是我遇到一个问题,当我退出活动并重新启动它时,服务将继续接收查询消息,就像活动重复发送它一样。但我确认活动中的发送代码只执行一次。任何人都知道消息来自哪里?

主要活动onCreate方法

中的代码
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

        Log.v("debug", "Main.onCreate");

        Intent intent=new Intent(MainActivity.this, PingService.class);
        startService(intent);

        Intent intent = new Intent(PingService.ACTION_QUERY);
        sendBroadcast(intent);
}

以下是服务中的代码

    private BroadcastReceiver receiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {

        if (intent.getAction().equals(PingService.ACTION_QUERY)) {
            Log.v("debug", "PingService.receiver.onReceive: ACTION_QUERY");

        //the program keeps coming here
        }
    }
 };

@Override
public void onCreate() {
    Log.v("debug", "PingService.onCreate");

    HandlerThread thread = new HandlerThread("pingd",
            android.os.Process.THREAD_PRIORITY_BACKGROUND);
    thread.start();

    //handlers
    serviceHandler = new ServiceHandler();
    daemonHandler = new DaemonHandler(thread.getLooper());

        //register broadcast receiver
        IntentFilter filter = new IntentFilter();
        filter.addAction(PingService.ACTION_ADD);
        filter.addAction(PingService.ACTION_QUERY);
        filter.setPriority(999);
        registerReceiver(receiver, filter);


        instance = this;
}

0 个答案:

没有答案