Activate the BroadcastReceiver after a certain time

1

My goal is that the BroadcastReceiver does NOT activate when the app is installed, as it does, but waits for a button to be pressed and after pressing that button it waits for an X time and starts to perform its functions. In this case you must put into vibration the calls that come from a specific number. My logic: At the press of a button, the initProceso () method is called, so that it activates the BroadcastReceiver after 50s (in this case). I already checked that I entered the onReceive () method, writing the in Logcat, and entered. And as I said, it puts my calls on vibration, that's what it does, what I do not want is for it to do it without first pressing a button.

StartProcess Method ():

public void iniciarProceso(){
int i=50;
Intent intent= new Intent(this,Call_Reciver.class);

intent.putExtra (TelephonyManager.EXTRA_STATE, TelephonyManager.EXTRA_STATE);    PendingIntent pendingIntent = PendingIntent.getBroadcast (getApplicationContext (), 15635435, intent, 0);    AlarmManager alarmManager = (AlarmManager) getSystemService (ALARM_SERVICE);    alarmManager.setExact (AlarmManager.RTC_WAKEUP, System.currentTimeMillis () + (i * 1000), pendingIntent);

}

Method onReceive ():

 public void onReceive(Context context, Intent intent) {
    Log.d("onRecive","entro al metodo");
    AudioManager am=(AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
    String estado=intent.getStringExtra(TelephonyManager.EXTRA_STATE );
    if(estado.equals(TelephonyManager.EXTRA_STATE_RINGING)){
        String incomingnumber=intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER);
        if (incomingnumber.equals("unNumeroCualquiera")){
            am.setRingerMode(AudioManager.RINGER_MODE_VIBRATE);
        }

    }
 }

Manifest.xml

         

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
     <activity android:name=".Activity_llamadas">
         <intent-filter>
             <action android:name="android.intent.action.MAIN" />

             <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
     </activity>
         <receiver android:name=".Call_Reciver">
     <intent-filter>
        <action android:name="android.intent.action.PHONE_STATE">

        </action>

     </intent-filter>

    </receiver>

</application>

This is the code of the Activity:

public class Activity_llamadas extends Activity {
Button boton;
EditText editText;
TextView textView;
TextView textView2;
TextView textView3;
int h=0,m=0;
@Override
 public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.layout_llamadas);
    SimpleDateFormat date=  new SimpleDateFormat("mm"); 
    String mhora= date.format(System.currentTimeMillis()); 
    textView3=(TextView)findViewById(R.id.textHoraAct);
    textView3.setText(mhora);
    textView=(TextView)findViewById(R.id.textViewHora);
    textView2=(TextView)findViewById(R.id.textViewhora2);
     boton=(Button)findViewById(R.id.buttonHora);
     boton.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
             stardNotificacion();
             iniciarProceso();
         }
     });
    editText=(EditText)findViewById(R.id.getHora);
    editText.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            mostrarHora(textView);
        }
    });
    editText=(EditText)findViewById(R.id.getHora2);
    editText.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            mostrarHora(textView2);
        }
    });
 }


 public void setTxHora(int h,int m, TextView t){
   t.setText(String.valueOf(h)+": "+String.valueOf(m));
}
private void mostrarHora(final TextView t) {
    final TimePickerDialog timePickerDialog = new TimePickerDialog(this,
            new TimePickerDialog.OnTimeSetListener() {
                @Override
                public void onTimeSet(TimePicker view, int hourOfDay,int minute) {
                 int h= view.getCurrentHour();
                 int  m = view.getCurrentMinute();
                   setTxHora(h,m,t);
                }
            }, h, m, false);
    timePickerDialog.setTitle("Selecciona la hora");
    timePickerDialog.show();
}
private void stardNotificacion(){
    NotificationCompat.Builder mBuilder= (NotificationCompat.Builder) new NotificationCompat.Builder(this);
    mBuilder.setSmallIcon(R.mipmap.ic_launcher);
    mBuilder.setContentTitle("SiyOp");
    mBuilder.setContentText("La aplicion ha comensado a funcionar a las "+getSystemHora());
    NotificationManager notificationManager= (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.notify(0,mBuilder.build());
}


public String getSystemHora(){
SimpleDateFormat date=  new SimpleDateFormat("mm"); 
String mhora= date.format(System.currentTimeMillis()); 
    return mhora;
}

public void startProcess () {     int i = 50;     Intent intent = new Intent (this, Call_Reciver.class);    intent.putExtra (TelephonyManager.EXTRA_STATE, TelephonyManager.EXTRA_STATE);    PendingIntent pendingIntent = PendingIntent.getBroadcast (getApplicationContext (), 15635435, intent, 0);    AlarmManager alarmManager = (AlarmManager) getSystemService (ALARM_SERVICE);    alarmManager.setExact (AlarmManager.RTC_WAKEUP, System.currentTimeMillis () + (i * 1000), pendingIntent); } }

    
asked by Andry_UCI 24.02.2018 в 23:39
source

2 answers

1

First use the Java Timer class to manage the method to be executed after an X time:

 public void TactivarBroucast(){
    Date date= new Date(System.currentTimeMillis());
    Calendar c=Calendar.getInstance();
    c.setTime(date);
    c.set(Calendar.MILLISECOND,5000); //en este caso 5s
    date=c.getTime();
    Timer time= new Timer();
    time.schedule(new Temporisador(),date);
}

Then you have to implement an extended class of TimerAsk and there overwrite the run () method that is executed after a time X.

public class Temporisador extends TimerTask {
Thread myTherad;
@Override
 public void run(){
         myTherad= new MyTherad();
         myTherad.start();
   }
}

Use a Thread to execute a method that is responsible for activating the BroadcastReceiver. To use the method visit this response that tells how to use the method.

public class MyTherad extends Thread {
 @Override
public void run() {
 Activity_llamadas.getmInstanceActivity().activarFuncion();
}
}

And most importantly, the method to activate or deactivate the BroadcastReceiver. Visit the official documentation :

 public  void activarFuncion(){
  ComponentName mReciver= new ComponentName(this,Call_Reciver.class);
    PackageManager pm=getPackageManager();
    pm.setComponentEnabledSetting(mReciver,PackageManager.COMPONENT_ENABLED_STATE_ENABLED,PackageManager.DONT_KILL_APP);
}
    
answered by 05.03.2018 / 04:29
source
0

then add a button to the layout, assuming that the id is boton1, then in your activity you declare, initialize and add the listener:

boton = (Button) findViewById(R.id.boton1);

boton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
    iniciarProceso();
               }
            });

The 50 seconds you mention are already in the AlarmManager .

    
answered by 25.02.2018 в 00:00