如何从活动中取消服务中的警报?

时间:2014-02-19 05:26:09

标签: android android-intent broadcastreceiver android-service alarmmanager

我有一个brodcastReciver,一个活动和一个服务,在我发送意图服务设置警报的活动中,警报正在向brodcastReciver发送广播以显示吐司。 但是我无法取消来自activiy的警报。这是我的代码:

public class MainActivity extends Activity {

Button start, stop;

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

    start = (Button) findViewById(R.id.button1);
    stop = (Button) findViewById(R.id.button2);

    start.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            start();
        }
    });

    stop.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            stop();
        }
    });

}

void stop() {
    Intent i = new Intent(this, Reci.class);
    i.putExtra("c", "cancel");
    startService(i);
    Toast.makeText(this, "stop clicked!", Toast.LENGTH_SHORT).show();
}

void start() {
    Intent i = new Intent(this, Serv.class);
    i.putExtra("d", "do");
    startService(i);
    Toast.makeText(this, "start clicked!", Toast.LENGTH_SHORT).show();

}

 }

服务:

public class Serv extends Service {

@Override
public IBinder onBind(Intent intent) {
    // TODO Auto-generated method stub
    return null;
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {

    if (intent.getStringExtra("d").equalsIgnoreCase("do")) {
        Toast.makeText(this, "onStart", Toast.LENGTH_SHORT).show();

        Intent i = new Intent(this, Reci.class)
                .setAction("ir.test.code.Reci.noti");
        PendingIntent pi = PendingIntent.getBroadcast(this, 1234, i, 0);
        G.AM.setRepeating(AlarmManager.RTC_WAKEUP,
                System.currentTimeMillis() + 5000, 5000, pi);

    } else if (intent.getStringExtra("c").equalsIgnoreCase("cancel")) {

        Toast.makeText(this, "onCancel", Toast.LENGTH_SHORT).show();
        Intent i = new Intent(this, Reci.class)
                .setAction("ir.test.code.Reci.noti");
        PendingIntent pi = PendingIntent.getBroadcast(this, 1234, i, 0);
        G.AM.cancel(pi);
    }

    return super.onStartCommand(intent, flags, startId);
}
}

broadcastReciver

public class Reci extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {
    if (intent.getAction().equalsIgnoreCase("ir.test.code.Reci.noti")) {
        Toast.makeText(context, "ir.test.code.Reci.noti",
                Toast.LENGTH_SHORT).show();
    }

}

}

和应用程序类:

public class G extends Application{

public static AlarmManager AM;

@Override
public void onCreate() {
    super.onCreate();
    AM = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
}

}

我该怎么办?

1 个答案:

答案 0 :(得分:0)

由于您提供的类名不同,您没有开始服务...更改void stop()方法

Intent i = new Intent(this,Reci.class);

Intent i = new Intent(this, Serv.class);

主要活动的 stop()方法