Start activity on boot

匿名 (未验证) 提交于 2019-12-03 01:52:01

问题:

I'd like to start my app just after the phone boot. Apparently the app is started after the boot but it immediately crashes (just to be clear the app normally works fine). I have already read and tried different solutions (link1, link2) and actually the same code works fine with another app I was developing. Here's the code:

AndroidManifest.xml:

StartMyActivityAtBootReceiver.java:

    public class StartMyActivityAtBootReceiver extends BroadcastReceiver {         @Override     public void onReceive(Context context, Intent intent) {          if ("android.intent.action.BOOT_COMPLETED".equals(intent.getAction())) {                      Intent myStarterIntent = new Intent(context, MainActivity.class);                 myStarterIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);                 context.startActivity(myStarterIntent);              }         }    } 

Could it be related the fact that I'm using the a lot of user permissions?

回答1:

Try this: 

1] In AndroidManifest.xml file:

 

2] Inside BroadcastReciever class with StartMyActivityAtBootReceiver as class name.

@Override public void onReceive(Context context, Intent intent) {      Intent i = new Intent(context, MainActivity.class);       i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);     context.startActivity(i);   }  

This worked for me. The difference in code is as follows:

  • android:permission="android.permission.RECEIVE_BOOT_COMPLETED" inside receiver.
  • included "category android:name="android.intent.category.DEFAULT" " inside intent filter.
  • I am not checking the intent in onRecieve, as i know that code will be executed only if its true


回答2:



回答3:

do it like this in if condition

 if(intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)) 


回答4:

in place of

 

add also this

some devices like HTC don't catch BOOT_COMPLETED



回答5:

I managed to solve the problem. Inside the OnCreate() I had this code (related to the USB communication) which was causing the crash:

    act_string = getIntent().getAction();     if( -1 != act_string.indexOf("android.intent.action.MAIN")){         restorePreference();     }                else if( -1 != act_string.indexOf("android.hardware.usb.action.USB_ACCESSORY_ATTACHED")){         cleanPreference();     }    

Deleting this code solved the start after boot issue.



回答6:

I would like to add the whole manifest file which workedv for me on oppo neo 5. And,even take care that some phone requires special access to achieve boot start or other special permissions.So,don't forgot to allow the accesses to your app!!.

Here's the code -

    


易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!