Android - Start service on boot

前端 未结 7 1227
温柔的废话
温柔的废话 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:20

    Well here is a complete example of an AutoStart Application

    AndroidManifest file

    
    
    
        
    
        
    
            
                
                    
                
            
    
            
            
        
    
    

    autostart.java

    public class autostart extends BroadcastReceiver 
    {
        public void onReceive(Context context, Intent arg1) 
        {
            Intent intent = new Intent(context,service.class);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                context.startForegroundService(intent);
            } else {
                context.startService(intent);
            }
            Log.i("Autostart", "started");
        }
    }
    

    service.java

    public class service extends Service
    {
        private static final String TAG = "MyService";
        @Override
        public IBinder onBind(Intent intent) {
            return null;
        }
        public void onDestroy() {
            Toast.makeText(this, "My Service Stopped", Toast.LENGTH_LONG).show();
            Log.d(TAG, "onDestroy");
        }
    
        @Override
        public void onStart(Intent intent, int startid)
        {
            Intent intents = new Intent(getBaseContext(),hello.class);
            intents.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intents);
            Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG).show();
            Log.d(TAG, "onStart");
        }
    }
    

    hello.java - This will pop-up everytime you start the device after executing the Applicaton once.

    public class hello extends Activity 
    {   
        public void onCreate(Bundle savedInstanceState) 
        {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
            Toast.makeText(getBaseContext(), "Hello........", Toast.LENGTH_LONG).show();
        }
    }
    

提交回复
热议问题