目前我正在尝试阻止我的服务被应用程序管理器杀死。每次我刷这个应用程序,服务也会被杀死。
我尝试过的是 1.使用START_STICKY
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d(TAG, "onStartCommand started");
if(!isRunning){
mythread.start();
isRunning = true;
}
return START_STICKY;
}
在这个例子中,我的线程每五秒钟显示一次吐司。
我还创建了一个广播接收器,并提供了一个服务单独的过程
<service android:name="com.example.asd.mainhub.GPSTracker"
android:process=":my_process"
android:enabled="true" />
<receiver android:name="com.example.asd.mainhub.BootCompletedIntentReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.USER_PRESENT" />
<action android:name="android.intent.action.PACKAGE_RESTARTED" />
<action android:name="com.example.asd.mainhub.BootCompletedIntentReceiver" />
</intent-filter>
</receiver>
服务的public void onDestroy(){
Intent intent = new Intent("com.example.asd.mainhub.BootCompletedIntentReceiver");
intent.putExtra("yourvalue", "torestore");
sendBroadcast(intent);
}
MainActivity,调用我的服务onCreate()
gps = new GPSTracker();
mServiceIntent = new Intent(this, gps.getClass());
if (!isMyServiceRunning(gps.getClass())) {
startService(mServiceIntent);
}
我还尝试使用服务的通知和前景onCreate():
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
notificationIntent, 0);
Notification notification = new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("My Awesome App")
.setContentText("Doing some work...")
.setContentIntent(pendingIntent).build();
startForeground(1337, notification);
同样,每次我交换我的应用程序时,服务也会死亡,并且不再显示Toasts。在我的控制台中,最后的消息是: 我/ MAINACT:onDestroy! 申请终止。 好像甚至没有调用onDestroy()方法的服务。请提出建议,我该如何解决。
P.S顺便说一句,我将应用程序安装为系统应用程序,它会解决问题吗?
EDIT1:
private final class ServiceHandler extends Handler {
public ServiceHandler(Looper looper) {
super(looper);
}
@Override
public void handleMessage(Message msg) {
// Normally we would do some work here, like download a file.
// For our sample, we just sleep for 5 seconds.
// try {
// Thread.sleep(5000);
// } catch (InterruptedException e) {
// // Restore interrupt status.
// Thread.currentThread().interrupt();
// }
while(isRunning){
Log.d(TAG,"Running");
try {
postToastMessage("Toast from Service");
Thread.sleep(DELAY);
} catch (InterruptedException e) {
isRunning = false;
e.printStackTrace();
}
}
// Stop the service using the startId, so that we don't stop
// the service in the middle of handling another job
//stopSelf(msg.arg1);
}
}
public void postToastMessage(final String message) {
Handler handler = new Handler(Looper.getMainLooper());
handler.post(new Runnable() {
@Override
public void run() {
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show();
}
});
}
static final long DELAY = 5000;
编辑2:
HelloService service = new HelloService();
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = new Intent(this, service.getClass());
if (!isMyServiceRunning(service.getClass())) {
//startService(mServiceIntent);
startService(intent);
}
答案 0 :(得分:1)
使用意向服务而不是服务,它在工作线程而不是主线程上运行。因此,当从任务管理器中删除应用程序时,它将继续运行。
答案 1 :(得分:-1)
您正在寻找的是Services。您最常建议您阅读Android Studio here的文档。
服务将允许您的应用程序的特定部分始终存在。即使用户重新启动设备而又从未再次运行应用程序。关于服务有很多东西可以看,但目前我认为一段代码对你最有帮助,这里有一些代码,
首先在你的清单中
<!--notification-->
<service android:name="services.HelloService"
android:exported="false"
android:description="My notification Center"/>
<!--notification-->
第二
创建一个名为 HelloService
的类并使用正确的导入*
粘贴以下代码public class HelloService extends Service {
private Looper mServiceLooper;
private ServiceHandler mServiceHandler;
// Handler that receives messages from the thread
private final class ServiceHandler extends Handler {
public ServiceHandler(Looper looper) {
super(looper);
}
@Override
public void handleMessage(Message msg) {
// Normally we would do some work here, like download a file.
// For our sample, we just sleep for 5 seconds.
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// Restore interrupt status.
Thread.currentThread().interrupt();
}
// Stop the service using the startId, so that we don't stop
// the service in the middle of handling another job
stopSelf(msg.arg1);
}
}
@Override
public void onCreate() {
// Start up the thread running the service. Note that we create a
// separate thread because the service normally runs in the process's
// main thread, which we don't want to block. We also make it
// background priority so CPU-intensive work will not disrupt our UI.
HandlerThread thread = new HandlerThread("ServiceStartArguments",
Process.THREAD_PRIORITY_BACKGROUND);
thread.start();
// Get the HandlerThread's Looper and use it for our Handler
mServiceLooper = thread.getLooper();
mServiceHandler = new ServiceHandler(mServiceLooper);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this, "servicestarting",Toast.LENGTH_SHORT).show();
Message msg = mServiceHandler.obtainMessage();
msg.arg1 = startId;
mServiceHandler.sendMessage(msg);
// If we get killed, after returning from here, restart
return START_STICKY;
}
@Override
public IBinder onBind(Intent intent) {
// We don't provide binding, so return null
return null;
}
@Override
public void onDestroy() {
Toast.makeText(this, "service done", Toast.LENGTH_SHORT).show();
}
}
现在,在&#39; handleMessage方法&#39;例如,添加你的代码;
@Override
public void handleMessage(Message msg) {
//... your bit of code goes here
尝试{ 了Thread.sleep(5000);
// make a toast appears here
} catch (InterruptedException e) {
// Restore interrupt status.
Thread.currentThread().interrupt();
}
//stopSelf(msg.arg1); //... kill the service in your condition
}
最后,要激活服务类,在您的函数中触发服务,首先导入HelloService.class,然后创建一个Intent并启动!
Intent intent = new Intent(this, HelloService.class);
startActivity(intent)