0
NewActivity.class(它實際上是服務。遺憾的奇數命名)安卓我的服務沒有啓動
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
import java.util.Date;
public class NewActivity extends Service {
boolean flag;
public IBinder onBind(Intent intent) {
return null;
}
public void onCreate() {
super.onCreate();
Log.d("TAG", "Running");
flag = true;
}
public int onStartCommand() {
Thread t = new Thread(new Runnable() {
public void run() {
while(flag) {
try{
Thread.sleep(1000);
} catch(Exception e) {
e.printStackTrace();
}
Date d = new Date();
Log.i("MyTag", d.toString());
}
}
});
return START_STICKY;
}
public void onDestroy() {
super.onDestroy();
flag = false;
}
}
MainActivity.class
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LinearLayout layout = new LinearLayout(this);
Button startBtn = new Button(this);
Button isBtn = new Button(this);
startBtn.setText("Button");
startBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
startService(new Intent(MainActivity.this, NewActivity.class));
}
});
isBtn.setText("check");
isBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if(isServiceRunningCheck())
Log.d("TAG", "Service is running.");
else Log.d("TAG", "Service is not running.");
}
});
layout.addView(startBtn);
layout.addView(isBtn);
setContentView(layout);
}
public boolean isServiceRunningCheck() {
ActivityManager manager = (ActivityManager) this.getSystemService(Activity.ACTIVITY_SERVICE);
for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if ("com.example.zzing.test.NewActivity".equals(service.service.getClassName())) {
return true;
}
}
return false;
}
}
AndroidManifest.xml中
<Service android:name=".NewActivity"/>
該服務不會沒有任何錯誤地啓動。我在NewActivity中看不到任何日誌。我的代碼錯了? Plz的幫助。
在這裏,在清單'Service'應該是'service'。 –
我的上帝。感謝幫助。 –
你還沒有在onStartCommand中啓動你的線程。你剛剛創建它。 –