我正在为我的Android应用程序创建一个服务,我希望它在onPostExecute上运行另一个活动。
下面是CheckStatus.class(服务类)
public class CheckStatus extends Service {
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.e("service", "start");
loop();
return START_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
Log.e("service", "stop service");
}
private void loop(){
long endTime = System.currentTimeMillis()+5*1000;
while (System.currentTimeMillis()<endTime) {
synchronized (this) {
try {
wait(endTime - System.currentTimeMillis());
} catch (Exception e) {
}
}
}
Log.e("service", "Check status");
new CheckStatusTask().execute();
}
private class CheckStatusTask extends AsyncTask<String, Void, Void> {
char check_online;
@Override
protected Void doInBackground(String... params) {
//call url json POST method
try {
//Check return data status
} catch (Exception e) {
e.printStackTrace();
check_online = '2';
}
return null;
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
dialog.dismiss();
if (check_online == '1') {
Toast.makeText(getApplicationContext(), "online", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "offline", Toast.LENGTH_LONG).show();
}
}
}
}
所以我尝试在另一个活动上调用该服务
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
Intent check_status = new Intent(MainActivity.this,CheckStatus.class);
startService(check_status);
}
但这没有运行。
如何让它运行(服务)?
答案 0 :(得分:0)
请在manifest.xml中添加以下内容
<service
android:name=".NameOfService">
</service>