简体   繁体   中英

Alarm Manager not Triggering Service

I am stuck with a simple Alarm Manager for a few days now. Alarm Manager is expected to start a service but the problem is that it is not starting the service.

My Main Activity :

public class MainActivity extends Activity {
private Button start 
private Button stop

@Override
protected void onCreate (Bundle _savedInstanceState){
super.onCreate (_savedInstanceState);
setContentView(R.layout.main);
initialize(_savedInstanceState);
initializeLogic();
}

private void initialize(Bundle _savedInstanceState) {
start = (Button) findByViewId(R.id.start);
stop = (Button) findByViewId(R.id.stop);

start.setOnClickListener(new View.onClickListener(){
@Override
public void onClick(View _view){
startAlert();
}});

stop.setOnClickListener(new View.onClickListener(){
@Override
public void onClick(View _view){
stopAlert();
}});

private void initializeLogic(){}

@Override
protected void onActivityResult(int _requestCode, int _resultCode, Intent _data){
super.onActivityResult(_requestCode, _resultCode, _data);
switch (_requestCode){
default:
break;
}}

public void startAlert() {
int i = 5;
Intent intent = new Intent(this, MyBroadcastReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this.getApplicationContext(), 234324243, intent, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + (i * 1000), pendingIntent);
Toast.makeText(this, "Alarm set in " + i + " seconds", Toast.LENGTH_LONG).show();
}

public void stopAlert() {
Intent intent = new Intent(this, MyBroadcastReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this.getApplicationContext(), 234324243, intent, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.cancel(pendingIntent);
Toast.makeText(this, "Alarm stopped", Toast.LENGTH_LONG).show();
}

}

My BroadcastReceiver :

public class MyBroadcastReceiver extends BroadcastReceiver 
{    
    @Override
    public void onReceive(Context context, Intent intent) 
    {   

Toast.makeText(context, "Intent received", Toast.LENGTH_LONG).show();
Intent intent = new Intent(this, MyService.class); 
context.startService(intent);
    }
}

My Service :

public class MyService extends Service {
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Toast.makeText(this, "onStartCommand Called", Toast.LENGTH_LONG).show();
        return START_STICKY;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Toast.makeText(this, "onDestroy Called", Toast.LENGTH_LONG).show();
    }
}

I have registered the Service and BroadcastReceiver in manifest. Following a few suggestions on stackoverflow, I tried "MyService" (without.) but it still doesn't work.

<service android:name=".MyService" /> 
<receiver android:name=".MyBroadcastReceiver" />
  1. I tried calling startService and stopService directly from my Start and Stop buttons and it works fine. I get "onStartCommand called" and "onDestroy called".
  2. When I set alarm, it is not triggering the service which means there is some issue with either AlarmManager or BroadcastReceiver. I get "Alarm set in 5 seconds" and "Alarm stopped" texts when I press Start or Stop buttons respectively but I dont get "Intent received" after 5 seconds.

I have tried a few examples available on this forum or other websites but nothing is working for me. Can anyone please highlight what I am doing wrong?

You can try below code, firstly check that you have registered your Broadcast receiver and service as follows:

<service android:name="YOUR_PACKAGE_NAME.MyService"/>
<receiver android:name="YOUR_PACKAGE_NAME.MyBroadcastReceiver"/>

You should also check for some missing braces in your MainActivity.java class. You can compare it with below code for reference

public class MainActivity extends AppCompatActivity {
    private Button start;
    private Button stop;

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

        initialize(savedInstanceState);
    }

    private void initialize(Bundle savedInstanceState)
    {
        start = (Button) findViewById(R.id.start);
        stop = (Button) findViewById(R.id.stop);

        start.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View view)
            {
                startAlert();
            }
        });

        stop.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View view)
            {
            stopAlert();
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data)
    {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode)
        {

        }
    }

    public void startAlert() {
        int i = 5;
        Intent intent = new Intent(this, MyBroadcastReceiver.class);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(this.getApplicationContext(), 234324243, intent, 0);
        AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
        alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + (i * 1000), pendingIntent);
        Toast.makeText(this, "Alarm set in " + i + " seconds", Toast.LENGTH_LONG).show();
    }

    public void stopAlert() {
        Intent intent = new Intent(this, MyBroadcastReceiver.class);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(this.getApplicationContext(), 234324243, intent, 0);
        AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
        alarmManager.cancel(pendingIntent);
        Toast.makeText(this, "Alarm stopped", Toast.LENGTH_LONG).show();
    }
}

And lastly you need to make minor adjustments in your BroadcastReceiver class, where name of intent object should be changed to something else apart from intent as follows:

public class MyBroadcastReceiver extends BroadcastReceiver 
{
    @Override
    public void onReceive(Context context, Intent intent)
    {
        Toast.makeText(context, "Intent received", Toast.LENGTH_LONG).show();
        Intent serviceIntent = new Intent(context, MyService.class);
        context.startService(serviceIntent);
    }
}

Hope this solves your issue.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM