应用程序处于非活动状态时,如何创建Forground服务永远不会停止

时间:2018-06-08 09:34:00

标签: android google-maps android-fragmentactivity

我创建了一个应用程序,我想在其中启动服务首次打开应用程序。当应用程序在前台时每隔5或10分钟收到本地通知。但仅在应用程序活动或最近应用程序时收到通知。清除最近时应用程序通知无法接收。我希望此服务继续在设备上运行。

创建的服务和启动服务的示例代码:  启动服务:

404 error

服务:

$labels = array(
    'name'                       => _x( 'Tipos de Productos', 'Taxonomy General Name', 'bonestheme' ),
    'singular_name'              => _x( 'Tipo de Producto', 'Taxonomy Singular Name', 'bonestheme' ),
    'menu_name'                  => __( 'Tipos de Productos', 'bonestheme' ),
    'all_items'                  => __( 'All Items', 'bonestheme' ),
    'parent_item'                => __( 'Parent Item', 'bonestheme' ),
    'parent_item_colon'          => __( 'Parent Item:', 'bonestheme' ),
    'new_item_name'              => __( 'New Item Name', 'bonestheme' ),
    'add_new_item'               => __( 'Add New Item', 'bonestheme' ),
    'edit_item'                  => __( 'Edit Item', 'bonestheme' ),
    'update_item'                => __( 'Update Item', 'bonestheme' ),
    'view_item'                  => __( 'View Item', 'bonestheme' ),
    'separate_items_with_commas' => __( 'Separate items with commas', 'bonestheme' ),
    'add_or_remove_items'        => __( 'Add or remove items', 'bonestheme' ),
    'choose_from_most_used'      => __( 'Choose from the most used', 'bonestheme' ),
    'popular_items'              => __( 'Popular Items', 'bonestheme' ),
    'search_items'               => __( 'Search Items', 'bonestheme' ),
    'not_found'                  => __( 'Not Found', 'bonestheme' ),
    'no_terms'                   => __( 'No items', 'bonestheme' ),
    'items_list'                 => __( 'Items list', 'bonestheme' ),
    'items_list_navigation'      => __( 'Items list navigation', 'bonestheme' ),
);
$args = array(
    'labels'                     => $labels,
    'hierarchical'               => true,
    'public'                     => true,
    'show_ui'                    => true,
    'show_admin_column'          => true,
    'show_in_nav_menus'          => true,
    'show_tagcloud'              => false,
);
register_taxonomy( 'tipos_productos', array( 'producto' ), $args );

}
add_action( 'init', 'ct_tipos_productos', 0 );

清单声明:

    Intent i=new Intent(MainActivity.this,MyService.class);       
    startService(i);

是否可以在应用程序暂停和其他任何操作时始终运行此服务。一段时间后,我的应用程序暂停,服务也暂停或停止。那么如何在后台运行此服务并始终如此。

2 个答案:

答案 0 :(得分:1)

public class MyService extends Service {
static final int NOTIFICATION_ID = 100;

public static boolean isServiceRunning = false;

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

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    if (intent != null && intent.getAction().equals(C.ACTION_START_SERVICE)) {
        startServiceWithNotification();
    }
    else stopMyService();
    return START_STICKY;
}

// In case the service is deleted or crashes some how
@Override
public void onDestroy() {
    isServiceRunning = false;
    super.onDestroy();
}

@Override
public IBinder onBind(Intent intent) {
    // Used only in case of bound services.
    return null;
}


void startServiceWithNotification() {
    if (isServiceRunning) return;
    isServiceRunning = true;

    Intent notificationIntent = new Intent(getApplicationContext(), MyActivity.class);
    notificationIntent.setAction(C.ACTION_MAIN);  // A string containing the action name
    notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
    PendingIntent contentPendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);

    Bitmap icon = BitmapFactory.decodeResource(getResources(), R.drawable.my_icon);

    Notification notification = new NotificationCompat.Builder(this)
            .setContentTitle(getResources().getString(R.string.app_name))
            .setTicker(getResources().getString(R.string.app_name))
            .setContentText(getResources().getString(R.string.my_string))
            .setSmallIcon(R.drawable.my_icon)
            .setLargeIcon(Bitmap.createScaledBitmap(icon, 128, 128, false))
            .setContentIntent(contentPendingIntent)
            .setOngoing(true)
//                .setDeleteIntent(contentPendingIntent)  // if needed
            .build();
    notification.flags = notification.flags | Notification.FLAG_NO_CLEAR;     // NO_CLEAR makes the notification stay when the user performs a "delete all" command
    startForeground(NOTIFICATION_ID, notification);
}

void stopMyService() {
    stopForeground(true);
    stopSelf();
    isServiceRunning = false;
}
}

C =是必须以包名称

开头的字符串

答案 1 :(得分:1)

您可以使用Alarm Manager在特定时间安排未来任务,并在触发时再次设置。 Sample usage或新的api WorkManager可以帮助运行任务甚至应用程序被杀死。

但我认为,当您的应用程序从系统任务中删除时,保持服务正常运行是不好的做法,因为该服务会消耗内存和内存。功率。最好遵循这个Guideline