从活动到服务的方法调用

时间:2015-07-07 15:37:59

标签: android android-intent notifications

我正在开发一个在后台触发通知的应用。即使设备处于睡眠状态。我使用过警报管理器和服务类。这是代码 - 这些都在活动类中。

public void start(){

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

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();

}

按意向点击按钮调用该服务

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));

    }

这是通知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);

}

服务类是 -

@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();
}

以上代码显示错误,指出无法通过意图调用服务! 请帮助我如何在指定时间甚至在后台发送通知.. 提前谢谢..

1 个答案:

答案 0 :(得分:0)

我们有类似的情况,但我的工作。我将在这里发布我的代码并将其改编为您的代码。你做错了是在广播接收者和服务中的广播接收者“工作”中做服务“工作”

onCreate内的MainActivity

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);

广播接收器

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

服务

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;
}