2017-04-12 58 views
0

我有一個項目只是一個服務,它沒有活動和用戶界面。我想在手機完全啓動時啓動我的應用程序後臺服務。但我從來沒有收到操作系統的「BOOT_COMPLETED」消息。這是我的代碼:爲什麼Broadcast Receiver不能用於服務應用程序android?

清單:

<manifest xmlns:android="http://schemas.android.com/apk/res/android" 
package="com.droid.arghaman.location_tracker"> 

<application 
    android:allowBackup="true" 
    android:icon="@mipmap/ic_launcher" 
    android:label="@string/app_name" 
    android:supportsRtl="true" 
    android:theme="@style/AppTheme"> 

    <receiver android:name=".BootBroadcastReceiver" 
    android:enabled="true" 
    android:exported="false" 
    android:label="StartServiceAtBootReceiver"> 
    <intent-filter> 
     <action android:name="android.intent.action.BOOT_COMPLETED"></action> 
     <category android:name="android.intent.category.DEFAULT"></category> 
    </intent-filter> 

    </receiver> 
</application> 

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

廣播接收器:

public class BootBroadcastReceiver extends BroadcastReceiver { 
    @Override 
    public void onReceive(Context context, Intent intent) { 
     Log.i("boot Received", intent.getAction()); 
     Intent serviceLuncher = new Intent(context, myService.class); 
     context.startService(serviceLuncher); 
    } 
} 

爲myService:

public class LocationNotifierService extends Service { 
    Timer timer ; 
    @Nullable 
    @Override 
    public IBinder onBind(Intent intent) { 
     return null; 
    } 

    @Override 
    public void onCreate(){ 
     timer = new Timer(); 
     timer.schedule(new TimerTask() { 
     @Override 
     public void run() { 

Toast.makeText(getBaseContext(),"Location",Toast.LENGTH_SHORT).show(); 
      } 
      },3000); 
     } 

    @Override 
    public void onDestroy(){ 

    } 
    @Override 
    public int onStartCommand(Intent intent, int flagId, int startId){ 
     return START_STICKY; 
    } 
} 

,但我從來沒有得到「啓動接收」日誌。 是否有任何錯誤,並有任何方法來調試我的程序?

我建議我的項目必須只有這個服務,它不能有任何的UI。

回答

2

我從來沒有從OS

晴收到「BOOT_COMPLETED」消息,那是因爲你沒有<receiver>設置爲接收android.intent.action.BOOT_COMPLETED做廣播。

天色,那是因爲,直到設備上的東西使用顯式Intent開始你的組件之一你的應用程序將不會收到廣播。該方法您的應用程序設置—沒有用戶可以運行—這是不可能的任何應用程序會做這樣的一個活動,所以您的代碼將永遠不會運行。此外,請記住,Android O的設計更改專門用於防止後臺服務運行很長時間,並限制您獲取後臺位置更新的能力(您的location_tracker名稱暗示您希望在未來添加)。您可能希望重新考慮以這種方式編寫此應用程序是否明智之舉。

+0

我有接收器在我的清單.... –

+0

請提供解決方案...我如何開始我的服務而無需用戶交互??? –

+0

@ Navid_pdp11:一般沒有解決方案。 Android的設置是爲了防止惡意軟件作者做你正在做的事:隱藏用戶並窺探他們。 – CommonsWare

0

試試這個在您的清單

<receiver android:name=".BootBroadcastReceiver" 
    android:enabled="true" 
    android:exported="false" 
    android:label="StartServiceAtBootReceiver"> 
     <intent-filter> 
     <action android:name="android.intent.action.BOOT_COMPLETED" /> 
     </intent-filter> 
    </receiver> 
+0

...可能想要刪除這行'android:exported =「false」' - 它需要導出,默認情況下默認情況下帶靜態接收器和意向過濾器? –

相關問題