Android ACTION_SHUTDOWN Broadcast not working

前端 未结 1 351
南旧
南旧 2020-11-28 13:44

Code -

public class ShutdownReceiver extends BroadcastReceiver {
    private static final String TAG = \"ShutdownReceiver\";

    @Override
    public void o         


        
相关标签:
1条回答
  • 2020-11-28 14:47

    I know this is old but I have a partial solution which follows the material above. At least the shutdown event is called and I am able to do that unique item on shutdown, but there is a side effect that I don't understand; a memory leak. In one sense it IS shutdown so the memory leak has no drastic effects but I don't understand it and that is a bother.

    In any case I have no additions in the manifest.xml with respect to this BroadcastReceiver. It is completely defined in code.

    In my main activity a define a class as above

    private class ShutDownReceiver extends BroadcastReceiver
    {
    
        @Override
        public void onReceive(Context context, Intent intent)
        {
            if(Intent.ACTION_SHUTDOWN.equals(intent.getAction()))
            {
                Log.i(TAG, "System shutting down");
                context.stopService(new Intent(context, BluetoothPanService.class));
            }
        }
    
    }
    

    In the main activity's onResume() method I instantiate and register the receiver:

    public void onResume()
    {
        super.onResume();
        Log.i(TAG, "Measurement Log Activity has Resumed.");
    
        IntentFilter filter = new IntentFilter(Intent.ACTION_SHUTDOWN);
        mReceiver = new ShutDownReceiver();
        registerReceiver(mReceiver, filter);
    }
    

    ('mReceiver' is defined as a private class variable of the main activity)

    And finally in the main activity's onPause() I unregister the receiver

    public void onPause()
    {
        super.onPause();
        Log.i(TAG, "Measurement Log Activity has Paused.");
        this.unregisterReceiver(mReceiver);
    }
    

    When the phone is powered off the ACTION_SHUTDOWN event is indeed signaled and the service is stopped; it's onDestroy() method is signaled and a message to a remote MQTT broker service is published indicating that the client is no longer connected. The remote broker is getting the message so I know it is working.

    However, after that all hell break loose and it's mainly because I cannot stop my service from re-starting (even though I set START_NOT_STICKY in the onStartCommand method). But at this time besides getting a lot of red error lines in logcat, the ACTION_SHUTDOWN is heeded and the action I need to invoke gets done.

    Hope this helps someone (who perhaps isn't dealing with shutting down a service).

    0 讨论(0)
提交回复
热议问题