为什么Broadcast Receiver不能用于服务应用程序android?
我有一个项目只是一个服务,它没有活动和用户界面。我想在手机完全启动时启动我的应用程序后台服务。但我从来没有收到操作系统的“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。
我从来没有从OS
晴收到“BOOT_COMPLETED”消息,那是因为你没有<receiver>
设置为接收android.intent.action.BOOT_COMPLETED
做广播。
天色,那是因为,直到设备上的东西使用显式Intent
开始你的组件之一你的应用程序将不会收到广播。该方法您的应用程序设置—没有用户可以运行—这是不可能的任何应用程序会做这样的一个活动,所以您的代码将永远不会运行。此外,请记住,Android O的设计更改专门用于防止后台服务运行很长时间,并限制您获取后台位置更新的能力(您的location_tracker
名称暗示您希望在未来添加)。您可能希望重新考虑以这种方式编写此应用程序是否明智之举。
试试这个在您的清单
<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>
...可能想要删除这行'android:exported =“false”' - 它需要导出,默认情况下默认情况下带静态接收器和意向过滤器? –
我有接收器在我的清单.... –
请提供解决方案...我如何开始我的服务而无需用户交互??? –
@ Navid_pdp11:一般没有解决方案。 Android的设置是为了防止恶意软件作者做你正在做的事:隐藏用户并窥探他们。 – CommonsWare