Muy buenas a todos, he podido leer algo acerca de como lanzar una
Activity desde un BroadcastReceiver, de ahí llegue hasta el punto
donde me encuentro, realmente no pude encontrar el porque mi
aplicación se cierra.
Paso a explicar la idea de la aplicación que, a modo de ejercicio y
aprendizaje estoy haciendo:
La misma consta de una pantalla principal "main" que solo posee un
ToggleButton cuando este cambia de estado a "Encendido" inicia mi
servicio, al pasar a "Apagado" hace lo propio y detiene lo detiene.
Todo esto funciona correctamente, puedo cerrar la aplicación y el
servicio queda corriendo sin problemas y lo puedo detener cuando lo
desee abriendo nuevamente la aplicación.
Ahora bien el servicio "MyService" se queda esperando que el estado
del teléfono cambie, para cada cambio con un mensaje tipo Toast puedo
verificar si mi servicio esta activo, hasta ahí me funciono todo
perfecto salvo cuando agregue las lineas que según algunos foros deben
utilizarse para poder hacer lo que deseo, quiero que cuando el
teléfono reciba una llamada se ejecute una Activity que contiene
simplemente una imagen, ahí es donde la aplicación se cierra, puedo
comprobarlo porque si solo dejo el Toast va de maravilla, me dice que
entro una llamada y hasta el numero telefónico entrante.
Simplificando para hacer lo ultimo cree una clase que recibe el
contexto e intenta lanzar la Activity en cuestión "NewScreen"
Aquí dejo el código de la aplicación, espero puedan ayudarme ya que
llevo varios días si llegar a un gran avance
--------------------------------------------------------------------------- -------------------------------------------
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="xx.com.xxxxx.myservice"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="4" />
<uses-permission android:name="android.permission.VIBRATE"></uses-
permission>
<uses-permission
android:name="android.permission.READ_PHONE_STATE" ></uses-permission>
<application
android:icon="@
drawable/icon"
android:label="@
string/app_name">
<activity
android:label="@
string/app_name"
android:screenOrientation="portrait" android:name="Main">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category
android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:screenOrientation="portrait"
android:name="NewScreen">
</activity>
<service
android:label="My Service"
android:enabled="true"
android:name="MyService">
</service>
</application>
</manifest>
--------------------------------------------------------------------------- -------------------------------------------
public class Main extends Activity{
ToggleButton buttonStatus;
ActivityManager ActivityMan;
List<RunningServiceInfo> RunningServices;
boolean isMyServiceRunning = false;
@
override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ActivityMan = (ActivityManager) this.getSystemService
(ACTIVITY_SERVICE);
RunningServices =
ActivityMan.getRunningServices(Integer.MAX_VALUE);
buttonStatus = (ToggleButton) findViewById(R.id.buttonStatus);
buttonStatus.setOnCheckedChangeListener(listener);
checkServiceRuning();
showStatusService();
}
OnCheckedChangeListener listener = new OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
showStatusService();
MyService(isChecked);
}
};
public void checkServiceRuning(){
for (RunningServiceInfo runningServiceInfo : RunningServices)
{
if
(runningServiceInfo.service.getClassName().equals( MyService.class.getName() ))
{
isMyServiceRunning = true;
buttonStatus.setChecked(true);
}
}
}
public void MyService(boolean status){
if (status)
startService(new Intent(getApplicationContext(),
MyService.class));
else
stopService(new Intent(getApplicationContext(),
MyService.class));
}
public void showStatusService(){
if(buttonStatus.isChecked()) {
Toast.makeText(Main.this, "Service ON",
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(Main.this, "Service OFF",
Toast.LENGTH_SHORT).show();
}
}
}
--------------------------------------------------------------------------- -------------------------------------------
public class MyService extends Service {
BroadcastReceiver phoneStateChangeReceiver;
Bundle extras;
String phoneNumber;
@
override
public void onCreate() {
phoneStateChangeReceiver = new PhoneStateChangeReceiver();
registerReceiver(phoneStateChangeReceiver, new
IntentFilter(android.telephony.TelephonyManager.AC TION_PHONE_STATE_CHANGED) );
}
public void onDestroy() {
unregisterReceiver(phoneStateChangeReceiver);
}
public class PhoneStateChangeReceiver extends BroadcastReceiver {
@
override
public void onReceive(Context context, Intent intent) {
String newState = intent.getStringExtra("state");
Toast.makeText(getApplicationContext(), "Phone state: " + newState,
Toast.LENGTH_SHORT).show();
if
( android.telephony.TelephonyManager.EXTRA_STATE_RIN GING.equals(newState) )
{
extras = intent.getExtras();
phoneNumber =
extras.getString(TelephonyManager.EXTRA_INCOMING_N UMBER);
Toast.makeText(getApplicationContext(), "Phone number: " +
phoneNumber, Toast.LENGTH_SHORT).show();
showScreen(getApplicationContext());
}
}
}
public void showScreen(Context context){
Intent NewScreen = new Intent(context, MyScreen.class);
NewScreen.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
NewScreen.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP );
context.startActivity(NewScreen);
}
@
override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}