2016-04-27 106 views
4

我想在手機重新啓動時自動運行應用程序。我已經添加了這些行我的代碼:在Android重新啓動時運行應用程序

public class BootComplete extends BroadcastReceiver { 
@Override 
public void onReceive(Context context, Intent intent) { 

    if (intent.getAction().equalsIgnoreCase(Intent.ACTION_BOOT_COMPLETED)) { 
     Intent serviceIntent = new Intent(context, MyActivity.class); 
     context.startService(serviceIntent); 
    } 
} 

而且我已經添加了這些行到我的清單:

<receiver 
     android:name=".BootComplete" 
     android:enabled="true" 
     android:exported="false" > 
     <intent-filter> 
      <action android:name="android.intent.action.BOOT_COMPLETED" /> 
     </intent-filter> 
    </receiver> 

和它的權限:

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" > 
</uses-permission> 

它正常工作時MyActivity類只包含一些後臺任務。例如,當我想打開LED時。但是當我想播放媒體(例如視頻)時,它不起作用。只是說服務已經開始,並沒有發揮任何作用。

我該如何解決?有什麼我必須添加到代碼?

+0

您是否使用android monitor來查看您的日誌貓? –

+0

你爲什麼要打一個活動服務? – JoxTraex

+0

@JoxTraex我通過在Stack中搜索找到了這些。有沒有更好的方法? –

回答

0

做這個改變BroadcastReceiver

public class BootComplete extends BroadcastReceiver { 
    @Override 
    public void onReceive(Context context, Intent intent) { 

    if (intent.getAction().equalsIgnoreCase(Intent.ACTION_BOOT_COMPLETED)) { 
     Intent serviceIntent = new Intent(context, MyActivity.class); 
     // Change is here... 
     serviceInten.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
     context.startService(serviceIntent); 
    } 
} 

在清單:

<receiver 
     android:name=".BootComplete" 
     android:enabled="true" 
     android:exported="true" 
     android:permission="android.permission.RECEIVE_BOOT_COMPLETED" > 
     <intent-filter android:priority="500"> 
      <action android:name="android.intent.action.BOOT_COMPLETED" /> 

      <category android:name="android.intent.category.DEFAULT" /> 

      <action android:name="android.intent.action.QUICKBOOT_POWERON" /> 
     </intent-filter> 
</receiver> 

並留下許可,因爲它是。

1

問題不在於您的代碼!這是關於Android設備。

當設備啓動時,您會收到廣播。但請注意,當您收到廣播時,SD卡仍在填充,您無法訪問它。如果該媒體在SD卡上,則無法播放。另外,你應該注意別的:如果用戶在他/她的SD卡上安裝你的應用程序,該廣播接收機將永遠不會觸發。 因此,如果您想防止某些設備出現問題,請在您的清單中選擇內部安裝位置。

+0

感謝您的回答。我不想釋放我的應用程序。我只想把它放在我的設備中。而且我的設備中沒有存儲卡。有沒有辦法做到這一點? –

+0

當接收者打電話和媒體沒有播放時,請分享您的日誌貓。 –

相關問題