我正在尝试在后台运行服务.我的应用程序所做的是当用户检查复选框然后服务启动时以及取消选中时服务停止.哪个工作得很好.但问题是,当我从任务管理器关闭应用程序时,它也会停止服务.我想要的是即使它从任务管理器关闭后仍保持服务运行.然后,只有通过取消方框才能让用户自己停止该服务.
我怎样才能做到这一点?
这是我的代码
我的主要活动
public class SampleServiceActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final CheckBox cb = (CheckBox) findViewById(R.id.checkBox1);
cb.setOnCheckedChangeListener(new OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
if(isChecked) {
Toast.makeText(getBaseContext(), "Checked", Toast.LENGTH_LONG).show();
startService(new Intent(getBaseContext(), MyService.class));
} else {
Toast.makeText(getBaseContext(), "Unchecked", Toast.LENGTH_LONG).show();
stopService(new Intent(getBaseContext(), MyService.class));
}
}
});
}
}
Run Code Online (Sandbox Code Playgroud)
我的服务类
public class MyService extends Service {
Notify n = new Notify();
@Override
public IBinder …Run Code Online (Sandbox Code Playgroud) 我正在开发一个用作应用程序锁定器的应用程序,这个应用程序可以通过询问用户打开这些应用程序的密码来保护其他已安装的应用程序,我的应用程序在这里
问题是可以通过强制关闭android任务管理器来轻松跳过应用程序,我该如何克服这个问题呢?
另外,检查新应用程序打开的最佳方法是什么,制作一项服务,每隔一秒检查一次应用程序的任务,或者每隔一秒用警报管理器发出警报进行检查.
关于它有几个问题,但我总是读同样的事情:"如果系统需要资源,服务将被杀死"或"你无法构建一个永远运行的服务,因为它在后台运行的越多,就越容易受到影响系统杀死它"等等
我面临的问题是:我的服务运行良好并且正如预期的那样,如果我运行我的应用程序然后退出它我的服务仍在运行,但是当我杀了我的应用程序时(通过转到"最近的应用程序"并转换它离开)服务停止.在这一刻,如果我转到设置>> aplications >>运行,我会看到该服务正在重启.过了一会儿,它回来了,我的服务运行没有问题.
我谷歌它,我找到了一些我能做的事情,但让我们先看看我的代码:
我通过这种方式启动我的服务(点击一下按钮后):
Intent intent = new Intent (MainActivity.this, MyService.class);
startService(intent);
Run Code Online (Sandbox Code Playgroud)
我还有3个额外的整数,所以我有这样的东西:
final Integer i, i2, i3;
i = 5; //for example
i2 = 10; //for example
i3 = 15; //for example
final Intent intent = new Intent (MainActivity.this, MyService.class);
intent.putExtra("INTEGER1", i);
intent.putExtra("INTEGER2", i2);
intent.putExtra("INTEGER3", i3);
startService(intent);
Run Code Online (Sandbox Code Playgroud)
在MyService中,我有以下方面:
public class MyService extends Service
{
AlarmManager am;
BroadcastReceiver br;
PendingIntent pi;
Integer i, i2, i3;
@Override
public void onCreate()
{
super.onCreate();
am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
pi = PendingIntent.getBroadcast(this, …Run Code Online (Sandbox Code Playgroud)