Android - Start service on boot

前端 未结 7 1234
温柔的废话
温柔的废话 2020-11-22 16:05

From everything I\'ve seen on Stack Exchange and elsewhere, I have everything set up correctly to start an IntentService when Android OS boots. Unfortunately it is not start

7条回答
  •  执笔经年
    2020-11-22 16:26

    I have found a way to make your application run well when the device reboots, please follow the steps below to be successful.

    AndroidManifest file

    
    
    
    
    
    
    
    
            
                
    
                
            
        
        
            
                
                
            
        
         
    
    

    UIBootReceiver

    public class UIBootReceiver extends BroadcastReceiver {
    
    private static final String TAG = "UIBootReceiver";
    @Override
    
        public void onReceive(Context context, Intent arg1)
        {
            Toast.makeText(context, "started", Toast.LENGTH_SHORT).show();
            Intent intent = new Intent(context,class_Service.class);
            context.startService(intent);
        }
      }
    

    This is asking permission to not need to manage battery saving for this app so you can run in the background stably.

    Declare this code in onCreate () of MainActivity class:

       Intent myIntent = new Intent();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            myIntent.setAction(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
            myIntent.setData(Uri.parse("package:" + 
       DeviceMovingSpeed.this.getPackageName()));
        }
        startActivity(myIntent);
    

提交回复
热议问题