关闭我的应用程序时,IntentService不起作用

时间:2017-08-02 11:53:19

标签: android firebase firebase-realtime-database intentservice

我有这个:

public class MyIntentServiceBiz extends IntentService {


private AlarmManager alarmManager;
private boolean started;
private PendingIntent pendingIntent;
private FirebaseDatabase database;
private SharedPreferences sp;
private long bizId =0;
private long update=0;
private NotificationManager mNotificationManager;


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

@Override
public void onCreate() {
    super.onCreate();
    alarmManager = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
    database = FirebaseDatabase.getInstance();
    sp = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
    bizId = sp.getLong("bizId",0);
    update = sp.getLong("update",0);
}


@Override
protected void onHandleIntent(Intent intent) {

    new Timer().schedule(new TimerTask() {
        @Override
        public void run() {
            String ns = Context.NOTIFICATION_SERVICE;
            NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);


            int icon = R.drawable.check;
            CharSequence tickerText = "Pet Parrot";
            long when = System.currentTimeMillis();

            NotificationCompat.Builder builder =
                    new NotificationCompat.Builder(MyIntentServiceBiz.this)
                            .setSmallIcon(R.drawable.check)
                            .setContentTitle("My Notification Title")
                            .setContentText("Something interesting happened");
            int NOTIFICATION_ID = 12345;

            Intent targetIntent = new Intent(MyIntentServiceBiz.this, MyIntentServiceBiz.class);
            PendingIntent contentIntent = PendingIntent.getActivity(MyIntentServiceBiz.this, 0, targetIntent, PendingIntent.FLAG_UPDATE_CURRENT);
            builder.setContentIntent(contentIntent);
            NotificationManager nManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
            nManager.notify(NOTIFICATION_ID, builder.build());

            // DO YOUR STUFF HERE
            DatabaseReference ref = database.getReference("Biz").child(""+bizId);
            ref.addListenerForSingleValueEvent(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {
                    long newUpdate = dataSnapshot.child("update").getValue(Long.class);
                    if (update < newUpdate){
                        Toast.makeText(MyIntentServiceBiz.this, "Updated ", Toast.LENGTH_SHORT).show();
                    }
                }

                @Override
                public void onCancelled(DatabaseError databaseError) {

                }
            });
        }
    }, 5000);


}

}

即使我关闭应用程序,也能看到通知后即可。 所以即使应用程序关闭,这个意图服务也应该在android上运行。

现在我可以看到通知,但只有当应用程序处于启用状态或后台时才会看到通知。 我想要通知,而不需要运行应用程序。

拜托,帮助。

3 个答案:

答案 0 :(得分:0)

您的服务运行正常,只是验证方法不正确。您正尝试从后台线程显示Toast。尝试使用:

Log.i(service.class.getName(),"this is working");

此外,如果您想显示来自服务的通知消息,则应使用

private NotificationManager mNotificationManager;

编辑:这是我测试的服务,它可以按你的需要工作。 使用方法:

this.startService(MyIntentServiceBiz.getIntent(this));

IntentService类:

public class MyIntentServiceBiz extends IntentService {


    private AlarmManager alarmManager;
    private boolean started;
    //    private PendingIntent pendingIntent;
//    private FirebaseDatabase database;
//    private SharedPreferences sp;
    private long bizId = 0;
    private long update = 0;

    public static Intent getIntent(Context context) {
        Intent intent = new Intent(context, MyIntentServiceBiz.class);

        return intent;
    }

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

    @Override
    public void onCreate() {
        super.onCreate();
//        alarmManager = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
//        database = FirebaseDatabase.getInstance();
//        sp = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
//        bizId = sp.getLong("bizId",0);
//        update = sp.getLong("update",0);
    }


    @Override
    protected void onHandleIntent(Intent intent) {
        new Timer().schedule(new TimerTask() {
            @Override
            public void run() {
                Log.i(MyIntentServiceBiz.class.getName(), "working");
            }
        }, 5000);
//        if (! started) {
//            started = true;
//
//            // Call the service periodically every 15 minutes
//            pendingIntent = PendingIntent.getService(
//                    getApplicationContext(),
//                    0,
//                    intent,
//                    PendingIntent.FLAG_UPDATE_CURRENT);
//
//            alarmManager.setRepeating(
//                    AlarmManager.ELAPSED_REALTIME,
//                    15000,
//                    15000,
//                    pendingIntent);
//        }
//
//        Toast.makeText(this, "background service", Toast.LENGTH_SHORT).show();
//
//        // DO YOUR STUFF HERE
//        DatabaseReference ref = database.getReference("Biz").child(""+bizId);
//        ref.addListenerForSingleValueEvent(new ValueEventListener() {
//            @Override
//            public void onDataChange(DataSnapshot dataSnapshot) {
//                long newUpdate = dataSnapshot.child("update").getValue(Long.class);
//                if (update < newUpdate){
//                    Toast.makeText(MyIntentServiceBiz.this, "Updated ", Toast.LENGTH_SHORT).show();
//                }
//            }
//
//            @Override
//            public void onCancelled(DatabaseError databaseError) {
//
//            }
//        });
    }
}

编辑2:这是清单声明

<service
    android:name=".services.MyIntentServiceBiz"
    android:exported="false" />

答案 1 :(得分:0)

试试这个BroadcastReceiver

public class TrackingReceiver extends BroadcastReceiver {

// todo do time lies for scheduletime
private static final long ScheduleTime = 1000 * 1800;
private static java.text.DateFormat frm = new SimpleDateFormat(
        "MM/dd/yyyy HH:mm:ss");

static void scheduleAlarms(Context paramContext) {
    Date alramTime = null;
    try {
        alramTime = (Date) frm.parse((Calendar.getInstance().get(
                Calendar.MONTH) + 1)
                + "/"
                + Calendar.getInstance().get(Calendar.DAY_OF_MONTH)
                + "/"
                + Calendar.getInstance().get(Calendar.YEAR)
                + " "
                + " 00:00:00");

    } catch (ParseException e) {
        e.printStackTrace();

        try {
            alramTime = (Date) frm.parse((Calendar.getInstance().get(
                    Calendar.MONTH) + 1)
                    + "/"
                    + Calendar.getInstance().get(Calendar.DAY_OF_MONTH)
                    + "/"
                    + Calendar.getInstance().get(Calendar.YEAR)
                    + " 00:00:00");

        } catch (ParseException ex) {
            ex.printStackTrace();
        }
    }

    long diff = 0;
    if (alramTime.getTime() > Calendar.getInstance().getTimeInMillis())
        diff = alramTime.getTime()
                - Calendar.getInstance().getTimeInMillis();
    else
        diff = ScheduleTime
                - (Calendar.getInstance().getTimeInMillis() - alramTime
                        .getTime());

    AlarmManager localAlarmManager = (AlarmManager) paramContext
            .getSystemService(Context.ALARM_SERVICE);
    PendingIntent localPendingIntent = PendingIntent.getService(
            paramContext, 0, new Intent(paramContext,
                    SyncTrackingData.class), 0);

    localAlarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME, diff
            + SystemClock.elapsedRealtime(), ScheduleTime,
            localPendingIntent);
}

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


    scheduleAlarms(context);
    context.startService(new Intent(context, MyIntentServiceBiz.class));
}

}

也在清单文件中声明 //添加权限

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>

//添加接收器

 <receiver
        android:name=".TrackingReceiver"
        android:enabled="true">
        <intent-filter>
            <action android:name="android.intent.action.BOOT_COMPLETED"/>
        </intent-filter>
    </receiver>

答案 2 :(得分:-1)

前台服务是最好的方式。因为它不是系统在内存不足时杀死的候选者。这是一个很好的例子:http://www.truiton.com/2014/10/android-foreground-service-example/