对于演示,我在 Evert 10 秒后打印了一个 Toast。使用Service
类。
它工作正常,如果我在离开应用程序时处于活动状态,我每 10 秒就会收到一次 Toast,服务没有给出 o/p。
但是我想干杯,要么我会杀死应用程序,要么按一下下面的代码片段:
服务演示.java
public class ServiceDemo extends Activity {
private Handler myHandler = new Handler();
private Runnable drawRunnable = new Runnable() {
@Override
public void run() {
as();
myHandler.postDelayed(this, 10000);
}
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_service_demo);
myHandler.postDelayed(drawRunnable, 10000);
startService(new Intent(this, MyService.class));
}
public void as(){
startService(new Intent(this, MyService.class));
}
@Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
}
}
服务.java
public class MyService extends Service {
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
Toast.makeText(this, "HOHO Service Created...", Toast.LENGTH_LONG).show();
}
@Override
public void onDestroy() {
}
@Override
public void onStart(Intent intent, int startid) {
Toast.makeText(this, "Service Started...", Toast.LENGTH_LONG).show();
}
}
编辑 1
moveTaskToBack(true);
我将它放入 onBackPressed 方法中,如果我不在屏幕上,我服务会给出 o/p 但是当我杀死应用程序时,Service not responding