2014-05-21 3 views
0

Я уже два дня (около 12 часов) ищу информацию о будильниках и трансляторе, и мне удается заставить его работать, но я экспериментирую с действительно странной проблемой.AlarmManager не работает

Я пытаюсь запустить службу, которая затем запускает intenservice. Иногда это работает, но потом просто перестает работать. Это действительно странно, но решение вызывает широковещательный приемник по намерению тревоги, а затем меняет класс на сервисный. Как я уже сказал, это действительно странно, но после этого он работает некоторое время (до третьего или четвертого компиляции, затем он перестает работать снова).

Я просто не могу понять, почему это работает иногда, но это не некоторые другие.

Вот мой BroadcastReceiver класс:

общественного класса BootCompletat расширяет BroadcastReceiver {

@Override 
public void onReceive(Context context, Intent intent) { 

    if ((intent.getAction() != null) && (intent.getAction().equals("android.intent.action.BOOT_COMPLETED"))){ 
     Log.d("BOOT COMPLETAT!! Inicio el servei","Iniciat"); 
     context.startService(new Intent(context, ServeiConnexio.class));  
    }else if((intent.getAction() != null) && (intent.getAction().equals("com.example.primerprograma.ALARMA_DISPARADA"))){ 
     Log.d("ALARMA!! Inicio el servei","Iniciat"); 
     context.startService(new Intent(context, ServeiConnexio.class)); 
    } 
    Log.d("Detecto un esdeveniment: ",intent.getAction().toString()); 
    //Toast.makeText(context, "Detecto un esdeveniment", Toast.LENGTH_SHORT).show(); 
} 

public static void SetAlarm(Context context){ 
    Log.d("Crido l'alarma","Cridant"); 
    int act = 1; 
    //Toast.makeText(context, "Crido l'alarma", Toast.LENGTH_LONG).show(); 
    AlarmManager am=(AlarmManager)context.getSystemService(Context.ALARM_SERVICE); 
    // When it stops working, I change on the line below ServeiConnexio.class for BootCompletat.class 
    // Then it starts working (it updates every second) and I change it back to ServeiConnexio.class. After that, it works for a while (???) 
    Intent i = new Intent(context, ServeiConnexio.class); 
    i.setAction("com.example.primerprograma.ALARMA_DISPARADA"); 
    PendingIntent pi = PendingIntent.getBroadcast(context, 0, i, 0); 
    am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 1000 * 60 * act, pi); // Millisec * Second * Minute 
} 

}

Вот мой ServiceClass:

общественного класса ServeiConnexio расширяет службы {

// Definim les variables que utilitzarem 
private ArrayList<String> params_conn = new ArrayList<String>(); 
private String[] conn_params = null; 
private ServidorsSQL factory = null; 
private Funcions funcions = new Funcions(); 

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

public void onStart(Intent intent, int startid) { 
    //Toast.makeText(this, "Iniciant servei", Toast.LENGTH_LONG).show(); 
    Log.d("SERVEI - He entrat a onStart", "onStart"); 

    factory = new ServidorsSQL(this,"Servidors", null,9); 
    Log.d("Carrego info de tots els servidors","Carrego dades"); 
    funcions.llegeix(params_conn, factory); 

    // Calling alarm 
    Log.d("Executo alarma",""); 
    BootCompletat.SetAlarm(this); 

    // Search for data to create the intent 
    // The loop works perfectly and the intentservice works like charm 
    // So it doesn't have anything to do with the alarm not working 
    for(int m=0;m<params_conn.size();m++){ 
     Log.d("Entro al servei: " + Integer.toString(m),"Executo ConnectaSSH"); 
     // Partim els resultats en un array per poder-los passar a l'intent 

     conn_params = params_conn.get(m).split("\n"); 

     Intent i = new Intent(); 
     i.putExtra("Resultats", conn_params); 
     i.setClass(ServeiConnexio.this,IntentServeiConnexio.class); 
     i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
     Log.d("Crido activity ConnectaSSH: " + Integer.toString(m),"IntentServeiConnexio"); 
     startService(i); 
     Log.d("Finalitzo activity IntentServeiConnexio: ",Integer.toString(m)); 
    } 
} 

@Override 
public void onDestroy() { 
     Toast.makeText(getApplicationContext(), "Servei destruït",Toast.LENGTH_SHORT).show(); 
     super.onDestroy(); 
} 

}

Любая помощь будет оценена, я отчаялась

ответ

0

этот код работает для меня:

// Start service using AlarmManager 
    try { 

     Calendar cal = Calendar.getInstance(); 
     cal.add(Calendar.SECOND, 10); 

     Intent intent = new Intent(this, YourService.class); 

     PendingIntent pintent = PendingIntent.getService(this, 0, intent, 0); 

     AlarmManager alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE); 



     alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), 20000 , pintent); //20 second 
     startService(new Intent(getBaseContext(), YourService.class)); 
     Log.d(tag, "Timer Started.."); 


} catch (Exception e) { 
    Log.d(tag, "timer error: "+e); 
    e.printStackTrace(); 
} 
+0

Отлично, я не уверен, где разница между вашим кодом и моя, но твоя работа как шарм. спасибо. – user3424020

Смежные вопросы