这是我的代码
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = new Intent(this, Services.class);
ActivityManager manager = (ActivityManager)getSystemService(ACTIVITY_SERVICE);
for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (Services.class.getName().equals(service.service.getClassName())) {
Toast.makeText(this,"Service is Running",Toast.LENGTH_LONG).show();
}else {
Toast.makeText(this,"Service Will run now",Toast.LENGTH_LONG).show();
startService(intent);
}
break;
}
}
}
和服务代码
package gcmtutorial.androidbegin.com.socket;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.widget.Toast;
/**
* Created by shuser on 21-07-2016.
*/
public class Services extends Service {
@Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
public class Hello implements Runnable{
public void run(){
synchronized (this){
int i=0;
while (i<100){
try {
wait(1000);
i++;
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// Let it continue running until it is stopped.
Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
Thread thread = new Thread(new Hello());
thread.start();
return START_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show();
}
}
我关闭应用程序并重新启动它总是说服务将立即运行。甚至我的服务都在后台运行。我怎么知道这个服务是否在android
的后台运行答案 0 :(得分:1)
我稍微更改了代码,原因如下,
private boolean isMyServiceRunning(Class<?> serviceClass) {
ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (serviceClass.getName().equals(service.service.getClassName())) {
return true;
}
}
return false;
}
你正在这里举杯,这需要一段时间,即只有在第一个去世后才会出现另一个吐司,尝试使用Log to nottast函数。
另一种方法:
让事情变得更简单。