如何通过定时通知启动服务

时间:2019-11-05 15:55:55

标签: android

我现在正在与android一起构建一个可以每天启动通知的应用程序。 现在,我有一个代码,可以在后台服务中添加通知。我知道我必须使用警报服务来选择正确的时间,但我不知道如何每天在同一时间一次修改使其成为服务或通知的代码。

代码( MainActivity.java ):

public class MainActivity extends AppCompatActivity {
    private EditText editTextInput;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    editTextInput = findViewById(R.id.edit_text_input);
}

public void startService(View v) {
    String input = editTextInput.getText().toString();

    Intent serviceIntent = new Intent(this, ExampleService.class);
    serviceIntent.putExtra("inputExtra", input);

    ContextCompat.startForegroundService(this, serviceIntent);
}

public void stopService(View v) {
    Intent serviceIntent = new Intent(this, ExampleService.class);
    stopService(serviceIntent);
}
}

App.java

public class App extends Application {
    public static final String CHANNEL_ID = "exampleServiceChannel";

@Override
public void onCreate() {
    super.onCreate();

    createNotificationChannel();
}

private void createNotificationChannel() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        NotificationChannel serviceChannel = new NotificationChannel(
                CHANNEL_ID,
                "Example Service Channel",
                NotificationManager.IMPORTANCE_DEFAULT
        );

        NotificationManager manager = getSystemService(NotificationManager.class);
        manager.createNotificationChannel(serviceChannel);
    }
}
}

服务:

public class ExampleService extends Service {

@Override
public void onCreate() {
    super.onCreate();
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    String input = intent.getStringExtra("inputExtra");

    Intent notificationIntent = new Intent(this, MainActivity.class);
    PendingIntent pendingIntent = PendingIntent.getActivity(this,
            0, notificationIntent, 0);

    Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
            .setContentTitle("Example Service")
            .setContentText(input)
            .setSmallIcon(R.drawable.ic_android_black_24dp)
            .setContentIntent(pendingIntent)
            .build();

    startForeground(1, notification);

    //do heavy work on a background thread
    //stopSelf();

    return START_NOT_STICKY;
}

@Override
public void onDestroy() {
    super.onDestroy();
}

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

感谢您的帮助。

2 个答案:

答案 0 :(得分:0)

您不需要服务即可显示通知。将警报管理器与广播接收器一起使用,并写下您的代码以在广播接收器的onReceive中显示警报。

答案 1 :(得分:0)

警报管理器应用程序以显示通知:

Mainactivity.java:

TimePicker timePicker;


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

    //getting the timepicker object
    timePicker = (TimePicker) findViewById(R.id.timePicker);
    Button btn=(Button)findViewById(R.id.buttonAlarm);
    //attaching clicklistener on button
    btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            //We need a calendar object to get the specified time in millis
            //as the alarm manager method takes time in millis to setup the alarm
            Calendar calendar = Calendar.getInstance();
            if (android.os.Build.VERSION.SDK_INT >= 23) {
                calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH),
                        timePicker.getHour(), timePicker.getMinute(), 0);
            } else {
                calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH),
                        timePicker.getCurrentHour(), timePicker.getCurrentMinute(), 0);
            }


            setAlarm(calendar.getTimeInMillis());
        }
    });
}

private void setAlarm(long time) {
    //getting the alarm manager
    AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);

    //creating a new intent specifying the broadcast receiver
    Intent i = new Intent(this, MyAlarm.class);

    //creating a pending intent using the intent
    PendingIntent pi = PendingIntent.getBroadcast(this, 0, i, 0);

    //setting the repeating alarm that will be fired every day
    am.setRepeating(AlarmManager.RTC, time, AlarmManager.INTERVAL_DAY, pi);
    Toast.makeText(this, "Alarm is set", Toast.LENGTH_SHORT).show();
}

Myalarm.java:

public class MyAlarm extends BroadcastReceiver {

//the method will be fired when the alarm is triggerred
@Override
public void onReceive(Context context, Intent intent) {

    //you can check the log that it is fired
    //Here we are actually not doing anything
    //but you can do any task here that you want to be done at a specific time everyday
    addNotification(context);
    Log.d("MyAlarmBelal", "Alarm just fired");
}
private void addNotification(Context context) {
    // Builds your notification
    NotificationCompat.Builder builder=new NotificationCompat.Builder(context);
    builder.setSmallIcon(R.mipmap.ic_launcher_round);
    builder.setContentTitle("John's Android Studio Tutorials");
    builder.setContentText("A video has just arrived!");

    // Creates the intent needed to show the notification
    Intent notificationIntent = new Intent();
    PendingIntent contentIntent = PendingIntent.getActivity(context , 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
    builder.setContentIntent(contentIntent);

    // Add as notification
    NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
    manager.notify(0, builder.build());
}
}
相关问题