无法从Alarm Manager调用Broadcast Reveiver

时间:2017-03-30 15:52:00

标签: java android android-studio

我已经搜索了档案,仍然无法解决我的问题。

我试图在几秒钟内接受用户输入,这将调用广播接收器创建一个Toast消息并振动手机。然而,广播接收器从未被调用过,我无法弄明白。我的代码如下。

谢谢!

bingo

广播接收器类:

package com.example.cs984x.alrm;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

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

    Button btn1 = (Button) findViewById(R.id.button1);
    btn1.setOnClickListener(new View.OnClickListener() {
        @Override
         public void onClick(View v) {
            EditText inputSeconds = (EditText) findViewById(R.id.editText1);
            int inputTime = Integer.parseInt(inputSeconds.getText().toString());
            Toast.makeText(MainActivity.this, "The alarm will go off in " + inputTime + " seconds.", Toast.LENGTH_LONG).show();
            AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
            Intent myIntent = new Intent(MainActivity.this, MyReceiver.class);
            myIntent.setAction("com.example.cs984x.alrm.vibrate");
            PendingIntent pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 0, myIntent,0);
            alarmManager.set(AlarmManager.RTC_WAKEUP,   System.currentTimeMillis()+(inputTime*1000), pendingIntent);


        }
    });
}
}

清单:

package com.example.cs984x.alrm;

import android.app.AlarmManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Vibrator;
import android.widget.EditText;
import android.widget.Toast;

import static android.content.Context.ALARM_SERVICE;


public class MyReceiver extends BroadcastReceiver {

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

    Toast.makeText(context, "Your time is up", Toast.LENGTH_LONG).show();
    Vibrator v;
    v= (Vibrator)context.getSystemService(Context.VIBRATOR_SERVICE);
    v.vibrate(2000);

}

}

1 个答案:

答案 0 :(得分:0)

向意图添加行动:

Intent myIntent = new Intent(MainActivity.this, MyReceiver.class);
myIntent.setAction("YourPackageName.YourAction");
            PendingIntent pendingIntent =PendingIntent.getBroadcast(MainActivity.this, 0, myIntent,0);
AndroidManifest中的

<intent-filter>
                <action android:name="YourPackageName.YourAction" />
            </intent-filter>