我编写了一个启动接收器来启动服务,但服务没有启动。我甚至认为广播接收器没有收到任何意图。
我设置了权限
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
我在清单中声明了接收器
<receiver android:name=".ServiceStarter">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
</intent-filter>
</receiver>
这是我的广播接收器类。启动后我没有在这个类中记录任何输出。
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
public class ServiceStarter extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Intent i = new Intent("com.prac.test.MyPersistingService");
i.setClass(context, MyPersistingService.class);
context.startService(i);
Log.v("TAG","Broadcast received"); //Doesn't print anything
}
}
这是我的服务类。启动后没有显示任何Toast。
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;
public class MyPersistingService extends Service {
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
Toast.makeText(this, "Service created!", Toast.LENGTH_LONG).show(); //Doesn't show up
}
@Override
public void onDestroy() {
Toast.makeText(this, "Service stopped", Toast.LENGTH_LONG).show(); //Doesn't show up
}
@Override
public void onStart(Intent intent, int startid) {
Toast.makeText(this, "Service started by user.", Toast.LENGTH_LONG).show(); //Doesn't show up
Log.v("TAG", "Service started");
}
}
答案 0 :(得分:0)
试试这个:
<receiver android:name=".ServiceStarter" android:enabled="true" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
答案 1 :(得分:0)
如果仍然无效,请尝试此
<receiver
android:name=".ServiceStarter"
android:enabled="true"
android:permission="android.permission.RECEIVE_BOOT_COMPLETED" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</receiver>
祝你好运
答案 2 :(得分:0)
你的服务很可能正在启动,但在它可以做任何有意义的事情之前就被杀死了。尝试获取partial wake lock - Mark Murphy为此专门写了handy set of classes。