Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/198.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 传达服务和意图_Android_Service_Android Intent - Fatal编程技术网

Android 传达服务和意图

Android 传达服务和意图,android,service,android-intent,Android,Service,Android Intent,首先对不起我的英语我听得懂但写不好 我有一个定位服务,它保存在bd中的纬度和经度。他工作得很好,但我想在位置Listener发生变化时向我的意图发送信息。我想向我的意图发送一个字符串,以便输入编辑文本 服务代码: public class LocalizadorService extends Service{ private LocationManager locManager; private LocationListener locListener; private EjercicioBD

首先对不起我的英语我听得懂但写不好

我有一个定位服务,它保存在bd中的纬度和经度。他工作得很好,但我想在位置Listener发生变化时向我的意图发送信息。我想向我的意图发送一个字符串,以便输入编辑文本

服务代码:

public class LocalizadorService extends Service{

private LocationManager locManager;
private LocationListener locListener;
private EjercicioBD baseDatos = EjercicioBD.getEjercicioBD(this);

@Override
public IBinder onBind(Intent arg0) {
    return null;
}

@Override
public void onCreate() {
    super.onCreate();
}

@Override
public void onStart(Intent intent, int startId) {
    encontrarGPS();
    super.onStart(intent, startId);
}

@Override
public void onDestroy() {
    locManager.removeUpdates(locListener);
    super.onDestroy();
}

private void encontrarGPS() {
    //Obtenemos una referencia al LocationManager
    locManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);

    if(locManager.isProviderEnabled(LocationManager.GPS_PROVIDER)){
        locListener = new LocationListener(){
            public void onLocationChanged(Location arg0) {
                if (arg0 != null) {
                    setCurrentLocation(arg0);
                }
            }

            public void onProviderDisabled(String arg0) {
                noGPS();
                Toast.makeText(LocalizadorService.this, "El GPS ha sido desactivado, activelo", Toast.LENGTH_SHORT).show();
            }
            public void onProviderEnabled(String arg0) {
                         **HERE WANT TO SEND A STRING TO MY INTENT**
            public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
                         **HERE WANT TO SEND A STRING TO MY INTENT**
                    }
        };
        locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 7000, 0, locListener);
    }
    else{
        Toast.makeText(LocalizadorService.this, "El GPS no esta activado, por favor activelo para empezar", Toast.LENGTH_SHORT).show();
        noGPS();
    }
}

private void noGPS(){
    Intent intent = new Intent( android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    startActivity(intent);
}
private void setCurrentLocation(Location arg0){
    if(arg0 != null)
        baseDatos.insertarTablas(arg0.getLatitude(), arg0.getLongitude(), arg0.getSpeed());
}
}
我该怎么办

谢谢大家。

例如,您可以在活动中使用,也可以在服务中使用方法


请参阅如何使用BroadCastReceiver。

您应该使用BroadCastReceiver。您应该在服务类中扩展IntentService而不是服务

将此示例代码放入活动类中

   public class YourClass{
     private IntentFilter yourfilter;
     private ResponseReceiver yourreceiver;


     Override
     public void onCreate(Bundle savedInstanceState) {

      yourfilter = new IntentFilter(ResponseReceiver.MESSAGE);
      yourfilter.addCategory(Intent.CATEGORY_DEFAULT);
      yourreceiver = new ResponseReceiver();
      registerReceiver(yourreceiver, yourfilter);

     Intent i = new Intent(YourActivity.this, YourService.class);
     startService(i);
     }

    public class ResponseReceiver extends BroadcastReceiver {
       public static final String MESSAGE = "MESSAGE STRING";

       @Override
       public void onReceive(Context context, Intent intent) {
       yourEditText.setValue(intent.getStringExtra(YourKey);

      }
    }
并在位置发生变化时将这些代码放入服务类

    public class YourService extends IntentService {

    Intent broadcastIntent = new Intent();
    broadcastIntent.setAction(ResponseReceiver.MESSAGE);
    broadcastIntent.addCategory(Intent.CATEGORY_DEFAULT);
    broadcastIntent.putExtra(yourkey, yourvalue);
    sendBroadcast(broadcastIntent);

我在LocationListener中执行此操作:

public void onProviderDisabled(String arg0) {
                noGPS();
                Toast.makeText(LocalizadorService.this, "El GPS ha sido desactivado, activelo", Toast.LENGTH_SHORT).show();
                intent.setAction(EjercicioBroad.MESSAGE);
                intent.addCategory(Intent.CATEGORY_DEFAULT);
                intent.putExtra("prueba", "PROBANDO");
                sendBroadcast(intent);
            }
这是我对内心世界的看法:

public class EjercicioIniciar extends Activity {

private EditText nombreRuta;
private Button empezar,terminar,aceptar,cancelar;
private EjercicioBD baseDatos;
private boolean rutaEmpezada;
private SharedPreferences misDatos;
private SharedPreferences.Editor editor;
private Chronometer cronometro;

private EditText info;
private StringBuilder builder = new StringBuilder();
private RadioButton andar,correr,bici,coche;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.ejercicio_iniciar);

    baseDatos = EjercicioBD.getEjercicioBD(this);

    empezar = (Button)findViewById(R.id.empezar);

    terminar = (Button)findViewById(R.id.terminar);

    cronometro = (Chronometer)findViewById(R.id.cronometro);
    cronometro.setTextColor(Color.BLUE);

    info = (EditText)findViewById(R.id.editText1);
    info.setFocusable(false);
    info.setShadowLayer(2, 0, 0, Color.BLACK);

    String fontPath = "fonts/DS-DIGIT.ttf";
    Typeface tf = Typeface.createFromAsset(getAssets(), fontPath);
    cronometro.setTypeface(tf);

    misDatos = getApplicationContext().getSharedPreferences("misDatos", Context.MODE_PRIVATE);
    editor = misDatos.edit();
    rutaEmpezada = misDatos.getBoolean("rutaEmpezada", false);
}

@Override
protected void onStart() {
    super.onStart();
    empezar.setOnClickListener(new OnClickListener(){
        @Override
        public void onClick(View v) {
            if(!rutaEmpezada){
                final Dialog dialogo = new Dialog(EjercicioIniciar.this);
                dialogo.setContentView(R.layout.nombre_tabla);
                dialogo.setTitle("Nombre de la ruta");

                nombreRuta = (EditText)dialogo.findViewById(R.id.nombreRuta);

                aceptar = (Button)dialogo.findViewById(R.id.aceptar);
                aceptar.setOnClickListener(new OnClickListener(){
                    @Override
                    public void onClick(View v) {
                        int creada = baseDatos.crearTablas(nombreRuta.getText().toString().trim());

                        if(creada == 1){
                            Intent service = new Intent(EjercicioIniciar.this,LocalizadorService.class);
                            startService(service);

                            cronometro.setBase(SystemClock.elapsedRealtime());

                            Calendar calen = Calendar.getInstance();
                            String actual = ""+calen.get(Calendar.HOUR_OF_DAY)+":"+calen.get(Calendar.MINUTE)+":"+calen.get(Calendar.SECOND);
                            cronometro.start();

                            builder.append("Ha iniciado una ruta "+radioButton().toUpperCase()+", "+nombreRuta.getText().toString().toUpperCase()+" \n"+"A las "+actual+" \n");
                            info.setText(builder);

                            dialogo.dismiss();

                            rutaEmpezada = true;
                            editor.putBoolean("rutaEmpezada", true);
                            editor.commit();
                        }
                    }
                });

                cancelar = (Button)dialogo.findViewById(R.id.cancelar);
                cancelar.setOnClickListener(new OnClickListener(){
                    @Override
                    public void onClick(View v) {
                        dialogo.dismiss();
                    }
                });

                andar = (RadioButton)dialogo.findViewById(R.id.andar);
                correr = (RadioButton)dialogo.findViewById(R.id.correr);
                bici = (RadioButton)dialogo.findViewById(R.id.bici);
                coche = (RadioButton)dialogo.findViewById(R.id.coche);

                dialogo.show();
            }else
                Toast.makeText(EjercicioIniciar.this, "Actualmente has iniciado una ruta", Toast.LENGTH_SHORT).show();
        }
    });
    terminar.setOnClickListener(new OnClickListener(){
        @Override
        public void onClick(View v) {
            if(rutaEmpezada){
                Intent service = new Intent(EjercicioIniciar.this,LocalizadorService.class);
                stopService(service);

                Calendar calen = Calendar.getInstance();
                String actual = ""+calen.get(Calendar.HOUR_OF_DAY)+":"+calen.get(Calendar.MINUTE)+":"+calen.get(Calendar.SECOND);
                builder.append("Fin de su ruta a las "+actual+"\n");
                cronometro.stop();
                builder.append("Duración de la ruta, "+cronometro.getText());
                info.setText(builder);
                cronometro.setBase(SystemClock.elapsedRealtime());
                baseDatos.insertarDatos(builder.toString());
            }

            rutaEmpezada = false;
            editor.putBoolean("rutaEmpezada", false);
            editor.commit();
        }
    });
}

private String radioButton(){
    if(andar.isChecked())
        return andar.getText().toString();
    else if(correr.isChecked())
        return correr.getText().toString();
    else if(bici.isChecked())
        return bici.getText().toString();
    else if(coche.isChecked())
        return coche.getText().toString();
    else
        return "de alguna manera";
}

public class EjercicioBroad extends BroadcastReceiver{
    public static final String MESSAGE = "MESSAGE STRING";
    @Override
    public void onReceive(Context arg0, Intent arg1) {
        info.setText(arg1.getStringExtra("prueba"));
    }
}

}

不工作,编辑文本不变。谢谢大家

而且我忘了说您应该扩展IntentService而不是服务类中的服务。我编辑了我的回答谢谢,现在效果很好,但我的服务扩展了服务,因为如果我扩展了IntentService,服务就不起作用了。谢谢再次光临谢谢,现在很好用,但我的服务会扩展服务,因为如果我扩展了IntentService,服务就不起作用了。谢谢你再次光临。