📜  android 在启动时运行后台服务 - Java 代码示例

📅  最后修改于: 2022-03-11 14:52:30.043000             🧑  作者: Mango

代码示例1
//AndroidManifest.xml:
    
               
                   
               
         
//


//Add permission in your AndroidManifest.xml as:



//In code part BootBroadcastReceiver:
public class BootBroadcastReceiver extends BroadcastReceiver {     
    static final String ACTION = "android.intent.action.BOOT_COMPLETED";   
    @Override   
    public void onReceive(Context context, Intent intent) {   
        // BOOT_COMPLETED” start Service    
        if (intent.getAction().equals(ACTION)) {   
            //Service    
            Intent serviceIntent = new Intent(context, StartOnBootService.class);       
            context.startService(serviceIntent);   
        }   
    }    
}   
/*
if you are talking about device screen on/off then you need to register  and  for starting your service when user is present or screen is on.
*/