我在我的应用程序中实现了一项服务。上传任务完成后,我想自行停止服务。我试图检测网络,当无线或移动网络可用,然后开始上传我的数据在服务器上,并在完成上传任务后停止onCreate()
方法中的服务本身。我在服务启动时记录了一条消息,但我不明白为什么即使在呼叫this.stopSelf()
之后,它也会连续打印停止服务消息。如何在Android中正确使用服务?如何让Android服务完成后自行停止?
这是我的服务代码。
public class ServiceTest extends Service {
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate()
{
super.onCreate();
mTimer = new Timer();
mTimer.schedule(timerTask, 2000, 15 * 1000);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
try {
} catch (Exception e) {
e.printStackTrace();
}
return super.onStartCommand(intent, flags, startId);
}
private Timer mTimer;
TimerTask timerTask = new TimerTask() {
@Override
public void run()
{
getConnectivityStatusString(getApplicationContext());
}
};
public String getConnectivityStatusString(Context context) {
int conn = Constant.getConnectivityStatus(context);
String status = null;
if (conn == Constant.TYPE_WIFI)
{
status = "Wifi enabled";
Log.e("", " status = " + status);
ConnectivityManager conMgr = (ConnectivityManager)context.getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
{
NetworkInfo netInfo = conMgr.getActiveNetworkInfo();
if (netInfo == null)
{
Log.e(" Not "," Accessible !!!");
}
else
{
Log.e(" Start ", " To Loading !!!!");
//new Welcome_Page().execute();
this.stopSelf();
Log.e(" Stop ", " The Service !!!!");
}
}
} else if (conn == Constant.TYPE_MOBILE) {
status = "Mobile data enabled";
Log.e(""," status = "+status);
this.stopSelf();
Log.e(" Stop ", " The Service !!!!");
} else if (conn == Constant.TYPE_NOT_CONNECTED) {
status = "Not connected to Internet";
Log.e(""," status = "+status);
}
return status;
}
public void onDestroy() {
try {
mTimer.cancel();
timerTask.cancel();
} catch (Exception e) {
e.printStackTrace();
}
Intent intent = new Intent("com.android.techtrainner");
intent.putExtra("yourvalue", "torestore");
sendBroadcast(intent);
}
}
这里是我的BroadcastReceiver类代码。
public class ReceiverCall extends BroadcastReceiver
{
@Override
public void onReceive(Context context, Intent intent)
{
context.startService(new Intent(context, ServiceTest.class));
}
}
这是我的网络代码。
public class Constant
{
public static int TYPE_WIFI = 1;
public static int TYPE_MOBILE = 2;
public static int TYPE_NOT_CONNECTED = 0;
public static int getConnectivityStatus(Context context) {
ConnectivityManager cm = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
if (null != activeNetwork) {
if(activeNetwork.getType() == ConnectivityManager.TYPE_WIFI)
return TYPE_WIFI;
if(activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE)
return TYPE_MOBILE;
}
return TYPE_NOT_CONNECTED;
}
}
stopService(新意图(YOUR_CONTEXT.this,ServiceTest.class))。 ...使用这些,让我知道如果担心 –
@Ravindra Kushwaha:我可以把这行在ServiceTest.class - stopService(新意图(YOUR_CONTEXT.this,ServiceTest.class)) – jandroid
无需把它放在里面服务类...你只需把这些代码放在一边e,您的操作已完成 –