简体   繁体   English

从活动到服务的方法调用

[英]method call from activity to service

I am developing an app that fires notifications in the background. 我正在开发一个在后台触发通知的应用程序。 Even when the device is on sleep. 即使设备处于睡眠状态。 I have used the alarm manager and service class. 我已经使用了警报管理器和服务类。 Here is the code- These are in the activity class. 这是代码-这些在活动类中。

public void start(){

scheduleNotification(getNotification(w.getMEAN()),time);
}

private void scheduleNotification(Notification notification, int delay) { private void scheduleNotification(通知通知,int延迟){

    AlarmManager alarmManager = (AlarmManager)getSystemService(getBaseContext().ALARM_SERVICE);
    int d=delay*1000;
    Intent notificationIntent = new Intent(getApplicationContext(), NotificationPublisher.class);
    notificationIntent.putExtra(NotificationPublisher.NOTIFICATION_ID, 1);
    notificationIntent.putExtra(NotificationPublisher.NOTIFICATION, notification);

    PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);

           long futureInMillis = SystemClock.elapsedRealtime() + d;
    alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, futureInMillis, pendingIntent);


}

private Notification getNotification(String content) {
    Intent intent=new Intent(getApplicationContext(),MeaningActivity.class);
     id++;}

   PendingIntent pi=PendingIntent.getActivity(this, 10, intent,PendingIntent.FLAG_CANCEL_CURRENT);

    Notification.Builder builder = new Notification.Builder(this);
    if(id<15){
     builder.setContentIntent(pi);
    builder.setAutoCancel(true);
    notiId++;
    }
    return builder.build();

}

The service is called by intent on button click 通过单击按钮即可调用该服务

case R.id.button1:
{
    String t=ed.getText().toString();
    int time = Integer.parseInt(t);

    savePreferences("switch", s.isChecked());
    if (s.isChecked())
    {
        savePreferences("time", ed.getText().toString());
        Intent intent = new Intent(this,NotifyService.class);
        //intent.putExtra("time",time);
        startService(intent);

    }
    else
    {
        stopService(new Intent(this,NotifyService.class));

    }

This is the notification publisher.java- 这是通知Publisher.java-

public class NotificationPublisher extends BroadcastReceiver {

public static String NOTIFICATION_ID = "notification-id";
public static String NOTIFICATION = "notification";
List<Word> quesList;
int id=0,count =0;
Word w;
public void onReceive(Context context, Intent intent) {

    NotificationManager notificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);


   Notification notification = intent.getParcelableExtra(NOTIFICATION);
  notification.defaults=Notification.DEFAULT_LIGHTS|Notification.DEFAULT_SOUND|Notification.DEFAULT_VIBRATE;
    int id = intent.getIntExtra(NOTIFICATION_ID, 0);
    notificationManager.notify(id, notification);

}

The Service Class is- 服务类别为-

@Override
public IBinder onBind(Intent arg0) {
    //time = arg0.getIntExtra("time",0);
    return null;
}

@Override
public void onCreate() {
    super.onCreate();
    Toast.makeText(this,"Service created", Toast.LENGTH_LONG).show();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    //start();
    // Restart the service if got killed
    sa.start();
    Toast.makeText(this,"Service started", Toast.LENGTH_LONG).show();

    return START_NOT_STICKY;
}

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

The above code shows an error stating the service cannot be called by intent!! 上面的代码显示了一个错误,指出该服务不能被意图调用! Please help me as to how can I fire the notifications even in the background at specified time.. Thanks in advance.. 请帮助我,即使在指定的时间在后台我也如何触发通知。

We have similar cases but mine works. 我们有类似的案例,但是我的作品。 I'll post here my code and you adapt it to yours. 我将在此处发布我的代码,然后您将其修改为适合您的代码。 What you are doing wrong is doing the service "job" in broadcastreceiver and the broadreceiver "job" inside service 您做错了的是在广播接收器中执行服务“作业”,在服务内部执行广泛接收器“作业”

MainActivity Inside onCreate MainActivity内部onCreate

Intent myIntent = new Intent(MainActivity.this, BroadReceiver.class);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 0, myIntent, 0);

    AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
    /*alarmManager.set(AlarmManager.RTC, calendar.getTimeInMillis(), pendingIntent);*/
    alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
            calendar.getTimeInMillis(),
            AlarmManager.INTERVAL_HALF_DAY, pendingIntent);

BroadcastReceiver 广播接收器

public void onReceive(Context context, Intent intent) {
    Intent service1 = new Intent(context, NotifyService.class);
    context.startService(service1);

Service 服务

public int onStartCommand(Intent intent, int flags, int startId) {
    NotificationManager notificationManager = (NotificationManager) this.getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
    Intent intent1 = new Intent(this.getApplicationContext(),MainActivity.class);
    Notification notification = new NotificationCompat.Builder(this)
            .setTicker(getText(R.string.notification_ticker))
            .setSmallIcon(R.drawable.green)
            .setContentTitle(frase())
            .setContentText(getText(R.string.notification_text))
            .setAutoCancel(true)
            .build();
    intent1.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP| Intent.FLAG_ACTIVITY_CLEAR_TOP);
    notificationManager.notify(0, notification);
    return START_STICKY;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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