sac*_*nur 3 android android-service android-studio
我还是新手.我使用stopService调用onDestroy方法.调用onDestroy方法,因为我可以看到toast消息.但是用于发送位置更新的无限for循环一直在运行.有什么我需要改变的吗?
public class myservice extends IntentService {
LocationManager locationManager ;
public myservice() {
super(myservice.class.getName());
}
@Override
protected void onHandleIntent(Intent intent) {
String numb=intent.getStringExtra("num");
for (;;) {
send(numb);
}
}
public IBinder onBind(Intent intent) {
return null;
}
public void send(String numb) {
locationManager = (LocationManager)this
.getSystemService(Context.LOCATION_SERVICE);
if (ContextCompat.checkSelfPermission( this, android.Manifest.permission.ACCESS_COARSE_LOCATION ) == PackageManager.PERMISSION_GRANTED ) {}
Location location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
Geocoder geocoder;
geocoder = new Geocoder(this, Locale.getDefault());
try {
Thread.sleep(3000);
List<Address> addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
Toast toast1 = Toast.makeText(this, "message sent", Toast.LENGTH_SHORT);
toast1.setText(numb.toString());
toast1.show();
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(numb, null, "current postition is" + addresses.get(0).getAddressLine(0) + "," + addresses.get(0).getAddressLine(1) + "," + addresses.get(0).getAddressLine(2), null, null);
Toast.makeText(getApplicationContext(), "SMS sent.", Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "SMS faild, please try again.", Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
@Override
public void onDestroy() {
Toast.makeText(getApplicationContext(), "DESTROY2", Toast.LENGTH_LONG).show();
super.stopSelf();
super.onDestroy();
}
}
Run Code Online (Sandbox Code Playgroud)
你不打电话给onDestroy()
自己.永远不要自己调用生命周期方法.Android将在服务停止时调用它们.
对IntentService进行子类化并不是管理正在进行的工作的最佳方法.您最好自己管理一个线程并管理传递给该服务的启动和停止命令.这不是一件容易的事.
http://developer.android.com/guide/components/services.html
归档时间: |
|
查看次数: |
740 次 |
最近记录: |