AlarmManager无法启动服务

时间:2016-12-10 22:55:41

标签: java android

之前,警报管理器正在工作。我认为我没有改变任何东西,但现在它根本没有改变。

以下是我设置闹钟管理器的代码:

public class UpdateScoresService extends IntentService {

    public int countChanged;
    Context context = this;

    public UpdateScoresService() {
        super("UpdateScoresService");
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        Log.e("onHandleIntent", "grabbing scores");
        countChanged = new GetAnimeScores(getApplicationContext()).refreshScores();

        if(countChanged>0){ //Display notification if any scores changed
            Log.d("Creating notification", " ");
            NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
            builder.setSmallIcon(R.drawable.ic_timeline_white_24dp);
            builder.setContentTitle("MAL Score Tracker");
            builder.setAutoCancel(true);

            if(countChanged==1){
                builder.setContentText("1 score changed since you were gone!");
            }else{
                builder.setContentText(countChanged+" scores changed since you were gone!");
            }

            Intent intent1 = new Intent(context, MainActivity.class);
            TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
            stackBuilder.addParentStack(MainActivity.class);
            stackBuilder.addNextIntent(intent1);
            PendingIntent pendingIntent = stackBuilder.getPendingIntent(0,PendingIntent.FLAG_UPDATE_CURRENT);
            builder.setContentIntent(pendingIntent);

            NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
            notificationManager.notify(0,builder.build());
        }
    }
}
}

UpdateScoresService在这里:

<StackPanel Orientation="Horizontal" VerticalAlignment="Top">
    <Label>Customer name:</Label>
    <TextBox Text="{Binding Customer.Name, UpdateSourceTrigger=PropertyChanged}" Width="136"/>
    <Button x:Name="UpdateClick">Update</Button>
</StackPanel>

登录SettingsActivity打印,但不打印从服务登录onHandleIntent。我不确定有什么问题。

1 个答案:

答案 0 :(得分:0)

最好有BroadcastReceiver负责启动服务。它的代码应如下所示:

创建BroadcastReceiver类:

public class ReceiverToStartService extends BroadcastReceiver{

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

        Intent i = new Intent(context, UpdateScoresService.class);
        ComponentName service = context.startService(i);
    }
}

在你的清单中注册接收者:

<receiver android:name=".ReceiverToStartService"/>

现在更改您要传递给PendingIntent的活动中的意图:

intent  = new Intent(context, ReceiverToStartService.class);
recurringDownload = PendingIntent.getService(context, 0, intent, 0);